Compare commits

..

124 Commits

Author SHA1 Message Date
dependabot[bot]
9f4f5df05d build(deps): bump pagehelper-spring-boot-starter from 1.4.0 to 1.4.1
Bumps pagehelper-spring-boot-starter from 1.4.0 to 1.4.1.

---
updated-dependencies:
- dependency-name: com.github.pagehelper:pagehelper-spring-boot-starter
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-19 23:24:14 +08:00
dependabot[bot]
c51798c87f build(deps): bump okhttp from 4.9.2 to 4.9.3
Bumps [okhttp](https://github.com/square/okhttp) from 4.9.2 to 4.9.3.
- [Release notes](https://github.com/square/okhttp/releases)
- [Changelog](https://github.com/square/okhttp/blob/master/CHANGELOG.md)
- [Commits](https://github.com/square/okhttp/compare/parent-4.9.2...parent-4.9.3)

---
updated-dependencies:
- dependency-name: com.squareup.okhttp3:okhttp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-19 23:24:01 +08:00
dependabot[bot]
8f6a75cd6a build(deps): bump protostuff-core from 1.1.6 to 1.2.2
Bumps protostuff-core from 1.1.6 to 1.2.2.

---
updated-dependencies:
- dependency-name: com.dyuproject.protostuff:protostuff-core
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-19 23:23:50 +08:00
dependabot[bot]
7e652e105b build(deps): bump protostuff-runtime from 1.1.6 to 1.2.2
Bumps protostuff-runtime from 1.1.6 to 1.2.2.

---
updated-dependencies:
- dependency-name: com.dyuproject.protostuff:protostuff-runtime
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-19 23:23:38 +08:00
dependabot[bot]
932333b595 build(deps-dev): bump junit-vintage-engine from 5.7.1 to 5.8.2
Bumps [junit-vintage-engine](https://github.com/junit-team/junit5) from 5.7.1 to 5.8.2.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.7.1...r5.8.2)

---
updated-dependencies:
- dependency-name: org.junit.vintage:junit-vintage-engine
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-02-19 23:23:24 +08:00
dependabot[bot]
2f122234fb build(deps): bump h2 from 1.4.200 to 2.0.206
Bumps [h2](https://github.com/h2database/h2database) from 1.4.200 to 2.0.206.
- [Release notes](https://github.com/h2database/h2database/releases)
- [Commits](https://github.com/h2database/h2database/compare/version-1.4.200...version-2.0.206)

---
updated-dependencies:
- dependency-name: com.h2database:h2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-07 09:05:38 +08:00
dependabot[bot]
7ba4137bf1 build(deps): bump lombok from 1.18.20 to 1.18.22
Bumps [lombok](https://github.com/projectlombok/lombok) from 1.18.20 to 1.18.22.
- [Release notes](https://github.com/projectlombok/lombok/releases)
- [Changelog](https://github.com/projectlombok/lombok/blob/master/doc/changelog.markdown)
- [Commits](https://github.com/projectlombok/lombok/compare/v1.18.20...v1.18.22)

---
updated-dependencies:
- dependency-name: org.projectlombok:lombok
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-01 12:14:12 -05:00
dependabot[bot]
850349bac0 build(deps): bump spring-boot-starter-parent from 2.5.5 to 2.5.6
Bumps [spring-boot-starter-parent](https://github.com/spring-projects/spring-boot) from 2.5.5 to 2.5.6.
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.5.5...v2.5.6)

---
updated-dependencies:
- dependency-name: org.springframework.boot:spring-boot-starter-parent
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-01 12:13:53 -05:00
禾几海
f7f8f41759 Update sync.yml 2021-11-02 01:04:38 +08:00
a2258d183f 修复找不到测试用例的异常 2021-11-02 01:00:29 +08:00
dependabot[bot]
68e2a4772c build(deps): bump pagehelper-spring-boot-starter from 1.3.1 to 1.4.0
Bumps pagehelper-spring-boot-starter from 1.3.1 to 1.4.0.

---
updated-dependencies:
- dependency-name: com.github.pagehelper:pagehelper-spring-boot-starter
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-01 11:38:09 -05:00
dependabot[bot]
f6e67aca07 build(deps): bump spring-boot-maven-plugin from 2.5.5 to 2.5.6
Bumps [spring-boot-maven-plugin](https://github.com/spring-projects/spring-boot) from 2.5.5 to 2.5.6.
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.5.5...v2.5.6)

---
updated-dependencies:
- dependency-name: org.springframework.boot:spring-boot-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-01 11:37:22 -05:00
禾几海
d667689f1a 修复不兼容项 2021-10-05 16:54:23 +08:00
dependabot[bot]
6cfa132a66 build(deps): bump spring-boot-starter-parent from 2.1.3.RELEASE to 2.5.5
Bumps [spring-boot-starter-parent](https://github.com/spring-projects/spring-boot) from 2.1.3.RELEASE to 2.5.5.
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.1.3.RELEASE...v2.5.5)

---
updated-dependencies:
- dependency-name: org.springframework.boot:spring-boot-starter-parent
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 16:54:23 +08:00
dependabot[bot]
359d3c2664 build(deps): bump pagehelper-spring-boot-starter from 1.3.0 to 1.3.1
Bumps pagehelper-spring-boot-starter from 1.3.0 to 1.3.1.

---
updated-dependencies:
- dependency-name: com.github.pagehelper:pagehelper-spring-boot-starter
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 16:24:23 +08:00
dependabot[bot]
243bbe8b20 build(deps): bump springfox-swagger2 from 2.9.2 to 3.0.0
Bumps [springfox-swagger2](https://github.com/springfox/springfox) from 2.9.2 to 3.0.0.
- [Release notes](https://github.com/springfox/springfox/releases)
- [Changelog](https://github.com/springfox/springfox/blob/master/docs/release-notes.md)
- [Commits](https://github.com/springfox/springfox/compare/2.9.2...3.0.0)

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 16:24:02 +08:00
dependabot[bot]
306f695f3f build(deps): bump jaxb-core from 2.3.0.1 to 3.0.2
Bumps jaxb-core from 2.3.0.1 to 3.0.2.

---
updated-dependencies:
- dependency-name: com.sun.xml.bind:jaxb-core
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 16:09:20 +08:00
dependabot[bot]
6d5b69ecd6 build(deps): bump jaxb-impl from 3.0.0 to 3.0.2
Bumps jaxb-impl from 3.0.0 to 3.0.2.

---
updated-dependencies:
- dependency-name: com.sun.xml.bind:jaxb-impl
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 16:04:22 +08:00
dependabot[bot]
d7fdd3ec23 build(deps): bump junit from 4.13.1 to 4.13.2
Bumps [junit](https://github.com/junit-team/junit4) from 4.13.1 to 4.13.2.
- [Release notes](https://github.com/junit-team/junit4/releases)
- [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.13.1.md)
- [Commits](https://github.com/junit-team/junit4/compare/r4.13.1...r4.13.2)

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 16:04:11 +08:00
禾几海
a6c9405499 Update sync.yml 2021-10-05 15:56:40 +08:00
禾几海
f090264066 Update sync.yml 2021-10-05 15:49:44 +08:00
禾几海
2d1c1a7208 Update build.yml 2021-10-05 15:44:20 +08:00
禾几海
9997caaedf Create sync.yml 2021-10-05 15:43:38 +08:00
dependabot[bot]
4ed8939945 build(deps): bump druid from 1.2.6 to 1.2.8
Bumps [druid](https://github.com/alibaba/druid) from 1.2.6 to 1.2.8.
- [Release notes](https://github.com/alibaba/druid/releases)
- [Commits](https://github.com/alibaba/druid/compare/1.2.6...1.2.8)

---
updated-dependencies:
- dependency-name: com.alibaba:druid
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 15:32:46 +08:00
dependabot[bot]
2c287b5c08 build(deps): bump okhttp from 4.9.1 to 4.9.2
Bumps [okhttp](https://github.com/square/okhttp) from 4.9.1 to 4.9.2.
- [Release notes](https://github.com/square/okhttp/releases)
- [Changelog](https://github.com/square/okhttp/blob/master/CHANGELOG.md)
- [Commits](https://github.com/square/okhttp/compare/parent-4.9.1...parent-4.9.2)

---
updated-dependencies:
- dependency-name: com.squareup.okhttp3:okhttp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 15:32:33 +08:00
禾几海
d07b1f9b96 Update build.yml 2021-10-05 15:24:38 +08:00
dependabot[bot]
4879a4bb79 build(deps): bump spring-boot-maven-plugin from 2.1.3.RELEASE to 2.5.5
Bumps [spring-boot-maven-plugin](https://github.com/spring-projects/spring-boot) from 2.1.3.RELEASE to 2.5.5.
- [Release notes](https://github.com/spring-projects/spring-boot/releases)
- [Commits](https://github.com/spring-projects/spring-boot/compare/v2.1.3.RELEASE...v2.5.5)

---
updated-dependencies:
- dependency-name: org.springframework.boot:spring-boot-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 15:23:51 +08:00
禾几海
027b81c006 close #94 2021-10-03 16:15:42 +08:00
禾几海
1c976f1310 EnvironmentUtil工具类 2021-10-03 16:04:53 +08:00
禾几海
a544e1bd54 delete file 2021-10-03 16:04:53 +08:00
禾几海
5a00e6c62f 记录项目配置,修改配置项的获取方式
- new class ` CommonEnvPostProcessor `
- remove ` @value `
- make JwtUtil's method static
2021-10-03 16:04:48 +08:00
禾几海
07e84ab875 修改版本号 2021-10-03 15:09:26 +08:00
禾几海
a6c91fc3f1 close [#93] 2021-10-03 14:58:48 +08:00
禾几海
fb88f90b70 添加banner 2021-10-03 14:57:56 +08:00
禾几海
692ce19320 ci 2021-10-03 14:15:05 +08:00
禾几海
5c7e3344c9 调整配置文件 2021-10-03 14:15:02 +08:00
禾几海
6ac9c69ff9 重新管理pom依赖 2021-10-03 14:13:15 +08:00
禾几海
c6a5de6335 修复无法获取blog-resource.jar包资源的问题 2021-10-03 14:13:11 +08:00
禾几海
ab13a1713f enum 包改名为 constant 2021-10-03 14:12:59 +08:00
禾几海
f8ee1da333 rename ExceptionHandle to BlogExceptionHandler 2021-10-01 15:58:12 +08:00
禾几海
366ce4b829 重构工具类 2021-10-01 15:57:46 +08:00
禾几海
fa120a6da5 MyException rename to BlogResponseException 2021-10-01 15:48:27 +08:00
禾几海
ef2f98e45f 模块化拆分 2021-10-01 15:43:54 +08:00
禾几海
7e700b6499 模块化拆分 2021-10-01 01:08:46 +08:00
禾几海
c1c7f38ee9 13 -> 1.8 2021-09-29 23:44:05 +08:00
禾几海
fd509e0042 修复依赖 2021-09-29 23:39:51 +08:00
禾几海
330d4d525a 修复依赖 2021-09-29 23:36:53 +08:00
禾几海
8c18abf120 修复依赖 2021-09-29 23:34:31 +08:00
禾几海
113a054bea 修复依赖 2021-09-29 23:20:14 +08:00
禾几海
6d3739517a 模块化拆分 2021-09-29 23:09:54 +08:00
禾几海
c8e93c45c7 Merge pull request #74 from xiaohai2271/dependabot/maven/com.alibaba-druid-1.2.6
build(deps): bump druid from 1.2.5 to 1.2.6
2021-06-02 10:57:25 +08:00
禾几海
32de31a21e Merge pull request #75 from xiaohai2271/dependabot/maven/org.mybatis.spring.boot-mybatis-spring-boot-starter-2.2.0
build(deps): bump mybatis-spring-boot-starter from 2.1.4 to 2.2.0
2021-06-02 10:57:04 +08:00
禾几海
cc20df91e6 Merge pull request #63 from xiaohai2271/dependabot/maven/org.projectlombok-lombok-1.18.20
build(deps): bump lombok from 1.18.18 to 1.18.20
2021-06-01 23:30:23 +08:00
dependabot[bot]
71d79ed008 build(deps): bump mybatis-spring-boot-starter from 2.1.4 to 2.2.0
Bumps [mybatis-spring-boot-starter](https://github.com/mybatis/spring-boot-starter) from 2.1.4 to 2.2.0.
- [Release notes](https://github.com/mybatis/spring-boot-starter/releases)
- [Commits](https://github.com/mybatis/spring-boot-starter/compare/mybatis-spring-boot-2.1.4...mybatis-spring-boot-2.2.0)

---
updated-dependencies:
- dependency-name: org.mybatis.spring.boot:mybatis-spring-boot-starter
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-01 15:30:00 +00:00
dependabot[bot]
f7ff494ea4 build(deps): bump druid from 1.2.5 to 1.2.6
Bumps [druid](https://github.com/alibaba/druid) from 1.2.5 to 1.2.6.
- [Release notes](https://github.com/alibaba/druid/releases)
- [Commits](https://github.com/alibaba/druid/compare/1.2.5...1.2.6)

---
updated-dependencies:
- dependency-name: com.alibaba:druid
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-01 15:29:55 +00:00
禾几海
971f48c5f9 Merge pull request #72 from xiaohai2271/dependabot/maven/org.jetbrains.kotlin-kotlin-maven-plugin-1.5.10
build(deps): bump kotlin-maven-plugin from 1.4.10 to 1.5.10
2021-06-01 23:29:54 +08:00
禾几海
e1522a8cc1 Merge pull request #73 from xiaohai2271/dependabot/maven/net.minidev-json-smart-2.4.7
build(deps): bump json-smart from 2.3 to 2.4.7
2021-06-01 23:29:32 +08:00
dependabot[bot]
3cc4989960 build(deps): bump json-smart from 2.3 to 2.4.7
Bumps [json-smart](https://github.com/netplex/json-smart-v2) from 2.3 to 2.4.7.
- [Release notes](https://github.com/netplex/json-smart-v2/releases)
- [Commits](https://github.com/netplex/json-smart-v2/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-01 05:22:45 +00:00
dependabot[bot]
8c751e6e76 build(deps): bump kotlin-maven-plugin from 1.4.10 to 1.5.10
Bumps kotlin-maven-plugin from 1.4.10 to 1.5.10.

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-01 05:22:39 +00:00
dependabot[bot]
af47631126 build(deps): bump lombok from 1.18.18 to 1.18.20
Bumps [lombok](https://github.com/rzwitserloot/lombok) from 1.18.18 to 1.18.20.
- [Release notes](https://github.com/rzwitserloot/lombok/releases)
- [Changelog](https://github.com/projectlombok/lombok/blob/master/doc/changelog.markdown)
- [Commits](https://github.com/rzwitserloot/lombok/compare/v1.18.18...v1.18.20)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-01 05:24:17 +00:00
禾几海
2107a1c100 Merge pull request #49 from xiaohai2271/dependabot/maven/com.squareup.okhttp3-okhttp-4.9.1
build(deps): bump okhttp from 4.9.0 to 4.9.1
2021-04-01 14:14:35 +08:00
禾几海
2eac16dbe4 Merge pull request #52 from xiaohai2271/dependabot/maven/com.alibaba-druid-1.2.5
build(deps): bump druid from 1.2.3 to 1.2.5
2021-04-01 14:12:39 +08:00
禾几海
d248e15cea fix: 规范请求头的token
规范为` Authorization: Bearer $token`
2021-03-16 20:09:06 +08:00
禾几海
91a818d293 fix: sql条件错误 2021-03-16 15:54:26 +08:00
禾几海
65c31e96b4 test: 补增单元测试 2021-03-16 15:45:49 +08:00
禾几海
81b4851e42 refactor: 分页查询
通过数据库进行分页查询而非查询全部然后分页
2021-03-16 15:38:49 +08:00
禾几海
9c580cf6d9 fix: 文章不可见
当open字段为false时文章应当不被感知
而之前的版本并没有做强制要求
2021-03-16 15:30:05 +08:00
禾几海
9eea5b3db9 ci: Sync repository to gitee 2021-03-15 22:12:49 +08:00
禾几海
eacb2e29f3 fix: 修复数据异常 2021-03-15 18:51:53 +08:00
禾几海
fafee4f918 fix: 分页数据异常 2021-03-15 17:31:37 +08:00
dependabot[bot]
30a4c11366 build(deps): bump druid from 1.2.3 to 1.2.5
Bumps [druid](https://github.com/alibaba/druid) from 1.2.3 to 1.2.5.
- [Release notes](https://github.com/alibaba/druid/releases)
- [Commits](https://github.com/alibaba/druid/compare/1.2.3...1.2.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-01 05:31:55 +00:00
禾几海
5632d47674 Merge pull request #48 from xiaohai2271/dependabot/maven/org.projectlombok-lombok-1.18.18
build(deps): bump lombok from 1.18.16 to 1.18.18
2021-02-28 22:24:55 +08:00
dependabot[bot]
15b5d89554 build(deps): bump okhttp from 4.9.0 to 4.9.1
Bumps [okhttp](https://github.com/square/okhttp) from 4.9.0 to 4.9.1.
- [Release notes](https://github.com/square/okhttp/releases)
- [Changelog](https://github.com/square/okhttp/blob/master/CHANGELOG.md)
- [Commits](https://github.com/square/okhttp/compare/parent-4.9.0...parent-4.9.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-01 05:28:43 +00:00
dependabot[bot]
79426dbe24 build(deps): bump lombok from 1.18.16 to 1.18.18
Bumps [lombok](https://github.com/rzwitserloot/lombok) from 1.18.16 to 1.18.18.
- [Release notes](https://github.com/rzwitserloot/lombok/releases)
- [Changelog](https://github.com/rzwitserloot/lombok/blob/master/doc/changelog.markdown)
- [Commits](https://github.com/rzwitserloot/lombok/compare/v1.18.16...v1.18.18)

Signed-off-by: dependabot[bot] <support@github.com>
2021-02-01 05:28:40 +00:00
禾几海
b3b19dbc45 Merge pull request #38 from xiaohai2271/dependabot/maven/net.sourceforge.htmlunit-htmlunit-2.45.0
build(deps): bump htmlunit from 2.44.0 to 2.45.0
2020-12-02 11:00:34 +08:00
禾几海
87ec6d24ca Merge pull request #37 from xiaohai2271/dependabot/maven/org.mybatis.spring.boot-mybatis-spring-boot-starter-2.1.4
build(deps): bump mybatis-spring-boot-starter from 2.1.3 to 2.1.4
2020-12-01 14:08:15 +08:00
禾几海
0148c5e3f5 Merge pull request #39 from xiaohai2271/dependabot/maven/com.alibaba-druid-1.2.3
build(deps): bump druid from 1.2.1 to 1.2.3
2020-12-01 14:04:58 +08:00
禾几海
7cff3b9c08 Merge pull request #40 from xiaohai2271/dependabot/maven/com.sun.xml.bind-jaxb-impl-3.0.0
build(deps): bump jaxb-impl from 2.3.3 to 3.0.0
2020-12-01 14:02:35 +08:00
禾几海
a354f48edf Merge pull request #41 from xiaohai2271/dependabot/maven/org.jetbrains.kotlin-kotlin-stdlib-1.4.20
build(deps): bump kotlin-stdlib from 1.4.10 to 1.4.20
2020-12-01 14:02:02 +08:00
dependabot[bot]
2cd2dc93d7 build(deps): bump kotlin-stdlib from 1.4.10 to 1.4.20
Bumps [kotlin-stdlib](https://github.com/JetBrains/kotlin) from 1.4.10 to 1.4.20.
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.4.10...v1.4.20)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-01 05:39:35 +00:00
dependabot[bot]
d5fbc0fbf1 build(deps): bump jaxb-impl from 2.3.3 to 3.0.0
Bumps jaxb-impl from 2.3.3 to 3.0.0.

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-01 05:39:09 +00:00
dependabot[bot]
b29362eb8c build(deps): bump druid from 1.2.1 to 1.2.3
Bumps [druid](https://github.com/alibaba/druid) from 1.2.1 to 1.2.3.
- [Release notes](https://github.com/alibaba/druid/releases)
- [Commits](https://github.com/alibaba/druid/compare/1.2.1...1.2.3)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-01 05:39:07 +00:00
dependabot[bot]
d7c6cca683 build(deps): bump htmlunit from 2.44.0 to 2.45.0
Bumps [htmlunit](https://github.com/HtmlUnit/htmlunit) from 2.44.0 to 2.45.0.
- [Release notes](https://github.com/HtmlUnit/htmlunit/releases)
- [Commits](https://github.com/HtmlUnit/htmlunit/compare/2.44.0...2.45.0)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-01 05:39:03 +00:00
dependabot[bot]
8020eaeff3 build(deps): bump mybatis-spring-boot-starter from 2.1.3 to 2.1.4
Bumps [mybatis-spring-boot-starter](https://github.com/mybatis/spring-boot-starter) from 2.1.3 to 2.1.4.
- [Release notes](https://github.com/mybatis/spring-boot-starter/releases)
- [Commits](https://github.com/mybatis/spring-boot-starter/compare/mybatis-spring-boot-2.1.3...mybatis-spring-boot-2.1.4)

Signed-off-by: dependabot[bot] <support@github.com>
2020-12-01 05:39:02 +00:00
禾几海
aedcaf207b ci: skip ci action situation
[skip ci]
2020-11-14 21:38:58 +08:00
禾几海
af9bf9ef46 ci: skip ci action situation 2020-11-14 21:27:44 +08:00
禾几海
b38ce4c8ce Update dependabot.yml 2020-11-02 15:04:20 +08:00
禾几海
3d3548b984 Merge pull request #27 from xiaohai2271/dependabot/maven/com.youbenzi-MDTool-1.2.4
build(deps): bump MDTool from 1.2.3 to 1.2.4
2020-11-01 19:12:55 +08:00
禾几海
4be9eda566 Merge pull request #28 from xiaohai2271/dependabot/maven/com.dyuproject.protostuff-protostuff-runtime-1.1.6
build(deps): bump protostuff-runtime from 1.0.8 to 1.1.6
2020-11-01 19:12:14 +08:00
禾几海
e5711746fb Merge pull request #29 from xiaohai2271/dependabot/maven/org.mybatis.spring.boot-mybatis-spring-boot-starter-2.1.3
build(deps): bump mybatis-spring-boot-starter from 2.0.1 to 2.1.3
2020-11-01 19:11:36 +08:00
禾几海
cc9cf8b1e8 Merge pull request #31 from xiaohai2271/dependabot/maven/com.alibaba-druid-1.2.1
build(deps): bump druid from 1.1.14 to 1.2.1
2020-10-27 13:22:10 +08:00
禾几海
ff076f8366 Merge pull request #32 from xiaohai2271/dependabot/maven/com.squareup.okhttp3-okhttp-4.9.0
build(deps): bump okhttp from 4.8.0 to 4.9.0
2020-10-27 13:17:27 +08:00
禾几海
dd9ae0b3f9 Merge pull request #30 from xiaohai2271/dependabot/maven/eu.bitwalker-UserAgentUtils-1.21
build(deps): bump UserAgentUtils from 1.20 to 1.21
2020-10-22 22:37:46 +08:00
dependabot[bot]
0e7d5f2d23 build(deps): bump okhttp from 4.8.0 to 4.9.0
Bumps [okhttp](https://github.com/square/okhttp) from 4.8.0 to 4.9.0.
- [Release notes](https://github.com/square/okhttp/releases)
- [Changelog](https://github.com/square/okhttp/blob/master/CHANGELOG.md)
- [Commits](https://github.com/square/okhttp/compare/parent-4.8.0...parent-4.9.0)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-20 16:17:29 +00:00
dependabot[bot]
1de1af2a54 build(deps): bump druid from 1.1.14 to 1.2.1
Bumps [druid](https://github.com/alibaba/druid) from 1.1.14 to 1.2.1.
- [Release notes](https://github.com/alibaba/druid/releases)
- [Commits](https://github.com/alibaba/druid/compare/1.1.14...1.2.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-20 16:17:25 +00:00
dependabot[bot]
857a3d9473 build(deps): bump UserAgentUtils from 1.20 to 1.21
Bumps [UserAgentUtils](https://github.com/HaraldWalker/user-agent-utils) from 1.20 to 1.21.
- [Release notes](https://github.com/HaraldWalker/user-agent-utils/releases)
- [Commits](https://github.com/HaraldWalker/user-agent-utils/compare/1.20...1.21)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-20 16:17:24 +00:00
dependabot[bot]
78efa62476 build(deps): bump protostuff-runtime from 1.0.8 to 1.1.6
Bumps protostuff-runtime from 1.0.8 to 1.1.6.

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-20 16:17:22 +00:00
dependabot[bot]
674812c5c6 build(deps): bump mybatis-spring-boot-starter from 2.0.1 to 2.1.3
Bumps [mybatis-spring-boot-starter](https://github.com/mybatis/spring-boot-starter) from 2.0.1 to 2.1.3.
- [Release notes](https://github.com/mybatis/spring-boot-starter/releases)
- [Commits](https://github.com/mybatis/spring-boot-starter/compare/mybatis-spring-boot-2.0.1...mybatis-spring-boot-2.1.3)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-20 16:17:22 +00:00
dependabot[bot]
14ce46c312 build(deps): bump MDTool from 1.2.3 to 1.2.4
Bumps [MDTool](https://github.com/cevin15/MDTool) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/cevin15/MDTool/releases)
- [Commits](https://github.com/cevin15/MDTool/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-20 16:17:21 +00:00
禾几海
5f5fbadfd8 Merge pull request #15 from xiaohai2271/dependabot/maven/com.sun.xml.bind-jaxb-core-2.3.0.1
build(deps): bump jaxb-core from 2.3.0 to 2.3.0.1
2020-10-21 00:11:48 +08:00
禾几海
c153d9a0e3 Merge pull request #16 from xiaohai2271/dependabot/maven/org.jetbrains.kotlin-kotlin-maven-plugin-1.4.10
build(deps): bump kotlin-maven-plugin from 1.3.72 to 1.4.10
2020-10-21 00:11:25 +08:00
禾几海
18d35809f5 Merge pull request #17 from xiaohai2271/dependabot/maven/com.sun.xml.bind-jaxb-impl-2.3.3
build(deps): bump jaxb-impl from 2.3.0 to 2.3.3
2020-10-21 00:11:00 +08:00
禾几海
75e2424f75 Merge pull request #22 from xiaohai2271/dependabot/maven/javax.xml.bind-jaxb-api-2.3.1
build(deps): bump jaxb-api from 2.3.0 to 2.3.1
2020-10-21 00:10:24 +08:00
禾几海
b6c4251198 Merge pull request #21 from xiaohai2271/dependabot/maven/com.github.pagehelper-pagehelper-spring-boot-starter-1.3.0
build(deps): bump pagehelper-spring-boot-starter from 1.2.12 to 1.3.0
2020-10-21 00:08:04 +08:00
禾几海
fc1bfa0e4f Merge pull request #19 from xiaohai2271/dependabot/maven/org.jetbrains.kotlin-kotlin-stdlib-1.4.10
build(deps): bump kotlin-stdlib from 1.3.72 to 1.4.10
2020-10-21 00:07:25 +08:00
禾几海
e37de0e177 Merge pull request #20 from xiaohai2271/dependabot/maven/com.dyuproject.protostuff-protostuff-core-1.1.6
build(deps): bump protostuff-core from 1.0.8 to 1.1.6
2020-10-21 00:06:58 +08:00
dependabot[bot]
082662af66 build(deps): bump protostuff-core from 1.0.8 to 1.1.6
Bumps protostuff-core from 1.0.8 to 1.1.6.

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-20 15:11:14 +00:00
dependabot[bot]
0c0e2404d0 Merge pull request #26 from xiaohai2271/dependabot/maven/org.projectlombok-lombok-1.18.16 2020-10-20 14:59:05 +00:00
dependabot[bot]
71f82bfe32 build(deps): bump lombok from 1.18.6 to 1.18.16
Bumps [lombok](https://github.com/rzwitserloot/lombok) from 1.18.6 to 1.18.16.
- [Release notes](https://github.com/rzwitserloot/lombok/releases)
- [Changelog](https://github.com/rzwitserloot/lombok/blob/master/doc/changelog.markdown)
- [Commits](https://github.com/rzwitserloot/lombok/compare/v1.18.6...v1.18.16)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-20 07:06:17 +00:00
禾几海
61ce2fddad Merge pull request #24 from xiaohai2271/dependabot/maven/net.sourceforge.htmlunit-htmlunit-2.44.0
build(deps): bump htmlunit from 2.42.0 to 2.44.0
2020-10-20 13:03:25 +08:00
禾几海
a245f259f7 revert: "Update test.yml"
This reverts commit 2c85c3ea
2020-10-17 23:28:58 +08:00
禾几海
aa22369b13 Merge pull request #25 from kingzhongking/master
style(pom):  delete some comment
2020-10-17 22:51:00 +08:00
kingzhongking
8c3866afe6 style(pom): delete some comment 2020-10-17 14:44:29 +00:00
禾几海
2c85c3eaac Update test.yml 2020-10-16 19:32:36 +08:00
dependabot[bot]
2559937e02 build(deps): bump htmlunit from 2.42.0 to 2.44.0
Bumps [htmlunit](https://github.com/HtmlUnit/htmlunit) from 2.42.0 to 2.44.0.
- [Release notes](https://github.com/HtmlUnit/htmlunit/releases)
- [Commits](https://github.com/HtmlUnit/htmlunit/compare/2.42.0...2.44.0)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-16 11:21:27 +00:00
dependabot[bot]
8de4be602e build(deps): bump jaxb-api from 2.3.0 to 2.3.1
Bumps [jaxb-api](https://github.com/javaee/jaxb-spec) from 2.3.0 to 2.3.1.
- [Release notes](https://github.com/javaee/jaxb-spec/releases)
- [Commits](https://github.com/javaee/jaxb-spec/compare/2.3.0...2.3.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-16 11:21:23 +00:00
dependabot[bot]
1f88995884 build(deps): bump pagehelper-spring-boot-starter from 1.2.12 to 1.3.0
Bumps pagehelper-spring-boot-starter from 1.2.12 to 1.3.0.

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-16 11:21:23 +00:00
禾几海
c879fbff5f Update dependabot.yml 2020-10-16 19:21:00 +08:00
dependabot[bot]
f6020bf8d0 build(deps): bump kotlin-stdlib from 1.3.72 to 1.4.10
Bumps [kotlin-stdlib](https://github.com/JetBrains/kotlin) from 1.3.72 to 1.4.10.
- [Release notes](https://github.com/JetBrains/kotlin/releases)
- [Changelog](https://github.com/JetBrains/kotlin/blob/v1.4.10/ChangeLog.md)
- [Commits](https://github.com/JetBrains/kotlin/compare/v1.3.72...v1.4.10)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-16 11:09:51 +00:00
dependabot[bot]
418b1d78e5 build(deps): bump jaxb-impl from 2.3.0 to 2.3.3
Bumps jaxb-impl from 2.3.0 to 2.3.3.

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-16 11:09:20 +00:00
dependabot[bot]
98ed489bb1 build(deps): bump kotlin-maven-plugin from 1.3.72 to 1.4.10
Bumps kotlin-maven-plugin from 1.3.72 to 1.4.10.

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-16 11:09:19 +00:00
dependabot[bot]
cfdd818829 build(deps): bump jaxb-core from 2.3.0 to 2.3.0.1
Bumps jaxb-core from 2.3.0 to 2.3.0.1.

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-16 11:09:18 +00:00
禾几海
3afbef009f Create dependabot.yml 2020-10-16 19:08:56 +08:00
禾几海
8f4d1cd6c8 Update issue templates 2020-10-15 16:46:31 +08:00
229 changed files with 10414 additions and 11460 deletions

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

12
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "maven" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "monthly"
open-pull-requests-limit: 10

View File

@@ -1,21 +1,23 @@
# This workflow will build a package using Maven and then publish it to GitHub packages when a release is created
# For more information see: https://github.com/actions/setup-java#apache-maven-with-a-settings-path
name: Build name: Build
on: on:
push: push:
branches: branches: [ master ]
- master paths-ignore:
- "doc/**"
- "**/README.md"
pull_request:
branches: [ master ]
paths-ignore:
- "doc/**"
- "**/README.md"
jobs: jobs:
build: build:
if: "!contains(github.event.head_commit.message, '[skip ci]')" # 如果 commit 信息包含以下关键字则跳过该任务
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
KEY: ${{ secrets.WEB_HOOK_ACCESS_KEY }} KEY: ${{ secrets.WEB_HOOK_ACCESS_KEY }}
QINIU_ACCESSKEY: ${{ secrets.QINIU_ACCESSKEY }}
QINIU_SECRETKEY: ${{ secrets.QINIU_SECRETKEY }}
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
@@ -24,5 +26,13 @@ jobs:
with: with:
java-version: 1.8 java-version: 1.8
- name: Deploy - name: Cache local Maven repository
run: mvn -B test --file pom.xml && curl http://bt.celess.cn:2271/hook?access_key=$KEY uses: actions/cache@v2
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Unit Test
run: mvn package -B -pl blog-deploy -am

View File

@@ -1,71 +0,0 @@
# 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.
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
schedule:
- cron: '0 14 * * 2'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
# Override automatic language detection by changing the below list
# Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python']
language: ['java']
# Learn more...
# https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
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.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# 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@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

22
.github/workflows/sync.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
name: Sync Repository Action
on:
push:
branches: [ master ]
schedule:
# 每周一0:00
- cron: '0 0 * * 1'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Sync to Gitee
uses: x-dr/sync-repo-to-gitee@master
env:
# 在 Settings->Secrets 配置 GITEE_KEY
SSH_KEY: ${{ secrets.GITEE_KEY }}
with:
# GitHub存储库的SSH URL.
github-repo: git@github.com:xiaohai2271/blog-backEnd.git
# Gitee存储库的SSH URL.
gitee-repo: git@gitee.com:xiaohai2271/blog-backEnd.git

View File

@@ -1,29 +0,0 @@
# This workflow will build a package using Maven and then publish it to GitHub packages when a release is created
# For more information see: https://github.com/actions/setup-java#apache-maven-with-a-settings-path
name: Test
on:
push:
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
env:
QINIU_ACCESSKEY: ${{ secrets.QINIU_ACCESSKEY }}
QINIU_SECRETKEY: ${{ secrets.QINIU_SECRETKEY }}
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Test
run: mvn -B test --file pom.xml

2
.gitignore vendored
View File

@@ -4,5 +4,5 @@
target/ target/
# 本地项目的私有文件 # 本地项目的私有文件
src/main/resources/application-dev.properties blog-deploy/src/main/resources/application-dev.properties
src/main/resources/application-prod.properties src/main/resources/application-prod.properties

45
blog-article/pom.xml Normal file
View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>blog</artifactId>
<groupId>cn.celess</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>blog-article</artifactId>
<dependencies>
<dependency>
<groupId>cn.celess</groupId>
<artifactId>blog-common</artifactId>
<version>${blog-common.version}</version>
</dependency>
<dependency>
<groupId>cn.celess</groupId>
<artifactId>blog-user</artifactId>
<version>${blog-user.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--MarkDown 2 html -->
<dependency>
<groupId>com.youbenzi</groupId>
<artifactId>MDTool</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>2.4.7</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,18 @@
package cn.celess.article;
import cn.celess.common.CommonApplication;
import cn.celess.user.UserApplication;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.SpringVersion;
@SpringBootApplication(scanBasePackageClasses = {ArticleApplication.class, CommonApplication.class, UserApplication.class})
public class ArticleApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ArticleApplication.class)
.main(SpringVersion.class)
.bannerMode(Banner.Mode.CONSOLE)
.run(args);
}
}

View File

@@ -1,163 +1,161 @@
package cn.celess.blog.controller; package cn.celess.article.controller;
import cn.celess.blog.enmu.ResponseEnum; import cn.celess.article.util.SitemapGenerateUtil;
import cn.celess.blog.entity.Response; import cn.celess.common.constant.ResponseEnum;
import cn.celess.blog.entity.model.ArticleModel; import cn.celess.common.entity.Response;
import cn.celess.blog.entity.request.ArticleReq; import cn.celess.common.entity.dto.ArticleReq;
import cn.celess.blog.service.ArticleService; import cn.celess.common.entity.vo.ArticleModel;
import cn.celess.blog.util.RedisUserUtil; import cn.celess.common.service.ArticleService;
import cn.celess.blog.util.SitemapGenerateUtil; import cn.celess.common.util.EnvironmentUtil;
import org.springframework.beans.factory.annotation.Autowired; import cn.celess.user.util.RedisUserUtil;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 15:18 * @date : 2019/03/28 15:18
*/ */
@RestController @RestController
public class ArticleController { public class ArticleController {
@Autowired @Autowired
ArticleService articleService; ArticleService articleService;
@Autowired @Autowired
SitemapGenerateUtil sitemapGenerateUtil; SitemapGenerateUtil sitemapGenerateUtil;
@Autowired @Autowired
RedisUserUtil redisUserUtil; RedisUserUtil redisUserUtil;
@Value("${spring.profiles.active}")
private String activeModel; /**
* 新建一篇文章
/** *
* 新建一篇文章 * @param body 请求数据
* * @return Response
* @param body 请求数据 */
* @return Response @PostMapping("/admin/article/create")
*/ public Response create(@RequestBody ArticleReq body) {
@PostMapping("/admin/article/create") ArticleModel articleModel = articleService.create(body);
public Response create(@RequestBody ArticleReq body) { if ("prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
ArticleModel articleModel = articleService.create(body); sitemapGenerateUtil.createSitemap();
if ("prod".equals(activeModel)) { }
sitemapGenerateUtil.createSitemap(); return Response.success(articleModel);
} }
return Response.success(articleModel);
} /**
* 通过文章id 删除一篇文章
/** *
* 通过文章id 删除一篇文章 * @param articleId 文章id
* * @return Response
* @param articleId 文章id */
* @return Response @DeleteMapping("/admin/article/del")
*/ public Response delete(@RequestParam("articleID") long articleId) {
@DeleteMapping("/admin/article/del") boolean delete = articleService.delete(articleId);
public Response delete(@RequestParam("articleID") long articleId) { if ("prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
boolean delete = articleService.delete(articleId); sitemapGenerateUtil.createSitemap();
if ("prod".equals(activeModel)) { }
sitemapGenerateUtil.createSitemap(); return Response.success(delete);
} }
return Response.success(delete);
} /**
* 更新文章
/** *
* 更新文章 * @param body 请求数据
* * @return Response
* @param body 请求数据 */
* @return Response @PutMapping("/admin/article/update")
*/ public Response update(@RequestBody ArticleReq body) {
@PutMapping("/admin/article/update") ArticleModel update = articleService.update(body);
public Response update(@RequestBody ArticleReq body) { if ("prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
ArticleModel update = articleService.update(body); sitemapGenerateUtil.createSitemap();
if ("prod".equals(activeModel)) { }
sitemapGenerateUtil.createSitemap(); return Response.success(update);
} }
return Response.success(update);
} /**
* 通过id查找一篇文章
/** * 公开 =>返回数据
* 通过id查找一篇文章 * 不公开
* 公开 =>返回数据 * *** =>作者 返回数据
* 不公开 * *** =>其他 抛出错误
* *** =>作者 返回数据 *
* *** =>其他 抛出错误 * @param articleId 文章id
* * @param is4update 是否是更新
* @param articleId 文章id * @return Response
* @param is4update 是否是更新 */
* @return Response @GetMapping("/article/articleID/{articleID}")
*/ public Response retrieveOneById(@PathVariable("articleID") long articleId,
@GetMapping("/article/articleID/{articleID}") @RequestParam(value = "update", defaultValue = "false") boolean is4update,
public Response retrieveOneById(@PathVariable("articleID") long articleId, HttpServletRequest request) {
@RequestParam(value = "update", defaultValue = "false") boolean is4update, ArticleModel article = articleService.retrieveOneById(articleId, is4update);
HttpServletRequest request) { if (article.getOpen()) {
ArticleModel article = articleService.retrieveOneById(articleId, is4update); return Response.success(article);
if (article.getOpen()) { } else if (article.getAuthor().getId().equals(redisUserUtil.get().getId())) {
return Response.success(article); return Response.success(article);
} else if (article.getAuthor().getId().equals(redisUserUtil.get().getId())) { }
return Response.success(article); return Response.response(ResponseEnum.PERMISSION_ERROR, null);
} }
return Response.response(ResponseEnum.PERMISSION_ERROR, null);
} /**
* 分页获取所有文章状态为开放的的文章
/** *
* 分页获取所有文章状态为开放的的文章 * @param page 页码
* * @param count 单页数据量
* @param page 页码 * @return Response
* @param count 单页数据量 */
* @return Response @GetMapping("/articles")
*/ public Response articles(@RequestParam(name = "page", defaultValue = "1") int page,
@GetMapping("/articles") @RequestParam(name = "count", defaultValue = "5") int count) {
public Response articles(@RequestParam(name = "page", defaultValue = "1") int page, return Response.success(articleService.retrievePageForOpen(count, page));
@RequestParam(name = "count", defaultValue = "5") int count) { }
return Response.success(articleService.retrievePageForOpen(count, page));
} /**
* 分页获取所有文章
/** *
* 分页获取所有文章 * @param page 页码
* * @param count 单页数据量
* @param page 页码 * @return Response
* @param count 单页数据量 */
* @return Response @GetMapping("/admin/articles")
*/ public Response adminArticles(@RequestParam(name = "page", defaultValue = "1") int page,
@GetMapping("/admin/articles") @RequestParam(name = "count", defaultValue = "10") int count,
public Response adminArticles(@RequestParam(name = "page", defaultValue = "1") int page, @RequestParam(name = "deleted", required = false) Boolean deleted) {
@RequestParam(name = "count", defaultValue = "10") int count, return Response.success(articleService.adminArticles(count, page, deleted));
@RequestParam(name = "deleted", required = false) Boolean deleted) { }
return Response.success(articleService.adminArticles(count, page, deleted));
} /**
* 通过分类获取文章文章摘要
/** *
* 通过分类获取文章文章摘要 * @param name 分类名
* * @param page 页码
* @param name 分类名 * @param count 单页数据量
* @param page 页码 * @return Response
* @param count 单页数据量 */
* @return Response @GetMapping("/articles/category/{name}")
*/ public Response findByCategory(@PathVariable("name") String name,
@GetMapping("/articles/category/{name}") @RequestParam(name = "page", defaultValue = "1") int page,
public Response findByCategory(@PathVariable("name") String name, @RequestParam(name = "count", defaultValue = "10") int count) {
@RequestParam(name = "page", defaultValue = "1") int page, return Response.success(articleService.findByCategory(name, page, count));
@RequestParam(name = "count", defaultValue = "10") int count) { }
return Response.success(articleService.findByCategory(name, page, count));
} /**
* 通过标签名获取文章文章摘要
/** *
* 通过标签名获取文章文章摘要 * @param name 标签名
* * @param page 页码
* @param name 标签名 * @param count 单页数据量
* @param page 页码 * @return Response
* @param count 单页数据量 */
* @return Response @GetMapping("/articles/tag/{name}")
*/ public Response findByTag(@PathVariable("name") String name,
@GetMapping("/articles/tag/{name}") @RequestParam(name = "page", defaultValue = "1") int page,
public Response findByTag(@PathVariable("name") String name, @RequestParam(name = "count", defaultValue = "10") int count) {
@RequestParam(name = "page", defaultValue = "1") int page, return Response.success(articleService.findByTag(name, page, count));
@RequestParam(name = "count", defaultValue = "10") int count) { }
return Response.success(articleService.findByTag(name, page, count));
}
@GetMapping("/createSitemap")
public Response createSitemap() {
@GetMapping("/createSitemap") sitemapGenerateUtil.createSitemap();
public Response createSitemap() { return Response.success(null);
sitemapGenerateUtil.createSitemap(); }
return Response.success(null); }
}
}

View File

@@ -1,362 +1,368 @@
package cn.celess.blog.service.serviceimpl; package cn.celess.article.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum; import cn.celess.common.constant.ResponseEnum;
import cn.celess.blog.enmu.RoleEnum; import cn.celess.common.constant.RoleEnum;
import cn.celess.blog.entity.*; import cn.celess.common.entity.*;
import cn.celess.blog.entity.model.ArticleModel; import cn.celess.common.entity.dto.ArticleReq;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.ArticleModel;
import cn.celess.blog.entity.request.ArticleReq; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.exception.MyException; import cn.celess.common.exception.BlogResponseException;
import cn.celess.blog.mapper.*; import cn.celess.common.mapper.*;
import cn.celess.blog.service.ArticleService; import cn.celess.common.service.ArticleService;
import cn.celess.blog.service.UserService; import cn.celess.common.service.UserService;
import cn.celess.blog.util.ModalTrans; import cn.celess.common.util.ModalTrans;
import cn.celess.blog.util.RedisUserUtil; import cn.celess.common.util.RegexUtil;
import cn.celess.blog.util.RegexUtil; import cn.celess.common.util.StringUtil;
import cn.celess.blog.util.StringFromHtmlUtil; import cn.celess.user.util.RedisUserUtil;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import com.youbenzi.mdtool.tool.MDTool; import com.youbenzi.mdtool.tool.MDTool;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList; import javax.annotation.Resource;
import java.util.List; import javax.servlet.http.HttpServletRequest;
import java.util.stream.Collectors; import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author : xiaohai
* @date : 2019/03/28 15:21 /**
*/ * @author : xiaohai
@Service * @date : 2019/03/28 15:21
@Slf4j */
public class ArticleServiceImpl implements ArticleService { @Service
@Slf4j
@Autowired public class ArticleServiceImpl implements ArticleService {
ArticleMapper articleMapper;
@Resource
@Autowired ArticleMapper articleMapper;
TagMapper tagMapper;
@Autowired @Resource
CategoryMapper categoryMapper; TagMapper tagMapper;
@Autowired @Resource
CommentMapper commentMapper; CategoryMapper categoryMapper;
@Autowired @Resource
ArticleTagMapper articleTagMapper; CommentMapper commentMapper;
@Autowired @Resource
UserService userService; ArticleTagMapper articleTagMapper;
@Autowired @Resource
HttpServletRequest request; UserService userService;
@Autowired @Autowired
RedisUserUtil redisUserUtil; HttpServletRequest request;
@Resource
@Override RedisUserUtil redisUserUtil;
@Transactional(rollbackFor = Exception.class)
public ArticleModel create(ArticleReq reqBody) { @Override
if (reqBody == null) { @Transactional(rollbackFor = Exception.class)
throw new MyException(ResponseEnum.PARAMETERS_ERROR); public ArticleModel create(ArticleReq reqBody) {
} if (reqBody == null) {
//数据判断 throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
if (reqBody.getTitle() == null || reqBody.getTitle().replaceAll(" ", "").isEmpty()) { }
throw new MyException(ResponseEnum.PARAMETERS_ERROR); //数据判断
} else if (reqBody.getMdContent() == null || reqBody.getMdContent().replaceAll(" ", "").isEmpty()) { if (reqBody.getTitle() == null || reqBody.getTitle().replaceAll(" ", "").isEmpty()) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR); throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
} } else if (reqBody.getMdContent() == null || reqBody.getMdContent().replaceAll(" ", "").isEmpty()) {
//转载 判断链接 throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
if (!reqBody.getType()) { }
if (reqBody.getUrl() == null || reqBody.getUrl().replaceAll(" ", "").isEmpty()) { //转载 判断链接
throw new MyException(ResponseEnum.PARAMETERS_ERROR); if (!reqBody.getType()) {
} else if (!RegexUtil.urlMatch(reqBody.getUrl())) { if (reqBody.getUrl() == null || reqBody.getUrl().replaceAll(" ", "").isEmpty()) {
throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR); throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
} } else if (!RegexUtil.urlMatch(reqBody.getUrl())) {
} throw new BlogResponseException(ResponseEnum.PARAMETERS_URL_ERROR);
if (reqBody.getCategory() == null || reqBody.getCategory().replaceAll(" ", "").isEmpty()) { }
throw new MyException(ResponseEnum.PARAMETERS_ERROR); }
} if (reqBody.getCategory() == null || reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
if (reqBody.getTags() == null || reqBody.getTags().length == 0) { throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
throw new MyException(ResponseEnum.PARAMETERS_ERROR); }
} if (reqBody.getTags() == null || reqBody.getTags().length == 0) {
if (articleMapper.existsByTitle(reqBody.getTitle())) { throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
throw new MyException(ResponseEnum.ARTICLE_HAS_EXIST); }
} if (articleMapper.existsByTitle(reqBody.getTitle())) {
// 查看是否存在已有的分类 throw new BlogResponseException(ResponseEnum.ARTICLE_HAS_EXIST);
Category category = categoryMapper.findCategoryByName(reqBody.getCategory()); }
if (category == null) { // 查看是否存在已有的分类
throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST); Category category = categoryMapper.findCategoryByName(reqBody.getCategory());
} if (category == null) {
throw new BlogResponseException(ResponseEnum.CATEGORY_NOT_EXIST);
// 构建 需要写入数据库的对象数据 }
Article article = new Article();
BeanUtils.copyProperties(reqBody, article); // 构建 需要写入数据库的对象数据
Article article = new Article();
article.setUser(redisUserUtil.get()); BeanUtils.copyProperties(reqBody, article);
//markdown->html->summary article.setUser(redisUserUtil.get());
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
//获取摘要 摘要长度为255个字符 //markdown->html->summary
String summary = str.length() > 240 ? str.substring(0, 240) + "......" : str; String str = StringUtil.getString(MDTool.markdown2Html(article.getMdContent()));
article.setSummary(summary); //获取摘要 摘要长度为255个字符
String summary = str.length() > 240 ? str.substring(0, 240) + "......" : str;
article.setCategory(category); article.setSummary(summary);
//文章存数据库 article.setCategory(category);
articleMapper.insert(article);
//将标签写入数据库 //文章存数据库
for (String tagName : reqBody.getTags()) { articleMapper.insert(article);
if (tagName.replaceAll(" ", "").length() == 0) { //将标签写入数据库
//单个标签只含空格 for (String tagName : reqBody.getTags()) {
continue; if (tagName.replaceAll(" ", "").length() == 0) {
} //单个标签只含空格
Tag tag = tagMapper.findTagByName(tagName); continue;
if (tag == null) { }
tag = new Tag(); Tag tag = tagMapper.findTagByName(tagName);
tag.setName(tagName); if (tag == null) {
tagMapper.insert(tag); tag = new Tag();
} tag.setName(tagName);
ArticleTag articleTag = new ArticleTag(article, tag); tagMapper.insert(tag);
articleTagMapper.insert(articleTag); }
} ArticleTag articleTag = new ArticleTag(article, tag);
Article articleFromDb = articleMapper.findArticleById(article.getId()); articleTagMapper.insert(articleTag);
}
ArticleModel articleModel = ModalTrans.article(articleFromDb); Article articleFromDb = articleMapper.findArticleById(article.getId());
articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(article.getId()), true));
return articleModel; ArticleModel articleModel = ModalTrans.article(articleFromDb);
} articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(article.getId()), true));
return articleModel;
@Override }
@Transactional(rollbackFor = Exception.class)
public boolean delete(long articleId) { @Override
Article articleForDel = articleMapper.findArticleById(articleId); @Transactional(rollbackFor = Exception.class)
public boolean delete(long articleId) {
if (articleForDel == null) { Article articleForDel = articleMapper.findArticleById(articleId);
//文章不存在
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST); if (articleForDel == null) {
} //文章不存在
throw new BlogResponseException(ResponseEnum.ARTICLE_NOT_EXIST);
//对访问情况进行判断 非admin 权限不可删除文章 }
User user = redisUserUtil.get();
if (!RoleEnum.ADMIN_ROLE.getRoleName().equals(user.getRole())) { //对访问情况进行判断 非admin 权限不可删除文章
throw new MyException(ResponseEnum.PERMISSION_ERROR); User user = redisUserUtil.get();
} if (!RoleEnum.ADMIN_ROLE.getRoleName().equals(user.getRole())) {
//删除指定文章 throw new BlogResponseException(ResponseEnum.PERMISSION_ERROR);
articleMapper.delete(articleId); }
//删除指定文章
//articleTagMapper.deleteByArticleId(articleId); articleMapper.delete(articleId);
return true; //articleTagMapper.deleteByArticleId(articleId);
}
return true;
@Transactional(rollbackFor = Exception.class) }
@Override
public ArticleModel update(ArticleReq reqBody) { @Transactional(rollbackFor = Exception.class)
if (reqBody == null || reqBody.getId() == null) { @Override
throw new MyException(ResponseEnum.PARAMETERS_ERROR); public ArticleModel update(ArticleReq reqBody) {
} if (reqBody == null || reqBody.getId() == null) {
// 查找数据 throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
Article article = articleMapper.findArticleById(reqBody.getId()); }
// 查找数据
//数据判断 Article article = articleMapper.findArticleById(reqBody.getId());
if (reqBody.getTitle() != null && !reqBody.getTitle().replaceAll(" ", "").isEmpty()) {
if (!article.getTitle().equals(reqBody.getTitle()) && articleMapper.existsByTitle(reqBody.getTitle())) { //数据判断
throw new MyException(ResponseEnum.ARTICLE_HAS_EXIST); if (reqBody.getTitle() != null && !reqBody.getTitle().replaceAll(" ", "").isEmpty()) {
} if (!article.getTitle().equals(reqBody.getTitle()) && articleMapper.existsByTitle(reqBody.getTitle())) {
article.setTitle(reqBody.getTitle()); throw new BlogResponseException(ResponseEnum.ARTICLE_HAS_EXIST);
} }
if (reqBody.getMdContent() != null && !reqBody.getMdContent().replaceAll(" ", "").isEmpty()) { article.setTitle(reqBody.getTitle());
article.setMdContent(reqBody.getMdContent()); }
} if (reqBody.getMdContent() != null && !reqBody.getMdContent().replaceAll(" ", "").isEmpty()) {
article.setMdContent(reqBody.getMdContent());
//转载 判断链接 }
if (reqBody.getType() != null) {
if (!reqBody.getType() && reqBody.getUrl() == null) { //转载 判断链接
throw new MyException(ResponseEnum.PARAMETERS_ERROR); if (reqBody.getType() != null) {
} if (!reqBody.getType() && reqBody.getUrl() == null) {
throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
if (!reqBody.getType() && !RegexUtil.urlMatch(reqBody.getUrl())) { }
throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR);
} if (!reqBody.getType() && !RegexUtil.urlMatch(reqBody.getUrl())) {
article.setType(reqBody.getType()); throw new BlogResponseException(ResponseEnum.PARAMETERS_URL_ERROR);
article.setUrl(reqBody.getUrl()); }
} article.setType(reqBody.getType());
if (reqBody.getCategory() != null && !reqBody.getCategory().replaceAll(" ", "").isEmpty()) { article.setUrl(reqBody.getUrl());
Category category = categoryMapper.findCategoryByName(reqBody.getCategory()); }
if (category == null) { if (reqBody.getCategory() != null && !reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
category = new Category(); Category category = categoryMapper.findCategoryByName(reqBody.getCategory());
category.setName(reqBody.getCategory()); if (category == null) {
categoryMapper.insert(category); category = new Category();
} category.setName(reqBody.getCategory());
article.setCategory(category); categoryMapper.insert(category);
} }
article.setCategory(category);
//写入数据库的数据 }
article.setOpen(reqBody.getOpen() == null ? article.getOpen() : reqBody.getOpen());
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent())); //写入数据库的数据
article.setSummary(str.length() > 240 ? str.substring(0, 240) + "......" : str); article.setOpen(reqBody.getOpen() == null ? article.getOpen() : reqBody.getOpen());
articleMapper.update(article); String str = StringUtil.getString(MDTool.markdown2Html(article.getMdContent()));
article.setSummary(str.length() > 240 ? str.substring(0, 240) + "......" : str);
articleMapper.update(article);
List<ArticleTag> allByArticleId = articleTagMapper.findAllByArticleId(article.getId());
List<ArticleTag> updateList = new ArrayList<>();
List<ArticleTag> deleteList = new ArrayList<>(); List<ArticleTag> allByArticleId = articleTagMapper.findAllByArticleId(article.getId());
List<ArticleTag> updateList = new ArrayList<>();
// 获取要更新 的标签 List<ArticleTag> deleteList = new ArrayList<>();
for (String tag : reqBody.getTags()) {
boolean contain = allByArticleId.stream().anyMatch(articleTag -> articleTag.getTag().getName().equals(tag)); // 获取要更新 的标签
if (!contain) { for (String tag : reqBody.getTags()) {
ArticleTag articleTag = new ArticleTag(); boolean contain = allByArticleId.stream().anyMatch(articleTag -> articleTag.getTag().getName().equals(tag));
articleTag.setArticle(article); if (!contain) {
Tag tagByName = tagMapper.findTagByName(tag); ArticleTag articleTag = new ArticleTag();
if (tagByName == null) { articleTag.setArticle(article);
tagByName = new Tag(tag); Tag tagByName = tagMapper.findTagByName(tag);
tagMapper.insert(tagByName); if (tagByName == null) {
} tagByName = new Tag(tag);
articleTag.setTag(tagByName); tagMapper.insert(tagByName);
updateList.add(articleTag); }
} articleTag.setTag(tagByName);
} updateList.add(articleTag);
// 获取要删除的标签 }
allByArticleId.forEach(articleTag -> { }
boolean contain = false; // 获取要删除的标签
for (String tag : reqBody.getTags()) { allByArticleId.forEach(articleTag -> {
if (articleTag.getTag().getName().equals(tag)) { boolean contain = false;
contain = true; for (String tag : reqBody.getTags()) {
break; if (articleTag.getTag().getName().equals(tag)) {
} contain = true;
} break;
if (!contain) { }
deleteList.add(articleTag); }
} if (!contain) {
}); deleteList.add(articleTag);
}
if (updateList.size() != 0) { });
updateList.forEach(articleTag -> articleTagMapper.insert(articleTag));
} if (updateList.size() != 0) {
updateList.forEach(articleTag -> articleTagMapper.insert(articleTag));
if (deleteList.size() != 0) { }
articleTagMapper.deleteMultiById(deleteList);
} if (deleteList.size() != 0) {
articleTagMapper.deleteMultiById(deleteList);
//更新完成移除 }
request.getSession().removeAttribute("article4update");
ArticleModel articleModel = ModalTrans.article(articleMapper.findArticleById(article.getId())); //更新完成移除
setPreAndNextArticle(articleModel); request.getSession().removeAttribute("article4update");
return articleModel; ArticleModel articleModel = ModalTrans.article(articleMapper.findArticleById(article.getId()));
} setPreAndNextArticle(articleModel);
return articleModel;
@Override }
public ArticleModel retrieveOneById(long articleId, boolean is4update) {
Article article = articleMapper.findArticleById(articleId); @Override
if (article == null) { @Cacheable(value = {"article"}, key = "'retrieveOneById'+#articleId")
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST); public ArticleModel retrieveOneById(long articleId, boolean is4update) {
} Article article = articleMapper.findArticleById(articleId);
if (!article.getOpen()) { if (article == null) {
User user = redisUserUtil.getWithOutExc(); throw new BlogResponseException(ResponseEnum.ARTICLE_NOT_EXIST);
if (user == null || "user".equals(user.getRole())) { }
throw new MyException(ResponseEnum.ARTICLE_NOT_PUBLIC); if (!article.getOpen()) {
} User user = redisUserUtil.getWithOutExc();
} if (user == null || "user".equals(user.getRole())) {
ArticleModel articleModel = ModalTrans.article(article); throw new BlogResponseException(ResponseEnum.ARTICLE_NOT_PUBLIC);
}
if (is4update) { }
//因更新而获取文章 不需要增加阅读量 ArticleModel articleModel = ModalTrans.article(article);
request.getSession().setAttribute("article4update", article);
return articleModel; if (is4update) {
} //因更新而获取文章 不需要增加阅读量
setPreAndNextArticle(articleModel); request.getSession().setAttribute("article4update", article);
articleMapper.updateReadingNumber(articleId); return articleModel;
return articleModel; }
} setPreAndNextArticle(articleModel);
articleMapper.updateReadingNumber(articleId);
/** return articleModel;
* @param count 数目 }
* @param page 页面
* @return PageInfo /**
*/ * @param count 数目
@Override * @param page 页面
public PageData<ArticleModel> adminArticles(int count, int page, Boolean deleted) { * @return PageInfo
List<Article> articleList = articleMapper.findAll(); */
@Override
PageData<ArticleModel> pageData = new PageData<>(null, 0, count, page); public PageData<ArticleModel> adminArticles(int count, int page, Boolean deleted) {
List<Article> collect; PageHelper.startPage(page, count);
if (deleted != null) { List<Article> articleList = articleMapper.findAll();
collect = articleList.stream().filter(article -> article.isDeleted() == deleted).collect(Collectors.toList());
} else { PageData<ArticleModel> pageData = new PageData<>(new PageInfo<>(articleList));
collect = articleList;
} List<Article> collect;
pageData.setTotal(collect.size()); if (deleted != null) {
List<ArticleModel> articleModels = collect.stream() collect = articleList.stream().filter(article -> article.isDeleted() == deleted).collect(Collectors.toList());
.peek(article -> article.setMdContent(null)) } else {
.map(ModalTrans::article) collect = articleList;
.skip((page - 1) * count) }
.limit(count) List<ArticleModel> articleModels = collect.stream()
.collect(Collectors.toList()); .peek(article -> article.setMdContent(null))
pageData.setList(articleModels); .map(ModalTrans::article)
.collect(Collectors.toList());
return pageData; pageData.setList(articleModels);
}
return pageData;
@Override }
public PageData<ArticleModel> retrievePageForOpen(int count, int page) {
PageHelper.startPage(page, count); @Override
List<Article> articleList = articleMapper.findAllByOpen(true); @Cacheable(value = {"article"}, key = "'retrievePageForOpen:'+#page+':'+#count")
PageData<ArticleModel> pageData = new PageData<>(new PageInfo<>(articleList)); public PageData<ArticleModel> retrievePageForOpen(int count, int page) {
PageHelper.startPage(page, count);
List<ArticleModel> articleModelList = articleList List<Article> articleList = articleMapper.findAllByOpen(true);
.stream() PageData<ArticleModel> pageData = new PageData<>(new PageInfo<>(articleList));
.map(article -> setPreAndNextArticle(ModalTrans.article(article, true)))
.collect(Collectors.toList()); List<ArticleModel> articleModelList = articleList
pageData.setList(articleModelList); .stream()
return pageData; .map(article -> setPreAndNextArticle(ModalTrans.article(article, true)))
} .collect(Collectors.toList());
pageData.setList(articleModelList);
@Override return pageData;
public PageData<ArticleModel> findByCategory(String name, int page, int count) { }
Category category = categoryMapper.findCategoryByName(name);
if (category == null) { @Override
throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST); @Cacheable(value = {"article"}, key = "'findByCategory:'+#name")
} public PageData<ArticleModel> findByCategory(String name, int page, int count) {
PageHelper.startPage(page, count); Category category = categoryMapper.findCategoryByName(name);
List<Article> open = articleMapper.findAllByCategoryIdAndOpen(category.getId()); if (category == null) {
throw new BlogResponseException(ResponseEnum.CATEGORY_NOT_EXIST);
List<ArticleModel> modelList = open.stream() }
.map(article -> ModalTrans.article(article, true)) PageHelper.startPage(page, count);
.peek(articleModel -> { List<Article> open = articleMapper.findAllByCategoryIdAndOpen(category.getId());
articleModel.setNextArticle(null);
articleModel.setPreArticle(null); List<ArticleModel> modelList = open.stream()
}) .map(article -> ModalTrans.article(article, true))
.collect(Collectors.toList()); .peek(articleModel -> {
return new PageData<>(new PageInfo<>(open), modelList); articleModel.setNextArticle(null);
} articleModel.setPreArticle(null);
})
@Override .collect(Collectors.toList());
public PageData<ArticleModel> findByTag(String name, int page, int count) { return new PageData<>(new PageInfo<>(open), modelList);
Tag tag = tagMapper.findTagByName(name); }
if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST); @Override
} @Cacheable(value = {"article"}, key = "'findByTag:'+#name")
PageHelper.startPage(page, count); public PageData<ArticleModel> findByTag(String name, int page, int count) {
List<ArticleTag> articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId()); Tag tag = tagMapper.findTagByName(name);
List<ArticleModel> modelList = articleByTag if (tag == null) {
.stream() throw new BlogResponseException(ResponseEnum.TAG_NOT_EXIST);
.map(articleTag -> ModalTrans.article(articleTag.getArticle(), true)) }
.peek(articleModel -> { PageHelper.startPage(page, count);
articleModel.setNextArticle(null); List<ArticleTag> articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId());
articleModel.setPreArticle(null); List<ArticleModel> modelList = articleByTag
}).collect(Collectors.toList()); .stream()
return new PageData<>(new PageInfo<>(articleByTag), modelList); .map(articleTag -> ModalTrans.article(articleTag.getArticle(), true))
} .peek(articleModel -> {
articleModel.setNextArticle(null);
private ArticleModel setPreAndNextArticle(ArticleModel articleModel) { articleModel.setPreArticle(null);
if (articleModel == null) { }).collect(Collectors.toList());
return null; return new PageData<>(new PageInfo<>(articleByTag), modelList);
} }
articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(articleModel.getId()), true));
articleModel.setNextArticle(ModalTrans.article(articleMapper.getNextArticle(articleModel.getId()), true));
return articleModel; private ArticleModel setPreAndNextArticle(ArticleModel articleModel) {
} if (articleModel == null) {
} return null;
}
articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(articleModel.getId()), true));
articleModel.setNextArticle(ModalTrans.article(articleMapper.getNextArticle(articleModel.getId()), true));
return articleModel;
}
}

View File

@@ -1,111 +1,111 @@
package cn.celess.blog.util; package cn.celess.article.util;
import cn.celess.blog.entity.Article;
import cn.celess.blog.mapper.ArticleMapper; import cn.celess.common.entity.Article;
import org.springframework.beans.factory.annotation.Autowired; import cn.celess.common.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Value; import cn.celess.common.util.DateFormatUtil;
import org.springframework.scheduling.annotation.Async; import cn.celess.common.util.EnvironmentUtil;
import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired;
import org.w3c.dom.Document; import org.springframework.scheduling.annotation.Async;
import org.w3c.dom.Element; import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException; import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource; import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.TransformerFactory;
import java.io.File; import javax.xml.transform.dom.DOMSource;
import java.io.IOException; import javax.xml.transform.stream.StreamResult;
import java.util.Date; import java.io.File;
import java.util.HashMap; import java.io.IOException;
import java.util.List; import java.util.Date;
import java.util.Map; import java.util.HashMap;
import java.util.stream.Collectors; import java.util.List;
import java.util.Map;
/** import java.util.stream.Collectors;
* @Author: 小海
* @Date 2019/07/30 17:29 /**
* @Description * @Author: 小海
*/ * @Date 2019/07/30 17:29
@Component * @Description
public class SitemapGenerateUtil { */
@Component
@Autowired public class SitemapGenerateUtil {
ArticleMapper articleMapper;
@Value("${sitemap.path}") @Autowired
private String path; ArticleMapper articleMapper;
private Map<String, String> urlList; private Map<String, String> urlList;
private static DocumentBuilder getDocumentBuilder() { private static DocumentBuilder getDocumentBuilder() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null; DocumentBuilder db = null;
try { try {
db = dbf.newDocumentBuilder(); db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) { } catch (ParserConfigurationException e) {
e.printStackTrace(); e.printStackTrace();
} }
return db; return db;
} }
@Async @Async
public void createSitemap() { public void createSitemap() {
initList(); initList();
if ("".equals(path) || "classpath".equals(path)) { String path = EnvironmentUtil.getProperties("sitemap.path", System.getProperty("user.dir"));
path = System.getProperty("user.dir") + "/sitemap.xml"; if ("classpath".equals(path)) {
} path = System.getProperty("user.dir") + "/sitemap.xml";
File file = new File(path); }
try { File file = new File(path);
if (file.exists()) { try {
file.delete(); if (file.exists()) {
} else { file.delete();
file.createNewFile(); } else {
} file.createNewFile();
} catch (IOException e) { }
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
DocumentBuilder db = getDocumentBuilder(); }
Document document = db.newDocument(); DocumentBuilder db = getDocumentBuilder();
document.setXmlVersion("1.0"); Document document = db.newDocument();
document.setXmlStandalone(true); document.setXmlVersion("1.0");
Element urlset = document.createElement("urlset"); document.setXmlStandalone(true);
urlset.setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"); Element urlset = document.createElement("urlset");
// 创建url 结点 urlset.setAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
urlList.forEach((s, s2) -> { // 创建url 结点
Element url = document.createElement("url"); urlList.forEach((s, s2) -> {
Element loc = document.createElement("loc"); Element url = document.createElement("url");
Element lastmod = document.createElement("lastmod"); Element loc = document.createElement("loc");
loc.setTextContent(s); Element lastmod = document.createElement("lastmod");
lastmod.setTextContent(s2); loc.setTextContent(s);
url.appendChild(loc); lastmod.setTextContent(s2);
url.appendChild(lastmod); url.appendChild(loc);
urlset.appendChild(url); url.appendChild(lastmod);
}); urlset.appendChild(url);
document.appendChild(urlset); });
try { document.appendChild(urlset);
TransformerFactory tff = TransformerFactory.newInstance(); try {
Transformer tf = tff.newTransformer(); TransformerFactory tff = TransformerFactory.newInstance();
tf.setOutputProperty(OutputKeys.INDENT, "yes"); Transformer tf = tff.newTransformer();
tf.transform(new DOMSource(document), new StreamResult(file)); tf.setOutputProperty(OutputKeys.INDENT, "yes");
} catch (TransformerException e) { tf.transform(new DOMSource(document), new StreamResult(file));
e.printStackTrace(); } catch (TransformerException e) {
} e.printStackTrace();
} }
}
private void initList() {
urlList = new HashMap<>(); private void initList() {
urlList.put("https://www.celess.cn", DateFormatUtil.getForXmlDate(new Date())); urlList = new HashMap<>();
urlList.put("https://www.celess.cn/links", DateFormatUtil.getForXmlDate(new Date())); urlList.put("https://www.celess.cn", DateFormatUtil.getForXmlDate(new Date()));
urlList.put("https://www.celess.cn/leaveMsg", DateFormatUtil.getForXmlDate(new Date())); urlList.put("https://www.celess.cn/links", DateFormatUtil.getForXmlDate(new Date()));
List<Article> articles = articleMapper.findAll().stream().filter(article -> article.getOpen()&&!article.isDeleted()).collect(Collectors.toList()); urlList.put("https://www.celess.cn/leaveMsg", DateFormatUtil.getForXmlDate(new Date()));
articles.forEach(article -> { List<Article> articles = articleMapper.findAll().stream().filter(article -> article.getOpen() && !article.isDeleted()).collect(Collectors.toList());
urlList.put("https://www.celess.cn/article/" + article.getId(), DateFormatUtil.getForXmlDate( articles.forEach(article -> {
article.getUpdateDate() == null ? article.getPublishDate() : article.getUpdateDate())); urlList.put("https://www.celess.cn/article/" + article.getId(), DateFormatUtil.getForXmlDate(
}); article.getUpdateDate() == null ? article.getPublishDate() : article.getUpdateDate()));
} });
}
}
}

View File

@@ -0,0 +1,12 @@
${AnsiColor.BRIGHT_GREEN}
_ _ _ ____ _ _ _ _
| | | | (_) | _ \ | | /\ | | (_) | |
| |__| | _ | |_) | | | ___ __ _ ______ / \ _ __ | |_ _ ___ | | ___
| __ | | | | _ < | | / _ \ / _` | |______| / /\ \ | '__| | __| | | / __| | | / _ \
| | | | | | | |_) | | | | (_) | | (_| | / ____ \ | | | |_ | | | (__ | | | __/
|_| |_| |_| |____/ |_| \___/ \__, | /_/ \_\ |_| \__| |_| \___| |_| \___|
__/ |
|___/
${AnsiColor.BRIGHT_RED}
Application Version: ${application.version}${application.formatted-version}
Spring Boot Version: ${spring-boot.version}${spring-boot.formatted-version}

View File

@@ -0,0 +1,11 @@
package cn.celess.article;
import cn.celess.common.test.BaseRedisTest;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = {ArticleApplication.class})
@RunWith(SpringRunner.class)
public abstract class ArticleBaseTest extends BaseRedisTest {
}

View File

@@ -1,302 +1,303 @@
package cn.celess.blog.controller; package cn.celess.article.controller;
import cn.celess.blog.BaseTest;
import cn.celess.blog.entity.Article; import cn.celess.article.ArticleBaseTest;
import cn.celess.blog.entity.Response; import cn.celess.common.entity.Article;
import cn.celess.blog.entity.Tag; import cn.celess.common.entity.Response;
import cn.celess.blog.entity.model.ArticleModel; import cn.celess.common.entity.Tag;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.dto.ArticleReq;
import cn.celess.blog.entity.request.ArticleReq; import cn.celess.common.entity.vo.ArticleModel;
import cn.celess.blog.mapper.ArticleMapper; import cn.celess.common.entity.vo.PageData;
import com.fasterxml.jackson.core.type.TypeReference; import cn.celess.common.mapper.ArticleMapper;
import org.junit.Test; import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired; import org.junit.Test;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.List; import javax.annotation.Resource;
import java.util.List;
import static cn.celess.blog.enmu.ResponseEnum.*;
import static org.junit.Assert.*; import static cn.celess.common.constant.ResponseEnum.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
public class ArticleControllerTest extends BaseTest {
@Autowired public class ArticleControllerTest extends ArticleBaseTest {
ArticleMapper articleMapper; @Resource
private static final TypeReference<?> ARTICLE_MODEL_TYPE = new TypeReference<Response<ArticleModel>>() { ArticleMapper articleMapper;
}; private static final TypeReference<?> ARTICLE_MODEL_TYPE = new TypeReference<Response<ArticleModel>>() {
private static final TypeReference<?> ARTICLE_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<ArticleModel>>>() { };
}; private static final TypeReference<?> ARTICLE_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<ArticleModel>>>() {
};
@Test
public void create() { @Test
ArticleReq articleReq = new ArticleReq(); public void create() {
// 应该正常通过 ArticleReq articleReq = new ArticleReq();
articleReq.setTitle("test-" + randomStr()); // 应该正常通过
articleReq.setMdContent("# test title"); articleReq.setTitle("test-" + randomStr());
articleReq.setCategory("随笔"); articleReq.setMdContent("# test title");
String[] tagList = {"tag", "category"}; articleReq.setCategory("随笔");
articleReq.setTags(tagList); String[] tagList = {"tag", "category"};
articleReq.setOpen(true); articleReq.setTags(tagList);
articleReq.setType(true); articleReq.setOpen(true);
articleReq.setUrl("http://xxxx.com"); articleReq.setType(true);
MockHttpServletRequestBuilder post = post("/admin/article/create"); articleReq.setUrl("http://xxxx.com");
MockHttpServletRequestBuilder post = post("/admin/article/create");
try {
getMockData(post, adminLogin(), articleReq).andDo(result -> { try {
Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE); getMockData(post, adminLogin(), articleReq).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE);
assertNotNull(response.getResult()); assertEquals(SUCCESS.getCode(), response.getCode());
ArticleModel articleModel = response.getResult(); assertNotNull(response.getResult());
assertNotNull(articleModel.getId()); ArticleModel articleModel = response.getResult();
assertNotNull(articleModel.getTitle()); assertNotNull(articleModel.getId());
assertNotNull(articleModel.getSummary()); assertNotNull(articleModel.getTitle());
assertNotNull(articleModel.getOriginal()); assertNotNull(articleModel.getSummary());
assertNotNull(articleModel.getTags()); assertNotNull(articleModel.getOriginal());
assertNotNull(articleModel.getCategory()); assertNotNull(articleModel.getTags());
assertNotNull(articleModel.getPublishDateFormat()); assertNotNull(articleModel.getCategory());
assertNotNull(articleModel.getMdContent()); assertNotNull(articleModel.getPublishDateFormat());
assertNotNull(articleModel.getPreArticle()); assertNotNull(articleModel.getMdContent());
assertNull(articleModel.getNextArticle()); assertNotNull(articleModel.getPreArticle());
assertNotNull(articleModel.getOpen()); assertNull(articleModel.getNextArticle());
assertNotNull(articleModel.getReadingNumber()); assertNotNull(articleModel.getOpen());
assertNotNull(articleModel.getAuthor()); assertNotNull(articleModel.getReadingNumber());
assertNotNull(articleModel.getUrl()); assertNotNull(articleModel.getAuthor());
}); assertNotNull(articleModel.getUrl());
} catch (Exception e) { });
e.printStackTrace(); } catch (Exception e) {
} e.printStackTrace();
} }
}
@Test
public void delete() { @Test
Article article; public void delete() {
do { Article article;
article = articleMapper.getLastestArticle(); do {
create(); article = articleMapper.getLastestArticle();
} while (article.isDeleted()); create();
assertFalse(article.isDeleted()); } while (article.isDeleted());
MockHttpServletRequestBuilder delete = MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + article.getId()); assertFalse(article.isDeleted());
try { MockHttpServletRequestBuilder delete = MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + article.getId());
Article finalArticle = article; try {
getMockData(delete, adminLogin()).andDo(result -> { Article finalArticle = article;
Response<Boolean> response = getResponse(result, BOOLEAN_TYPE); getMockData(delete, adminLogin()).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<Boolean> response = getResponse(result, BOOLEAN_TYPE);
// 断言删除成功 assertEquals(SUCCESS.getCode(), response.getCode());
assertTrue(response.getResult()); // 断言删除成功
assertTrue(articleMapper.isDeletedById(finalArticle.getId())); assertTrue(response.getResult());
}); assertTrue(articleMapper.isDeletedById(finalArticle.getId()));
} catch (Exception e) { });
e.printStackTrace(); } catch (Exception e) {
} e.printStackTrace();
} }
}
@Test
public void update() { @Test
Article article = articleMapper.getLastestArticle(); public void update() {
ArticleReq articleReq = new ArticleReq(); Article article = articleMapper.getLastestArticle();
articleReq.setId(article.getId()); ArticleReq articleReq = new ArticleReq();
articleReq.setUrl("http://www.test.test"); articleReq.setId(article.getId());
articleReq.setType(!article.getType()); articleReq.setUrl("http://www.test.test");
articleReq.setCategory("test"); articleReq.setType(!article.getType());
articleReq.setMdContent("test-" + article.getMdContent()); articleReq.setCategory("test");
articleReq.setOpen(!article.getOpen()); articleReq.setMdContent("test-" + article.getMdContent());
String tag1 = randomStr(4); articleReq.setOpen(!article.getOpen());
String tag2 = randomStr(4); String tag1 = randomStr(4);
String[] tagList = {"test", tag1, tag2}; String tag2 = randomStr(4);
articleReq.setTags(tagList); String[] tagList = {"test", tag1, tag2};
articleReq.setTitle("test-" + article.getTitle()); articleReq.setTags(tagList);
try { articleReq.setTitle("test-" + article.getTitle());
getMockData(put("/admin/article/update"), adminLogin(), articleReq).andDo(result -> { try {
Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE); getMockData(put("/admin/article/update"), adminLogin(), articleReq).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE);
ArticleModel a = response.getResult(); assertEquals(SUCCESS.getCode(), response.getCode());
assertEquals(articleReq.getCategory(), a.getCategory()); ArticleModel a = response.getResult();
assertEquals(articleReq.getUrl(), a.getUrl()); assertEquals(articleReq.getCategory(), a.getCategory());
assertEquals(articleReq.getMdContent(), a.getMdContent()); assertEquals(articleReq.getUrl(), a.getUrl());
assertEquals(articleReq.getTitle(), a.getTitle()); assertEquals(articleReq.getMdContent(), a.getMdContent());
assertEquals(articleReq.getType(), a.getOriginal()); assertEquals(articleReq.getTitle(), a.getTitle());
// Tag assertEquals(articleReq.getType(), a.getOriginal());
List<Tag> asList = a.getTags(); // Tag
assertEquals(3, asList.size()); List<Tag> asList = a.getTags();
assertEquals(articleReq.getOpen(), a.getOpen()); assertEquals(3, asList.size());
assertEquals(articleReq.getId(), a.getId()); assertEquals(articleReq.getOpen(), a.getOpen());
}); assertEquals(articleReq.getId(), a.getId());
} catch (Exception e) { });
e.printStackTrace(); } catch (Exception e) {
} e.printStackTrace();
} }
}
@Test
public void retrieveOneById() { @Test
try { public void retrieveOneById() {
long articleID = 3; try {
getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID)); long articleID = 3;
getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID + "?update=true")); getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID));
getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID + "?update=true"));
// 文章不存在
getMockData(MockMvcRequestBuilders.get("/article/articleID/-1")) // 文章不存在
.andDo(result -> assertEquals(ARTICLE_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); getMockData(MockMvcRequestBuilders.get("/article/articleID/-1"))
.andDo(result -> assertEquals(ARTICLE_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode()));
// 正常情况
getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID + "?update=false")).andDo(result -> { // 正常情况
Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE); getMockData(MockMvcRequestBuilders.get("/article/articleID/" + articleID + "?update=false")).andDo(result -> {
// 断言获取数据成功 Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); // 断言获取数据成功
assertNotNull(response.getResult()); assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult());
ArticleModel a = response.getResult();
assertNotNull(a.getTitle()); ArticleModel a = response.getResult();
assertNotNull(a.getId()); assertNotNull(a.getTitle());
assertNotNull(a.getSummary()); assertNotNull(a.getId());
assertNotNull(a.getMdContent()); assertNotNull(a.getSummary());
assertNotNull(a.getUrl()); assertNotNull(a.getMdContent());
assertNotNull(a.getUpdateDateFormat()); assertNotNull(a.getUrl());
assertTrue(a.getPreArticle() != null || a.getNextArticle() != null); assertNotNull(a.getUpdateDateFormat());
assertNotNull(a.getReadingNumber()); assertTrue(a.getPreArticle() != null || a.getNextArticle() != null);
assertNotNull(a.getOriginal()); assertNotNull(a.getReadingNumber());
assertNotNull(a.getPublishDateFormat()); assertNotNull(a.getOriginal());
assertNotNull(a.getCategory()); assertNotNull(a.getPublishDateFormat());
assertNotNull(a.getTags()); assertNotNull(a.getCategory());
assertNotNull(a.getAuthor()); assertNotNull(a.getTags());
}); assertNotNull(a.getAuthor());
} catch (Exception e) { });
e.printStackTrace(); } catch (Exception e) {
} e.printStackTrace();
} }
}
@Test
public void articles() { @Test
try { public void articles() {
// 测试不带参数访问 try {
getMockData(MockMvcRequestBuilders.get("/articles")); // 测试不带参数访问
getMockData(MockMvcRequestBuilders.get("/articles?page=1&count=5")).andDo(result -> { getMockData(MockMvcRequestBuilders.get("/articles"));
Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); getMockData(MockMvcRequestBuilders.get("/articles?page=1&count=5")).andDo(result -> {
// 断言获取数据成功 Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); // 断言获取数据成功
// 结果集非空 assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult()); // 结果集非空
// 判断pageInfo是否包装完全 assertNotNull(response.getResult());
PageData<ArticleModel> pageData = response.getResult(); // 判断pageInfo是否包装完全
assertNotEquals(0, pageData.getTotal()); PageData<ArticleModel> pageData = response.getResult();
assertEquals(1, pageData.getPageNum()); assertNotEquals(0, pageData.getTotal());
assertEquals(5, pageData.getPageSize()); assertEquals(1, pageData.getPageNum());
// 内容完整 assertEquals(5, pageData.getPageSize());
for (ArticleModel a : pageData.getList()) { // 内容完整
assertNotNull(a.getTitle()); for (ArticleModel a : pageData.getList()) {
assertNotNull(a.getId()); assertNotNull(a.getTitle());
assertNotNull(a.getSummary()); assertNotNull(a.getId());
assertNotNull(a.getOriginal()); assertNotNull(a.getSummary());
assertNotNull(a.getPublishDateFormat()); assertNotNull(a.getOriginal());
assertNotNull(a.getCategory()); assertNotNull(a.getPublishDateFormat());
assertNotNull(a.getTags()); assertNotNull(a.getCategory());
assertNotNull(a.getAuthor()); assertNotNull(a.getTags());
assertNull(a.getOpen()); assertNotNull(a.getAuthor());
assertNull(a.getMdContent()); assertNull(a.getOpen());
} assertNull(a.getMdContent());
}); }
} catch (Exception e) { });
e.printStackTrace(); } catch (Exception e) {
} e.printStackTrace();
} }
}
@Test
public void adminArticles() { @Test
try { public void adminArticles() {
getMockData(get("/admin/articles?page=1&count=10")).andExpect(result -> try {
assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result, STRING_TYPE).getCode()) getMockData(get("/admin/articles?page=1&count=5")).andExpect(result ->
); assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result, ARTICLE_MODEL_PAGE_TYPE).getCode())
);
// User权限登陆
getMockData(get("/admin/articles?page=1&count=10"), userLogin()).andDo(result -> // User权限登陆
assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, STRING_TYPE).getCode()) getMockData(get("/admin/articles?page=1&count=5"), userLogin()).andDo(result ->
); assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, ARTICLE_MODEL_PAGE_TYPE).getCode())
for (int i = 0; i < 2; i++) { );
// admin权限登陆 for (int i = 0; i < 2; i++) {
int finalI = i; // admin权限登陆
getMockData(get("/admin/articles?page=1&count=10&deleted=" + (i == 1)), adminLogin()).andDo(result -> { int finalI = i;
Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); getMockData(get("/admin/articles?page=1&count=5&deleted=" + (i == 1)), adminLogin()).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE);
assertNotNull(response.getResult()); assertEquals(SUCCESS.getCode(), response.getCode());
// 判断pageInfo是否包装完全 assertNotNull(response.getResult());
PageData<ArticleModel> pageData = response.getResult(); // 判断pageInfo是否包装完全
assertNotEquals(0, pageData.getTotal()); PageData<ArticleModel> pageData = response.getResult();
assertEquals(1, pageData.getPageNum()); assertNotEquals(0, pageData.getTotal());
assertEquals(10, pageData.getPageSize()); assertEquals(1, pageData.getPageNum());
// 内容完整 assertEquals(5, pageData.getPageSize());
for (ArticleModel a : pageData.getList()) { // 内容完整
assertNotNull(a.getTitle()); for (ArticleModel a : pageData.getList()) {
assertNotNull(a.getId()); assertNotNull(a.getTitle());
assertNotNull(a.getOriginal()); assertNotNull(a.getId());
assertNotNull(a.getPublishDateFormat()); assertNotNull(a.getOriginal());
assertNotNull(a.getOpen()); assertNotNull(a.getPublishDateFormat());
assertNotNull(a.getReadingNumber()); assertNotNull(a.getOpen());
assertNotNull(a.getLikeCount()); assertNotNull(a.getReadingNumber());
assertNotNull(a.getDislikeCount()); assertNotNull(a.getLikeCount());
assertEquals((finalI == 1), a.isDeleted()); assertNotNull(a.getDislikeCount());
assertNull(a.getMdContent()); assertEquals((finalI == 1), a.isDeleted());
} assertNull(a.getMdContent());
}); }
} });
} catch (Exception e) { }
e.printStackTrace(); } catch (Exception e) {
} e.printStackTrace();
} }
}
@Test
public void findByCategory() { @Test
try { public void findByCategory() {
// 分类不存在 try {
String categoryName = "NoSuchCategory"; // 分类不存在
getMockData(MockMvcRequestBuilders.get("/articles/category/" + categoryName + "?page=1&count=10")) String categoryName = "NoSuchCategory";
.andDo(result -> assertEquals(CATEGORY_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); getMockData(MockMvcRequestBuilders.get("/articles/category/" + categoryName + "?page=1&count=10"))
// 正常查询 .andDo(result -> assertEquals(CATEGORY_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode()));
categoryName = "linux"; // 正常查询
getMockData(MockMvcRequestBuilders.get("/articles/category/" + categoryName + "?page=1&count=10")) categoryName = "linux";
.andDo(result -> { getMockData(MockMvcRequestBuilders.get("/articles/category/" + categoryName + "?page=1&count=10"))
Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); .andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE);
PageData<ArticleModel> pageData = response.getResult(); assertEquals(SUCCESS.getCode(), response.getCode());
assertNotEquals(0, pageData.getTotal()); PageData<ArticleModel> pageData = response.getResult();
assertEquals(1, pageData.getPageNum()); assertNotEquals(0, pageData.getTotal());
assertEquals(10, pageData.getPageSize()); assertEquals(1, pageData.getPageNum());
for (ArticleModel arc : pageData.getList()) { assertEquals(10, pageData.getPageSize());
assertNotEquals(0, arc.getId().longValue()); for (ArticleModel arc : pageData.getList()) {
assertNotNull(arc.getTitle()); assertNotEquals(0, arc.getId().longValue());
assertNotNull(arc.getSummary()); assertNotNull(arc.getTitle());
} assertNotNull(arc.getSummary());
}); }
} catch (Exception e) { });
e.printStackTrace(); } catch (Exception e) {
} e.printStackTrace();
} }
}
@Test
public void findByTag() { @Test
try { public void findByTag() {
// 分类不存在 try {
String tagName = "NoSuchTag"; // 分类不存在
getMockData(MockMvcRequestBuilders.get("/articles/tag/" + tagName + "?page=1&count=10")) String tagName = "NoSuchTag";
.andDo(result -> assertEquals(TAG_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); getMockData(MockMvcRequestBuilders.get("/articles/tag/" + tagName + "?page=1&count=10"))
// 正常查询 .andDo(result -> assertEquals(TAG_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode()));
tagName = "linux"; // 正常查询
getMockData(MockMvcRequestBuilders.get("/articles/tag/" + tagName + "?page=1&count=10")) tagName = "linux";
.andDo(result -> { getMockData(MockMvcRequestBuilders.get("/articles/tag/" + tagName + "?page=1&count=10"))
Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE); .andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE);
PageData<ArticleModel> pageData = response.getResult(); assertEquals(SUCCESS.getCode(), response.getCode());
assertNotEquals(0, pageData.getTotal()); PageData<ArticleModel> pageData = response.getResult();
assertEquals(1, pageData.getPageNum()); assertNotEquals(0, pageData.getTotal());
assertEquals(10, pageData.getPageSize()); assertEquals(1, pageData.getPageNum());
assertEquals(10, pageData.getPageSize());
for (ArticleModel arc : pageData.getList()) {
assertNotEquals(0, arc.getId().longValue()); for (ArticleModel arc : pageData.getList()) {
assertNotNull(arc.getTitle()); assertNotEquals(0, arc.getId().longValue());
assertNotNull(arc.getSummary()); assertNotNull(arc.getTitle());
} assertNotNull(arc.getSummary());
}); }
} catch (Exception e) { });
e.printStackTrace(); } catch (Exception e) {
} e.printStackTrace();
} }
}
} }

View File

@@ -0,0 +1,55 @@
package cn.celess.article.serviceimpl;
import cn.celess.article.ArticleBaseTest;
import cn.celess.common.entity.vo.ArticleModel;
import cn.celess.common.entity.vo.PageData;
import cn.celess.common.mapper.ArticleMapper;
import cn.celess.common.service.ArticleService;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import static org.junit.Assert.*;
public class ArticleServiceTest extends ArticleBaseTest {
@Autowired
ArticleService articleService;
@Resource
ArticleMapper articleMapper;
@Test
public void adminArticles() {
// 测deleted参数传值
PageData<ArticleModel> pageData = articleService.adminArticles(10, 1, true);
assertTrue(pageData.getList().stream().allMatch(ArticleModel::isDeleted));
pageData = articleService.adminArticles(10, 1, false);
assertFalse(pageData.getList().stream().allMatch(ArticleModel::isDeleted));
pageData = articleService.adminArticles(10, 1, null);
assertTrue(pageData.getList().stream().anyMatch(ArticleModel::isDeleted));
assertTrue(pageData.getList().stream().anyMatch(articleModel -> !articleModel.isDeleted()));
}
@Test
public void retrievePageForOpen() {
PageData<ArticleModel> articleModelPageData = articleService.retrievePageForOpen(10, 1);
assertEquals(10, articleModelPageData.getPageSize());
assertEquals(1, articleModelPageData.getPageNum());
assertEquals(10, articleModelPageData.getList().size());
articleModelPageData.getList().forEach(Assert::assertNotNull);
// 测试open字段
articleModelPageData.getList().forEach(articleModel -> {
// 当前文章
assertTrue(articleMapper.findArticleById(articleModel.getId()).getOpen());
if (articleModel.getPreArticle() != null) {
assertTrue(articleMapper.findArticleById(articleModel.getPreArticle().getId()).getOpen());
}
if (articleModel.getNextArticle() != null) {
assertTrue(articleMapper.findArticleById(articleModel.getNextArticle().getId()).getOpen());
}
});
}
}

33
blog-categorytag/pom.xml Normal file
View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>blog</artifactId>
<groupId>cn.celess</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>blog-categorytag</artifactId>
<dependencies>
<dependency>
<groupId>cn.celess</groupId>
<artifactId>blog-common</artifactId>
<version>${blog-common.version}</version>
</dependency>
<dependency>
<groupId>cn.celess</groupId>
<artifactId>blog-user</artifactId>
<version>${blog-user.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,19 @@
package cn.celess.categorytag;
import cn.celess.common.CommonApplication;
import cn.celess.user.UserApplication;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.SpringVersion;
@SpringBootApplication(scanBasePackageClasses = {CategoryTagApplication.class, CommonApplication.class, UserApplication.class})
public class CategoryTagApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(CategoryTagApplication.class)
.main(SpringVersion.class)
.bannerMode(Banner.Mode.CONSOLE)
.run(args);
}
}

View File

@@ -1,63 +1,63 @@
package cn.celess.blog.controller; package cn.celess.categorytag.controller;
import cn.celess.blog.entity.Response; import cn.celess.common.entity.Response;
import cn.celess.blog.service.CategoryService; import cn.celess.common.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/30 20:36 * @date : 2019/03/30 20:36
*/ */
@RestController @RestController
public class CategoryController { public class CategoryController {
@Autowired @Autowired
CategoryService categoryService; CategoryService categoryService;
/** /**
* 新增一个分类 * 新增一个分类
* *
* @param name 分类名 * @param name 分类名
* @return Response * @return Response
*/ */
@PostMapping("/admin/category/create") @PostMapping("/admin/category/create")
public Response addOne(@RequestParam("name") String name) { public Response addOne(@RequestParam("name") String name) {
return Response.success(categoryService.create(name)); return Response.success(categoryService.create(name));
} }
/** /**
* 删除一个分类 * 删除一个分类
* *
* @param id 分类id * @param id 分类id
* @return Response * @return Response
*/ */
@DeleteMapping("/admin/category/del") @DeleteMapping("/admin/category/del")
public Response deleteOne(@RequestParam("id") long id) { public Response deleteOne(@RequestParam("id") long id) {
return Response.success(categoryService.delete(id)); return Response.success(categoryService.delete(id));
} }
/** /**
* 更新一个分类 * 更新一个分类
* *
* @param id 分类id * @param id 分类id
* @param name 更新后的名字 * @param name 更新后的名字
* @return Response * @return Response
*/ */
@PutMapping("/admin/category/update") @PutMapping("/admin/category/update")
public Response updateOne(@RequestParam("id") Long id, public Response updateOne(@RequestParam("id") Long id,
@RequestParam("name") String name) { @RequestParam("name") String name) {
return Response.success(categoryService.update(id, name)); return Response.success(categoryService.update(id, name));
} }
/** /**
* 获取所有的分类 * 获取所有的分类
* *
* @return Response * @return Response
*/ */
@GetMapping("/categories") @GetMapping("/categories")
public Response getPage(@RequestParam(name = "page", defaultValue = "1") int page, public Response getPage(@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "count", defaultValue = "1000") int count) { @RequestParam(name = "count", defaultValue = "1000") int count) {
return Response.success(categoryService.retrievePage(page, count)); return Response.success(categoryService.retrievePage(page, count));
} }
} }

View File

@@ -1,59 +1,59 @@
package cn.celess.blog.controller; package cn.celess.categorytag.controller;
import cn.celess.blog.entity.Response; import cn.celess.common.entity.Response;
import cn.celess.blog.entity.model.TagModel; import cn.celess.common.entity.vo.TagModel;
import cn.celess.blog.service.TagService; import cn.celess.common.service.TagService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/30 20:36 * @date : 2019/03/30 20:36
*/ */
@RestController @RestController
public class TagController { public class TagController {
@Autowired @Autowired
TagService tagService; TagService tagService;
@PostMapping("/admin/tag/create") @PostMapping("/admin/tag/create")
public Response addOne(@RequestParam("name") String name) { public Response addOne(@RequestParam("name") String name) {
return Response.success(tagService.create(name)); return Response.success(tagService.create(name));
} }
@DeleteMapping("/admin/tag/del") @DeleteMapping("/admin/tag/del")
public Response delOne(@RequestParam("id") long id) { public Response delOne(@RequestParam("id") long id) {
return Response.success(tagService.delete(id)); return Response.success(tagService.delete(id));
} }
@PutMapping("/admin/tag/update") @PutMapping("/admin/tag/update")
public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) { public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) {
return Response.success(tagService.update(id, name)); return Response.success(tagService.update(id, name));
} }
@GetMapping("/tags") @GetMapping("/tags")
public Response getPage(@RequestParam(required = false, defaultValue = "10", value = "count") int count, public Response getPage(@RequestParam(required = false, defaultValue = "10", value = "count") int count,
@RequestParam(required = false, defaultValue = "1", value = "page") int page) { @RequestParam(required = false, defaultValue = "1", value = "page") int page) {
return Response.success(tagService.retrievePage(page, count)); return Response.success(tagService.retrievePage(page, count));
} }
@GetMapping("/tags/nac") @GetMapping("/tags/nac")
public Response getTagNameAndCount() { public Response getTagNameAndCount() {
List<Map<String, Object>> nameAndCount = new ArrayList<>(); List<Map<String, Object>> nameAndCount = new ArrayList<>();
List<TagModel> all = tagService.findAll(); List<TagModel> all = tagService.findAll();
for (TagModel t : all) { for (TagModel t : all) {
Map<String, Object> map = new HashMap<>(2); Map<String, Object> map = new HashMap<>(2);
map.put("name", t.getName()); map.put("name", t.getName());
map.put("size", t.getArticles().size()); map.put("size", t.getArticles().size());
nameAndCount.add(map); nameAndCount.add(map);
} }
return Response.success(nameAndCount); return Response.success(nameAndCount);
} }
} }

View File

@@ -1,92 +1,92 @@
package cn.celess.blog.service.serviceimpl; package cn.celess.categorytag.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum; import cn.celess.common.constant.ResponseEnum;
import cn.celess.blog.entity.Article; import cn.celess.common.entity.Article;
import cn.celess.blog.entity.Category; import cn.celess.common.entity.Category;
import cn.celess.blog.entity.model.ArticleModel; import cn.celess.common.entity.vo.ArticleModel;
import cn.celess.blog.entity.model.CategoryModel; import cn.celess.common.entity.vo.CategoryModel;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.exception.MyException; import cn.celess.common.exception.BlogResponseException;
import cn.celess.blog.mapper.ArticleMapper; import cn.celess.common.mapper.ArticleMapper;
import cn.celess.blog.mapper.CategoryMapper; import cn.celess.common.mapper.CategoryMapper;
import cn.celess.blog.service.CategoryService; import cn.celess.common.service.CategoryService;
import cn.celess.blog.util.ModalTrans; import cn.celess.common.util.ModalTrans;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 22:43 * @date : 2019/03/28 22:43
*/ */
@Service @Service
public class CategoryServiceImpl implements CategoryService { public class CategoryServiceImpl implements CategoryService {
@Autowired @Autowired
CategoryMapper categoryMapper; CategoryMapper categoryMapper;
@Autowired @Autowired
HttpServletRequest request; HttpServletRequest request;
@Autowired @Autowired
ArticleMapper articleMapper; ArticleMapper articleMapper;
@Override @Override
public CategoryModel create(String name) { public CategoryModel create(String name) {
if (categoryMapper.existsByName(name)) { if (categoryMapper.existsByName(name)) {
throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST); throw new BlogResponseException(ResponseEnum.CATEGORY_HAS_EXIST);
} }
Category category = new Category(); Category category = new Category();
category.setName(name); category.setName(name);
categoryMapper.insert(category); categoryMapper.insert(category);
return ModalTrans.category(category); return ModalTrans.category(category);
} }
@Override @Override
public boolean delete(long id) { public boolean delete(long id) {
Category category = categoryMapper.findCategoryById(id); Category category = categoryMapper.findCategoryById(id);
if (category == null) { if (category == null) {
throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST); throw new BlogResponseException(ResponseEnum.CATEGORY_NOT_EXIST);
} }
return categoryMapper.delete(id) == 1; return categoryMapper.delete(id) == 1;
} }
@Override @Override
public CategoryModel update(Long id, String name) { public CategoryModel update(Long id, String name) {
if (id == null) { if (id == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空"); throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空");
} }
Category category = categoryMapper.findCategoryById(id); Category category = categoryMapper.findCategoryById(id);
category.setName(name); category.setName(name);
categoryMapper.update(category); categoryMapper.update(category);
return ModalTrans.category(category); return ModalTrans.category(category);
} }
@Override @Override
public PageData<CategoryModel> retrievePage(int page, int count) { public PageData<CategoryModel> retrievePage(int page, int count) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Category> all = categoryMapper.findAll(); List<Category> all = categoryMapper.findAll();
// 遍历没一个category // 遍历没一个category
List<CategoryModel> modelList = all List<CategoryModel> modelList = all
.stream() .stream()
.map(ModalTrans::category) .map(ModalTrans::category)
.peek(categoryModel -> { .peek(categoryModel -> {
// 根据category去查article并赋值给categoryModel // 根据category去查article并赋值给categoryModel
List<Article> allByCategoryId = articleMapper.findAllByCategoryId(categoryModel.getId()); List<Article> allByCategoryId = articleMapper.findAllByCategoryId(categoryModel.getId());
List<ArticleModel> articleModelList = allByCategoryId List<ArticleModel> articleModelList = allByCategoryId
.stream() .stream()
.map(article -> ModalTrans.article(article, true)) .map(article -> ModalTrans.article(article, true))
.peek(articleModel -> { .peek(articleModel -> {
// 去除不必要的字段 // 去除不必要的字段
articleModel.setPreArticle(null); articleModel.setPreArticle(null);
articleModel.setNextArticle(null); articleModel.setNextArticle(null);
articleModel.setTags(null); articleModel.setTags(null);
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
categoryModel.setArticles(articleModelList); categoryModel.setArticles(articleModelList);
}).collect(Collectors.toList()); }).collect(Collectors.toList());
return new PageData<>(new PageInfo<>(all), modelList); return new PageData<>(new PageInfo<>(all), modelList);
} }
} }

View File

@@ -1,103 +1,103 @@
package cn.celess.blog.service.serviceimpl; package cn.celess.categorytag.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.ArticleTag; import cn.celess.common.constant.ResponseEnum;
import cn.celess.blog.entity.Tag; import cn.celess.common.entity.ArticleTag;
import cn.celess.blog.entity.model.ArticleModel; import cn.celess.common.entity.Tag;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.entity.model.TagModel; import cn.celess.common.entity.vo.TagModel;
import cn.celess.blog.exception.MyException; import cn.celess.common.exception.BlogResponseException;
import cn.celess.blog.mapper.ArticleMapper; import cn.celess.common.mapper.ArticleMapper;
import cn.celess.blog.mapper.ArticleTagMapper; import cn.celess.common.mapper.ArticleTagMapper;
import cn.celess.blog.mapper.TagMapper; import cn.celess.common.mapper.TagMapper;
import cn.celess.blog.service.TagService; import cn.celess.common.service.TagService;
import cn.celess.blog.util.ModalTrans; import cn.celess.common.util.ModalTrans;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 22:29 * @date : 2019/03/28 22:29
*/ */
@Service @Service
public class TagServiceImpl implements TagService { public class TagServiceImpl implements TagService {
@Autowired @Autowired
TagMapper tagMapper; TagMapper tagMapper;
@Autowired @Autowired
HttpServletRequest request; HttpServletRequest request;
@Autowired @Autowired
ArticleMapper articleMapper; ArticleMapper articleMapper;
@Autowired @Autowired
ArticleTagMapper articleTagMapper; ArticleTagMapper articleTagMapper;
@Override @Override
public TagModel create(String name) { public TagModel create(String name) {
boolean b = tagMapper.existsByName(name); boolean b = tagMapper.existsByName(name);
if (b) { if (b) {
throw new MyException(ResponseEnum.TAG_HAS_EXIST); throw new BlogResponseException(ResponseEnum.TAG_HAS_EXIST);
} }
Tag tag = new Tag(); Tag tag = new Tag();
tag.setName(name); tag.setName(name);
tagMapper.insert(tag); tagMapper.insert(tag);
return ModalTrans.tag(tag); return ModalTrans.tag(tag);
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public boolean delete(long tagId) { public boolean delete(long tagId) {
Tag tag = tagMapper.findTagById(tagId); Tag tag = tagMapper.findTagById(tagId);
if (tag == null) { if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST); throw new BlogResponseException(ResponseEnum.TAG_NOT_EXIST);
} }
List<ArticleTag> articleByTag = articleTagMapper.findArticleByTag(tagId); List<ArticleTag> articleByTag = articleTagMapper.findArticleByTag(tagId);
// 删除文章 // 删除文章
articleByTag.forEach(articleTag -> articleMapper.delete(articleTag.getArticle().getId())); articleByTag.forEach(articleTag -> articleMapper.delete(articleTag.getArticle().getId()));
return tagMapper.delete(tagId) == 1; return tagMapper.delete(tagId) == 1;
} }
@Override @Override
public TagModel update(Long id, String name) { public TagModel update(Long id, String name) {
if (id == null) { if (id == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID"); throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID");
} }
Tag tag = tagMapper.findTagById(id); Tag tag = tagMapper.findTagById(id);
tag.setName(name); tag.setName(name);
tagMapper.update(tag); tagMapper.update(tag);
return ModalTrans.tag(tag); return ModalTrans.tag(tag);
} }
@Override @Override
public PageData<TagModel> retrievePage(int page, int count) { public PageData<TagModel> retrievePage(int page, int count) {
PageHelper.startPage(page, count); PageHelper.startPage(page, count);
List<Tag> tagList = tagMapper.findAll(); List<Tag> tagList = tagMapper.findAll();
List<TagModel> modelList = new ArrayList<>(); List<TagModel> modelList = new ArrayList<>();
tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag))); tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag)));
return new PageData<>(new PageInfo<>(tagList), modelList); return new PageData<>(new PageInfo<>(tagList), modelList);
} }
@Override @Override
public List<TagModel> findAll() { public List<TagModel> findAll() {
return tagMapper.findAll().stream() return tagMapper.findAll().stream()
.map(ModalTrans::tag) .map(ModalTrans::tag)
.peek(tagModel -> { .peek(tagModel -> {
List<ArticleTag> articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(tagModel.getId()); List<ArticleTag> articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(tagModel.getId());
tagModel.setArticles( tagModel.setArticles(
articleByTagAndOpen articleByTagAndOpen
.stream() .stream()
.map(articleTag -> ModalTrans.article(articleTag.getArticle(), true)) .map(articleTag -> ModalTrans.article(articleTag.getArticle(), true))
.collect(Collectors.toList()) .collect(Collectors.toList())
); );
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
} }

View File

@@ -0,0 +1,12 @@
${AnsiColor.BRIGHT_GREEN}
_ _ _ ____ _ _______
| | | | (_) | _ \ | | |__ __|
| |__| | _ | |_) | | | ___ __ _ ______ | | __ _ __ _
| __ | | | | _ < | | / _ \ / _` | |______| | | / _` | / _` |
| | | | | | | |_) | | | | (_) | | (_| | | | | (_| | | (_| |
|_| |_| |_| |____/ |_| \___/ \__, | |_| \__,_| \__, |
__/ | __/ |
|___/ |___/
${AnsiColor.BRIGHT_RED}
Application Version: ${application.version}${application.formatted-version}
Spring Boot Version: ${spring-boot.version}${spring-boot.formatted-version}

View File

@@ -0,0 +1,11 @@
package cn.celess.categorytag;
import cn.celess.common.test.BaseTest;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = {CategoryTagApplication.class})
@RunWith(SpringRunner.class)
public abstract class CategoryTagBaseTest extends BaseTest {
}

View File

@@ -1,78 +1,78 @@
package cn.celess.blog.controller; package cn.celess.categorytag.controller;
import cn.celess.blog.BaseTest; import cn.celess.categorytag.CategoryTagBaseTest;
import cn.celess.blog.entity.Category; import cn.celess.common.entity.Category;
import cn.celess.blog.entity.Response; import cn.celess.common.entity.Response;
import cn.celess.blog.entity.model.CategoryModel; import cn.celess.common.entity.vo.CategoryModel;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.mapper.CategoryMapper; import cn.celess.common.mapper.CategoryMapper;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; import static cn.celess.common.constant.ResponseEnum.SUCCESS;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
public class CategoryControllerTest extends BaseTest { public class CategoryControllerTest extends CategoryTagBaseTest {
@Autowired @Autowired
CategoryMapper categoryMapper; CategoryMapper categoryMapper;
private static final TypeReference<?> CATEGORY_MODEL_TYPE = new TypeReference<Response<CategoryModel>>() { private static final TypeReference<?> CATEGORY_MODEL_TYPE = new TypeReference<Response<CategoryModel>>() {
}; };
private static final TypeReference<?> CATEGORY_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<CategoryModel>>>() { private static final TypeReference<?> CATEGORY_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<CategoryModel>>>() {
}; };
@Test @Test
public void addOne() throws Exception { public void addOne() throws Exception {
String categoryName = randomStr(4); String categoryName = randomStr(4);
getMockData(post("/admin/category/create?name=" + categoryName), adminLogin()).andDo(result -> { getMockData(post("/admin/category/create?name=" + categoryName), adminLogin()).andDo(result -> {
Response<CategoryModel> response = getResponse(result, CATEGORY_MODEL_TYPE); Response<CategoryModel> response = getResponse(result, CATEGORY_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
CategoryModel category = response.getResult(); CategoryModel category = response.getResult();
assertEquals(categoryName, category.getName()); assertEquals(categoryName, category.getName());
assertNotNull(category.getId()); assertNotNull(category.getId());
assertNull(category.getArticles()); assertNull(category.getArticles());
}); });
} }
@Test @Test
public void deleteOne() throws Exception { public void deleteOne() throws Exception {
Category category = categoryMapper.getLastestCategory(); Category category = categoryMapper.getLastestCategory();
getMockData(delete("/admin/category/del?id=" + category.getId()), adminLogin()).andDo(result -> { getMockData(delete("/admin/category/del?id=" + category.getId()), adminLogin()).andDo(result -> {
Response<Boolean> response = getResponse(result, BOOLEAN_TYPE); Response<Boolean> response = getResponse(result, BOOLEAN_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
assertTrue(response.getResult()); assertTrue(response.getResult());
}); });
} }
@Test @Test
public void updateOne() throws Exception { public void updateOne() throws Exception {
Category category = categoryMapper.getLastestCategory(); Category category = categoryMapper.getLastestCategory();
String name = randomStr(4); String name = randomStr(4);
getMockData(put("/admin/category/update?id=" + category.getId() + "&name=" + name), adminLogin()).andDo(result -> { getMockData(put("/admin/category/update?id=" + category.getId() + "&name=" + name), adminLogin()).andDo(result -> {
// Response<CategoryModel> response = mapper.readValue(result.getResponse().getContentAsString(), new ResponseType<Response<CategoryModel>>()); // Response<CategoryModel> response = mapper.readValue(result.getResponse().getContentAsString(), new ResponseType<Response<CategoryModel>>());
Response<CategoryModel> response = getResponse(result, CATEGORY_MODEL_TYPE); Response<CategoryModel> response = getResponse(result, CATEGORY_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
CategoryModel c = response.getResult(); CategoryModel c = response.getResult();
assertEquals(name, c.getName()); assertEquals(name, c.getName());
assertNull(c.getArticles()); assertNull(c.getArticles());
assertNotNull(c.getId()); assertNotNull(c.getId());
}); });
} }
@Test @Test
public void getPage() throws Exception { public void getPage() throws Exception {
getMockData(get("/categories")).andDo(result -> { getMockData(get("/categories")).andDo(result -> {
Response<PageData<CategoryModel>> response = getResponse(result, CATEGORY_MODEL_PAGE_TYPE); Response<PageData<CategoryModel>> response = getResponse(result, CATEGORY_MODEL_PAGE_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult()); assertNotNull(response.getResult());
response.getResult().getList().forEach(c -> { response.getResult().getList().forEach(c -> {
assertNotNull(c.getName()); assertNotNull(c.getName());
assertNotNull(c.getId()); assertNotNull(c.getId());
assertNotNull(c.getArticles()); assertNotNull(c.getArticles());
}); });
}); });
} }
} }

View File

@@ -1,110 +1,111 @@
package cn.celess.blog.controller; package cn.celess.categorytag.controller;
import cn.celess.blog.BaseTest;
import cn.celess.blog.entity.Response; import cn.celess.categorytag.CategoryTagBaseTest;
import cn.celess.blog.entity.Tag; import cn.celess.common.entity.Response;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.Tag;
import cn.celess.blog.entity.model.TagModel; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.mapper.TagMapper; import cn.celess.common.entity.vo.TagModel;
import com.fasterxml.jackson.core.type.TypeReference; import cn.celess.common.mapper.TagMapper;
import org.junit.Test; import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Map; import java.util.List;
import java.util.Map;
import static cn.celess.blog.enmu.ResponseEnum.*;
import static org.junit.Assert.*; import static cn.celess.common.constant.ResponseEnum.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
public class TagControllerTest extends BaseTest {
@Autowired public class TagControllerTest extends CategoryTagBaseTest {
TagMapper tagMapper; @Autowired
private static final TypeReference<?> TAG_MODEL_TYPE = new TypeReference<Response<TagModel>>() { TagMapper tagMapper;
private static final TypeReference<?> TAG_MODEL_TYPE = new TypeReference<Response<TagModel>>() {
};
private static final TypeReference<?> TAG_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<TagModel>>>() { };
}; private static final TypeReference<?> TAG_MODEL_PAGE_TYPE = new TypeReference<Response<PageData<TagModel>>>() {
private static final TypeReference<?> TAG_NAC_LIST_TYPE = new TypeReference<Response<List<Map<String, Object>>>>() { };
}; private static final TypeReference<?> TAG_NAC_LIST_TYPE = new TypeReference<Response<List<Map<String, Object>>>>() {
};
@Test
public void addOne() throws Exception { @Test
String name = randomStr(4); public void addOne() throws Exception {
getMockData(post("/admin/tag/create?name=" + name)).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result, STRING_TYPE).getCode())); String name = randomStr(4);
getMockData(post("/admin/tag/create?name=" + name), userLogin()).andDo(result -> assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, STRING_TYPE).getCode())); getMockData(post("/admin/tag/create?name=" + name)).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), getResponse(result, STRING_TYPE).getCode()));
getMockData(post("/admin/tag/create?name=" + name), adminLogin()).andDo(result -> { getMockData(post("/admin/tag/create?name=" + name), userLogin()).andDo(result -> assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, STRING_TYPE).getCode()));
Response<TagModel> response = getResponse(result, TAG_MODEL_TYPE); getMockData(post("/admin/tag/create?name=" + name), adminLogin()).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<TagModel> response = getResponse(result, TAG_MODEL_TYPE);
TagModel tag = response.getResult(); assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(tag.getId()); TagModel tag = response.getResult();
assertEquals(name, tag.getName()); assertNotNull(tag.getId());
}); assertEquals(name, tag.getName());
});
}
}
@Test
public void delOne() throws Exception { @Test
Tag lastestTag = tagMapper.getLastestTag(); public void delOne() throws Exception {
assertNotNull(lastestTag.getId()); Tag lastestTag = tagMapper.getLastestTag();
getMockData(delete("/admin/tag/del?id=" + lastestTag.getId()), adminLogin()).andDo(result -> { assertNotNull(lastestTag.getId());
Response<Boolean> response = getResponse(result, BOOLEAN_TYPE); getMockData(delete("/admin/tag/del?id=" + lastestTag.getId()), adminLogin()).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<Boolean> response = getResponse(result, BOOLEAN_TYPE);
assertTrue(response.getResult()); assertEquals(SUCCESS.getCode(), response.getCode());
}); assertTrue(response.getResult());
long id = lastestTag.getId() * 2; });
getMockData(delete("/admin/tag/del?id=" + id), adminLogin()) long id = lastestTag.getId() * 2;
.andDo(result -> assertEquals(TAG_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode())); getMockData(delete("/admin/tag/del?id=" + id), adminLogin())
.andDo(result -> assertEquals(TAG_NOT_EXIST.getCode(), getResponse(result, STRING_TYPE).getCode()));
}
}
@Test
public void updateOne() throws Exception { @Test
Tag tag = tagMapper.getLastestTag(); public void updateOne() throws Exception {
assertNotNull(tag.getId()); Tag tag = tagMapper.getLastestTag();
String name = randomStr(4); assertNotNull(tag.getId());
getMockData(put("/admin/tag/update?id=" + tag.getId() + "&name=" + name), adminLogin()).andDo(result -> { String name = randomStr(4);
Response<TagModel> response = getResponse(result, TAG_MODEL_TYPE); getMockData(put("/admin/tag/update?id=" + tag.getId() + "&name=" + name), adminLogin()).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<TagModel> response = getResponse(result, TAG_MODEL_TYPE);
assertNotNull(response.getResult()); assertEquals(SUCCESS.getCode(), response.getCode());
TagModel t = response.getResult(); assertNotNull(response.getResult());
assertEquals(name, t.getName()); TagModel t = response.getResult();
assertEquals(tag.getId(), t.getId()); assertEquals(name, t.getName());
}); assertEquals(tag.getId(), t.getId());
});
}
}
@Test
public void getPage() throws Exception { @Test
getMockData(get("/tags?page=1&count=5")).andDo(result -> { public void getPage() throws Exception {
Response<PageData<TagModel>> response = getResponse(result, TAG_MODEL_PAGE_TYPE); getMockData(get("/tags?page=1&count=5")).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<PageData<TagModel>> response = getResponse(result, TAG_MODEL_PAGE_TYPE);
// 结果集非空 assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult()); // 结果集非空
// 判断pageInfo是否包装完全 assertNotNull(response.getResult());
PageData<TagModel> pageData = response.getResult(); // 判断pageInfo是否包装完全
assertNotEquals(0, pageData.getTotal()); PageData<TagModel> pageData = response.getResult();
assertEquals(1, pageData.getPageNum()); assertNotEquals(0, pageData.getTotal());
assertEquals(5, pageData.getPageSize()); assertEquals(1, pageData.getPageNum());
// 内容完整 assertEquals(5, pageData.getPageSize());
for (TagModel t : pageData.getList()) { // 内容完整
assertNotNull(t.getId()); for (TagModel t : pageData.getList()) {
assertNotNull(t.getName()); assertNotNull(t.getId());
} assertNotNull(t.getName());
}); }
} });
}
@Test
public void getTagNameAndCount() throws Exception { @Test
getMockData(get("/tags/nac")).andDo(result -> { public void getTagNameAndCount() throws Exception {
Response<List<Map<String, Object>>> response = getResponse(result, TAG_NAC_LIST_TYPE); getMockData(get("/tags/nac")).andDo(result -> {
assertEquals(SUCCESS.getCode(), response.getCode()); Response<List<Map<String, Object>>> response = getResponse(result, TAG_NAC_LIST_TYPE);
assertNotNull(response.getResult()); assertEquals(SUCCESS.getCode(), response.getCode());
response.getResult().forEach(o -> { assertNotNull(response.getResult());
assertNotNull(o.get("name")); response.getResult().forEach(o -> {
assertNotNull(o.get("size")); assertNotNull(o.get("name"));
}); assertNotNull(o.get("size"));
}); });
} });
}
} }

34
blog-comment/pom.xml Normal file
View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>blog</artifactId>
<groupId>cn.celess</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>blog-comment</artifactId>
<dependencies>
<dependency>
<groupId>cn.celess</groupId>
<artifactId>blog-common</artifactId>
<version>${blog-common.version}</version>
</dependency>
<dependency>
<groupId>cn.celess</groupId>
<artifactId>blog-user</artifactId>
<version>${blog-user.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,18 @@
package cn.celess.comment;
import cn.celess.common.CommonApplication;
import cn.celess.user.UserApplication;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.core.SpringVersion;
@SpringBootApplication(scanBasePackageClasses = {CommentApplication.class, CommonApplication.class, UserApplication.class})
public class CommentApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(CommentApplication.class)
.main(SpringVersion.class)
.bannerMode(Banner.Mode.CONSOLE)
.run(args);
}
}

View File

@@ -1,119 +1,119 @@
package cn.celess.blog.controller; package cn.celess.comment.controller;
import cn.celess.blog.entity.Response; import cn.celess.common.entity.Response;
import cn.celess.blog.entity.request.CommentReq; import cn.celess.common.entity.dto.CommentReq;
import cn.celess.blog.service.CommentService; import cn.celess.common.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/30 20:37 * @date : 2019/03/30 20:37
*/ */
@RestController @RestController
public class CommentController { public class CommentController {
@Autowired @Autowired
CommentService commentService; CommentService commentService;
/** /**
* 新增一条评论数据 * 新增一条评论数据
* *
* @param reqBody 请求数据 * @param reqBody 请求数据
* @return Response * @return Response
*/ */
@PostMapping("/user/comment/create") @PostMapping("/user/comment/create")
public Response addOne(@RequestBody CommentReq reqBody) { public Response addOne(@RequestBody CommentReq reqBody) {
return Response.success(commentService.create(reqBody)); return Response.success(commentService.create(reqBody));
} }
@DeleteMapping("/user/comment/del") @DeleteMapping("/user/comment/del")
public Response delete(@RequestParam("id") long id) { public Response delete(@RequestParam("id") long id) {
return Response.success(commentService.delete(id)); return Response.success(commentService.delete(id));
} }
@PutMapping("/user/comment/update") @PutMapping("/user/comment/update")
public Response update(@RequestBody CommentReq reqBody) { public Response update(@RequestBody CommentReq reqBody) {
return Response.success(commentService.update(reqBody)); return Response.success(commentService.update(reqBody));
} }
/** /**
* 获取所有的评论 * 获取所有的评论
* *
* @param pagePath pagePath * @param pagePath pagePath
* @param count 单页数据量 * @param count 单页数据量
* @param page 页码 * @param page 页码
* @return Response * @return Response
*/ */
@GetMapping("/comments/{pagePath}/{pid}") @GetMapping("/comments/{pagePath}/{pid}")
public Response commentsOfArticle(@PathVariable("pagePath") String pagePath, @PathVariable(value = "pid") long pid, public Response commentsOfArticle(@PathVariable("pagePath") String pagePath, @PathVariable(value = "pid") long pid,
@RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) { @RequestParam(value = "page", required = false, defaultValue = "1") int page) {
String path = ""; String path = "";
if (pagePath.contains("article+")) { if (pagePath.contains("article+")) {
path = "article/" + pagePath.split("\\+", 2)[1]; path = "article/" + pagePath.split("\\+", 2)[1];
} else { } else {
path = pagePath; path = pagePath;
} }
if ("*".equals(pagePath)) { if ("*".equals(pagePath)) {
path = null; path = null;
} }
return Response.success(commentService.retrievePageByPageAndPid(path, pid, page, count)); return Response.success(commentService.retrievePageByPageAndPid(path, pid, page, count));
} }
/** /**
* 通过pid获取数据 * 通过pid获取数据
* *
* @param pagePath pagePath * @param pagePath pagePath
* @param count count * @param count count
* @param page page * @param page page
* @return Response * @return Response
*/ */
@GetMapping("/comment/pagePath/{pagePath}") @GetMapping("/comment/pagePath/{pagePath}")
public Response retrievePage(@PathVariable("pagePath") String pagePath, public Response retrievePage(@PathVariable("pagePath") String pagePath,
@RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) { @RequestParam(value = "page", required = false, defaultValue = "1") int page) {
String path = ""; String path = "";
if (pagePath.contains("article+")) { if (pagePath.contains("article+")) {
path = "article/" + pagePath.split("\\+", 2)[1]; path = "article/" + pagePath.split("\\+", 2)[1];
} else { } else {
path = pagePath; path = pagePath;
} }
if ("*".equals(pagePath)) { if ("*".equals(pagePath)) {
path = null; path = null;
} }
return Response.success(commentService.retrievePage(path, page, count)); return Response.success(commentService.retrievePage(path, page, count));
} }
@GetMapping("/user/comment/pagePath/{pagePath}") @GetMapping("/user/comment/pagePath/{pagePath}")
public Response userComment(@PathVariable("pagePath") String pagePath, public Response userComment(@PathVariable("pagePath") String pagePath,
@RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) { @RequestParam(value = "page", required = false, defaultValue = "1") int page) {
String path = ""; String path = "";
if (pagePath.contains("article+")) { if (pagePath.contains("article+")) {
path = "article/" + pagePath.split("\\+", 2)[1]; path = "article/" + pagePath.split("\\+", 2)[1];
} else { } else {
path = pagePath; path = pagePath;
} }
if ("*".equals(pagePath)) { if ("*".equals(pagePath)) {
path = null; path = null;
} }
return Response.success(commentService.retrievePageByAuthor(path, page, count)); return Response.success(commentService.retrievePageByAuthor(path, page, count));
} }
@GetMapping("/admin/comment/pagePath/{pagePath}") @GetMapping("/admin/comment/pagePath/{pagePath}")
public Response adminComment(@PathVariable("pagePath") String pagePath, public Response adminComment(@PathVariable("pagePath") String pagePath,
@RequestParam(value = "count", required = false, defaultValue = "10") int count, @RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) { @RequestParam(value = "page", required = false, defaultValue = "1") int page) {
String path = ""; String path = "";
if (pagePath.contains("article+")) { if (pagePath.contains("article+")) {
path = "article/" + pagePath.split("\\+", 2)[1]; path = "article/" + pagePath.split("\\+", 2)[1];
} else { } else {
path = pagePath; path = pagePath;
} }
if ("*".equals(pagePath)) { if ("*".equals(pagePath)) {
path = null; path = null;
} }
return Response.success(commentService.retrievePageByPage(path, page, count)); return Response.success(commentService.retrievePageByPage(path, page, count));
} }
} }

View File

@@ -1,153 +1,152 @@
package cn.celess.blog.service.serviceimpl; package cn.celess.comment.serviceimpl;
import cn.celess.blog.enmu.CommentStatusEnum; import cn.celess.common.constant.CommentStatusEnum;
import cn.celess.blog.enmu.ResponseEnum; import cn.celess.common.constant.ResponseEnum;
import cn.celess.blog.entity.Comment; import cn.celess.common.entity.Comment;
import cn.celess.blog.entity.User; import cn.celess.common.entity.User;
import cn.celess.blog.entity.model.CommentModel; import cn.celess.common.entity.dto.CommentReq;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.CommentModel;
import cn.celess.blog.entity.request.CommentReq; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.exception.MyException; import cn.celess.common.exception.BlogResponseException;
import cn.celess.blog.mapper.ArticleMapper; import cn.celess.common.mapper.ArticleMapper;
import cn.celess.blog.mapper.CommentMapper; import cn.celess.common.mapper.CommentMapper;
import cn.celess.blog.mapper.UserMapper; import cn.celess.common.mapper.UserMapper;
import cn.celess.blog.service.CommentService; import cn.celess.common.service.CommentService;
import cn.celess.blog.util.ModalTrans; import cn.celess.common.util.ModalTrans;
import cn.celess.blog.util.RedisUserUtil; import cn.celess.user.util.RedisUserUtil;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList; import java.util.List;
import java.util.List; import java.util.stream.Collectors;
import java.util.stream.Collectors;
/**
/** * @author : xiaohai
* @author : xiaohai * @date : 2019/03/29 17:05
* @date : 2019/03/29 17:05 */
*/ @Service
@Service public class CommentServiceImpl implements CommentService {
public class CommentServiceImpl implements CommentService { @Autowired
@Autowired CommentMapper commentMapper;
CommentMapper commentMapper; @Autowired
@Autowired UserMapper userMapper;
UserMapper userMapper; @Autowired
@Autowired ArticleMapper articleMapper;
ArticleMapper articleMapper; @Autowired
@Autowired HttpServletRequest request;
HttpServletRequest request; @Autowired
@Autowired RedisUserUtil redisUserUtil;
RedisUserUtil redisUserUtil;
@Override
@Override public CommentModel create(CommentReq reqBody) {
public CommentModel create(CommentReq reqBody) { if (reqBody == null) {
if (reqBody == null) { throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
throw new MyException(ResponseEnum.PARAMETERS_ERROR); }
} User user = redisUserUtil.get();
User user = redisUserUtil.get(); Comment pComment = null;
Comment pComment = null; if (reqBody.getPid() != -1) {
if (reqBody.getPid() != -1) { pComment = commentMapper.findCommentById(reqBody.getPid());
pComment = commentMapper.findCommentById(reqBody.getPid()); }
} //不是一级评论
//不是一级评论 if (reqBody.getPid() != -1 && pComment == null) {
if (reqBody.getPid() != -1 && pComment == null) { //父评论不存在
//父评论不存在 throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR);
throw new MyException(ResponseEnum.PARAMETERS_ERROR); }
} Comment comment = new Comment();
Comment comment = new Comment(); comment.setFromUser(user);
comment.setFromUser(user); User userTo = new User();
User userTo = new User(); userTo.setId(null);
userTo.setId(null); if (reqBody.getToUserId() != -1) {
if (reqBody.getToUserId() != -1) { userTo = userMapper.findById(reqBody.getToUserId());
userTo = userMapper.findById(reqBody.getToUserId()); comment.setToUser(userTo);
comment.setToUser(userTo); }
} comment.setToUser(userTo);
comment.setToUser(userTo); userMapper.findById(reqBody.getToUserId());
userMapper.findById(reqBody.getToUserId()); BeanUtils.copyProperties(reqBody, comment);
BeanUtils.copyProperties(reqBody, comment); commentMapper.insert(comment);
commentMapper.insert(comment); return ModalTrans.comment(commentMapper.findCommentById(comment.getId()));
return ModalTrans.comment(commentMapper.findCommentById(comment.getId())); }
}
@Override
@Override public boolean delete(long id) {
public boolean delete(long id) { Comment b = commentMapper.findCommentById(id);
Comment b = commentMapper.findCommentById(id); if (b == null) {
if (b == null) { throw new BlogResponseException(ResponseEnum.COMMENT_NOT_EXIST);
throw new MyException(ResponseEnum.COMMENT_NOT_EXIST); }
} if (b.getStatus() == CommentStatusEnum.DELETED.getCode()) {
if (b.getStatus() == CommentStatusEnum.DELETED.getCode()) { throw new BlogResponseException(ResponseEnum.DATA_IS_DELETED);
throw new MyException(ResponseEnum.DATA_IS_DELETED); }
} commentMapper.delete(id);
commentMapper.delete(id); return true;
return true; }
}
@Override
@Override public CommentModel update(CommentReq reqBody) {
public CommentModel update(CommentReq reqBody) { if (reqBody.getId() == null) {
if (reqBody.getId() == null) { throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空");
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空"); }
} Comment comment = commentMapper.findCommentById(reqBody.getId());
Comment comment = commentMapper.findCommentById(reqBody.getId()); if (!comment.getContent().equals(reqBody.getContent())) {
if (!comment.getContent().equals(reqBody.getContent())) { commentMapper.updateContent(reqBody.getContent(), reqBody.getId());
commentMapper.updateContent(reqBody.getContent(), reqBody.getId()); comment.setContent(reqBody.getContent());
comment.setContent(reqBody.getContent()); }
} return ModalTrans.comment(comment);
return ModalTrans.comment(comment); }
}
@Override
@Override public PageData<CommentModel> retrievePage(String pagePath, int page, int count) {
public PageData<CommentModel> retrievePage(String pagePath, int page, int count) { PageHelper.startPage(page, count);
PageHelper.startPage(page, count); List<Comment> list = commentMapper.findAllByPagePathAndPidAndNormal(pagePath, -1);
List<Comment> list = commentMapper.findAllByPagePathAndPidAndNormal(pagePath, -1); return pageTrans(list);
return pageTrans(list); }
}
@Override
@Override public List<CommentModel> retrievePageByPid(long pid) {
public List<CommentModel> retrievePageByPid(long pid) { List<Comment> allByPagePath = commentMapper.findAllByPid(pid);
List<Comment> allByPagePath = commentMapper.findAllByPid(pid); return allByPagePath
return allByPagePath .stream()
.stream() .filter(comment -> comment.getStatus() != CommentStatusEnum.DELETED.getCode())
.filter(comment -> comment.getStatus() != CommentStatusEnum.DELETED.getCode()) .map(ModalTrans::comment)
.map(ModalTrans::comment) .collect(Collectors.toList());
.collect(Collectors.toList()); }
}
@Override
@Override public PageData<CommentModel> retrievePageByAuthor(String pagePath, int page, int count) {
public PageData<CommentModel> retrievePageByAuthor(String pagePath, int page, int count) { User user = redisUserUtil.get();
User user = redisUserUtil.get(); PageHelper.startPage(page, count);
PageHelper.startPage(page, count); List<Comment> list = commentMapper.findAllByPagePathAndFromUser(pagePath, user.getId());
List<Comment> list = commentMapper.findAllByPagePathAndFromUser(pagePath, user.getId()); return pageTrans(list);
return pageTrans(list); }
}
@Override
@Override public PageData<CommentModel> retrievePageByPageAndPid(String pagePath, long pid, int page, int count) {
public PageData<CommentModel> retrievePageByPageAndPid(String pagePath, long pid, int page, int count) { PageHelper.startPage(page, count);
PageHelper.startPage(page, count); List<Comment> list = commentMapper.findAllByPagePath(pagePath);
List<Comment> list = commentMapper.findAllByPagePath(pagePath); return pageTrans(list, true);
return pageTrans(list, true); }
}
@Override
@Override public PageData<CommentModel> retrievePageByPage(String pagePath, int page, int count) {
public PageData<CommentModel> retrievePageByPage(String pagePath, int page, int count) { PageHelper.startPage(page, count);
PageHelper.startPage(page, count); List<Comment> list = commentMapper.findAllByPagePath(pagePath);
List<Comment> list = commentMapper.findAllByPagePath(pagePath); return pageTrans(list, true);
return pageTrans(list, true); }
}
private PageData<CommentModel> pageTrans(List<Comment> commentList) {
private PageData<CommentModel> pageTrans(List<Comment> commentList) { return pageTrans(commentList, false);
return pageTrans(commentList, false); }
}
private PageData<CommentModel> pageTrans(List<Comment> commentList, boolean noResponseList) {
private PageData<CommentModel> pageTrans(List<Comment> commentList, boolean noResponseList) { PageInfo<Comment> p = PageInfo.of(commentList);
PageInfo<Comment> p = PageInfo.of(commentList); List<CommentModel> modelList = commentList
List<CommentModel> modelList = commentList .stream()
.stream() .map(ModalTrans::comment)
.map(ModalTrans::comment) .peek(commentModel -> commentModel.setRespComment(this.retrievePageByPid(commentModel.getId())))
.peek(commentModel -> commentModel.setRespComment(this.retrievePageByPid(commentModel.getId()))) .collect(Collectors.toList());
.collect(Collectors.toList()); return new PageData<>(p, modelList);
return new PageData<>(p, modelList); }
} }
}

View File

@@ -0,0 +1,12 @@
${AnsiColor.BRIGHT_GREEN}
_ _ _ ____ _ _____ _
| | | | (_) | _ \ | | / ____| | |
| |__| | _ | |_) | | | ___ __ _ ______ | | ___ _ __ ___ _ __ ___ ___ _ __ | |_
| __ | | | | _ < | | / _ \ / _` | |______| | | / _ \ | '_ ` _ \ | '_ ` _ \ / _ \ | '_ \ | __|
| | | | | | | |_) | | | | (_) | | (_| | | |____ | (_) | | | | | | | | | | | | | | __/ | | | | | |_
|_| |_| |_| |____/ |_| \___/ \__, | \_____| \___/ |_| |_| |_| |_| |_| |_| \___| |_| |_| \__|
__/ |
|___/
${AnsiColor.BRIGHT_RED}
Application Version: ${application.version}${application.formatted-version}
Spring Boot Version: ${spring-boot.version}${spring-boot.formatted-version}

View File

@@ -0,0 +1,11 @@
package cn.celess.comment;
import cn.celess.common.test.BaseTest;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = {CommentApplication.class})
@RunWith(SpringRunner.class)
public abstract class CommentBaseTest extends BaseTest {
}

View File

@@ -1,134 +1,134 @@
package cn.celess.blog.controller; package cn.celess.comment.controller;
import cn.celess.blog.BaseTest; import cn.celess.comment.CommentBaseTest;
import cn.celess.blog.entity.Article; import cn.celess.common.entity.Article;
import cn.celess.blog.entity.Comment; import cn.celess.common.entity.Comment;
import cn.celess.blog.entity.Response; import cn.celess.common.entity.Response;
import cn.celess.blog.entity.User; import cn.celess.common.entity.User;
import cn.celess.blog.entity.model.CommentModel; import cn.celess.common.entity.dto.CommentReq;
import cn.celess.blog.entity.request.CommentReq; import cn.celess.common.entity.vo.CommentModel;
import cn.celess.blog.mapper.ArticleMapper; import cn.celess.common.mapper.ArticleMapper;
import cn.celess.blog.mapper.CommentMapper; import cn.celess.common.mapper.CommentMapper;
import cn.celess.blog.mapper.UserMapper; import cn.celess.common.mapper.UserMapper;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.util.List; import java.util.List;
import static cn.celess.blog.enmu.ResponseEnum.DATA_IS_DELETED; import static cn.celess.common.constant.ResponseEnum.DATA_IS_DELETED;
import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; import static cn.celess.common.constant.ResponseEnum.SUCCESS;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
public class CommentControllerTest extends BaseTest { public class CommentControllerTest extends CommentBaseTest {
@Autowired @Autowired
ArticleMapper articleMapper; ArticleMapper articleMapper;
@Autowired @Autowired
UserMapper userMapper; UserMapper userMapper;
@Autowired @Autowired
CommentMapper commentMapper; CommentMapper commentMapper;
private static final TypeReference<?> COMMENT_MODEL_TYPE = new TypeReference<Response<CommentModel>>() { private static final TypeReference<?> COMMENT_MODEL_TYPE = new TypeReference<Response<CommentModel>>() {
}; };
@Test @Test
public void addOne() throws Exception { public void addOne() throws Exception {
Article article = articleMapper.getLastestArticle(); Article article = articleMapper.getLastestArticle();
CommentReq commentReq = new CommentReq(); CommentReq commentReq = new CommentReq();
commentReq.setPagePath("/article/" + article.getId()); commentReq.setPagePath("/article/" + article.getId());
commentReq.setContent(randomStr()); commentReq.setContent(randomStr());
List<User> all = userMapper.findAll(); List<User> all = userMapper.findAll();
commentReq.setPid(1L); commentReq.setPid(1L);
commentReq.setToUserId(2l); commentReq.setToUserId(2l);
getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> {
Response<CommentModel> response = getResponse(result, COMMENT_MODEL_TYPE); Response<CommentModel> response = getResponse(result, COMMENT_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
CommentModel model = response.getResult(); CommentModel model = response.getResult();
assertNotEquals(0, model.getId()); assertNotEquals(0, model.getId());
assertEquals(commentReq.getPid(), model.getPid().longValue()); assertEquals(commentReq.getPid(), model.getPid().longValue());
assertEquals(1, model.getPid().longValue()); assertEquals(1, model.getPid().longValue());
assertEquals(commentReq.getContent(), model.getContent()); assertEquals(commentReq.getContent(), model.getContent());
assertNotNull(model.getDate()); assertNotNull(model.getDate());
assertNotNull(model.getFromUser()); assertNotNull(model.getFromUser());
assertNotNull(model.getToUser()); assertNotNull(model.getToUser());
}); });
commentReq.setPagePath("/article/" + article.getId()); commentReq.setPagePath("/article/" + article.getId());
commentReq.setContent(randomStr()); commentReq.setContent(randomStr());
commentReq.setPid(-1L); commentReq.setPid(-1L);
commentReq.setToUserId(2); commentReq.setToUserId(2);
getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> {
Response<CommentModel> response = getResponse(result, COMMENT_MODEL_TYPE); Response<CommentModel> response = getResponse(result, COMMENT_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
CommentModel model = response.getResult(); CommentModel model = response.getResult();
// 响应数据的完整性 // 响应数据的完整性
assertNotEquals(0, model.getId()); assertNotEquals(0, model.getId());
assertEquals(commentReq.getPid(), model.getPid().longValue()); assertEquals(commentReq.getPid(), model.getPid().longValue());
assertEquals(-1, model.getPid().longValue()); assertEquals(-1, model.getPid().longValue());
assertEquals(commentReq.getContent(), model.getContent()); assertEquals(commentReq.getContent(), model.getContent());
assertEquals(commentReq.getPagePath(), "/article/" + article.getId()); assertEquals(commentReq.getPagePath(), "/article/" + article.getId());
assertNotNull(model.getDate()); assertNotNull(model.getDate());
assertNotNull(model.getFromUser()); assertNotNull(model.getFromUser());
assertNotNull(model.getToUser()); assertNotNull(model.getToUser());
}); });
// 测试二级回复 // 测试二级回复
Comment latestComment = commentMapper.getLastestComment(); Comment latestComment = commentMapper.getLastestComment();
commentReq.setPagePath("/article/" + article.getId()); commentReq.setPagePath("/article/" + article.getId());
commentReq.setContent(randomStr()); commentReq.setContent(randomStr());
commentReq.setPid(latestComment.getId()); commentReq.setPid(latestComment.getId());
getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> { getMockData(post("/user/comment/create"), userLogin(), commentReq).andDo(result -> {
Response<CommentModel> response = getResponse(result, COMMENT_MODEL_TYPE); Response<CommentModel> response = getResponse(result, COMMENT_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
CommentModel model = response.getResult(); CommentModel model = response.getResult();
// 重新获取父评论信息 // 重新获取父评论信息
Comment pCommon = commentMapper.findCommentById(latestComment.getId()); Comment pCommon = commentMapper.findCommentById(latestComment.getId());
assertEquals(pCommon.getId(), model.getPid()); assertEquals(pCommon.getId(), model.getPid());
}); });
} }
@Test @Test
public void deleteTest() throws Exception { public void deleteTest() throws Exception {
// 准备数据 // 准备数据
User from = userMapper.findByEmail("zh56462271@qq.com"); User from = userMapper.findByEmail("zh56462271@qq.com");
assertNotNull(from); assertNotNull(from);
User to = userMapper.findByEmail("a@celess.cn"); User to = userMapper.findByEmail("a@celess.cn");
assertNotNull(to); assertNotNull(to);
Comment comment = new Comment(); Comment comment = new Comment();
comment.setContent(randomStr(8)); comment.setContent(randomStr(8));
comment.setFromUser(from); comment.setFromUser(from);
comment.setToUser(to); comment.setToUser(to);
comment.setPagePath("/tags"); comment.setPagePath("/tags");
comment.setPid(-1L); comment.setPid(-1L);
commentMapper.insert(comment); commentMapper.insert(comment);
comment = commentMapper.findCommentById(comment.getId()); comment = commentMapper.findCommentById(comment.getId());
// 接口测试 // 接口测试
long id = comment.getId(); long id = comment.getId();
assertNotEquals(0, id); assertNotEquals(0, id);
getMockData(delete("/user/comment/del?id=" + id), userLogin()).andDo(result -> { getMockData(delete("/user/comment/del?id=" + id), userLogin()).andDo(result -> {
Response<Boolean> response = getResponse(result, BOOLEAN_TYPE); Response<Boolean> response = getResponse(result, BOOLEAN_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
assertTrue(response.getResult()); assertTrue(response.getResult());
}); });
getMockData(delete("/user/comment/del?id=" + id), userLogin()) getMockData(delete("/user/comment/del?id=" + id), userLogin())
.andDo(result -> assertEquals(DATA_IS_DELETED.getCode(), getResponse(result, COMMENT_MODEL_TYPE).getCode())); .andDo(result -> assertEquals(DATA_IS_DELETED.getCode(), getResponse(result, COMMENT_MODEL_TYPE).getCode()));
} }
@Test @Test
public void update() throws Exception { public void update() throws Exception {
Comment comment = commentMapper.getLastestComment(); Comment comment = commentMapper.getLastestComment();
CommentReq commentReq = new CommentReq(); CommentReq commentReq = new CommentReq();
commentReq.setId(comment.getId()); commentReq.setId(comment.getId());
commentReq.setContent(randomStr()); commentReq.setContent(randomStr());
// 不合法数据 setResponseId // 不合法数据 setResponseId
getMockData(put("/user/comment/update"), userLogin(), commentReq).andDo(result -> { getMockData(put("/user/comment/update"), userLogin(), commentReq).andDo(result -> {
Response<CommentModel> response = getResponse(result, COMMENT_MODEL_TYPE); Response<CommentModel> response = getResponse(result, COMMENT_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
CommentModel c = response.getResult(); CommentModel c = response.getResult();
assertEquals(commentReq.getContent(), c.getContent()); assertEquals(commentReq.getContent(), c.getContent());
}); });
} }
} }

110
blog-common/pom.xml Normal file
View File

@@ -0,0 +1,110 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>blog</artifactId>
<groupId>cn.celess</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>blog-common</artifactId>
<dependencies>
<dependency>
<groupId>cn.celess</groupId>
<artifactId>blog-resource</artifactId>
<version>${blog-resource.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.github.kstyrc</groupId>
<artifactId>embedded-redis</artifactId>
<version>0.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
<exclusions>
<exclusion>
<groupId>com.sun</groupId>
<artifactId>jconsole</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- pageHelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
<!--Email-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- TODO: remove this -->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.45.0</version>
</dependency>
<!-- protostuff序列化依赖 -->
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,26 @@
package cn.celess.common;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.SpringVersion;
@SpringBootApplication(
scanBasePackageClasses = {
CommonApplication.class
}
)
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = "cn.celess.common.test.BaseRedisTest")})
@MapperScan("cn.celess.common.mapper")
public class CommonApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(CommonApplication.class)
.main(SpringVersion.class)
.bannerMode(Banner.Mode.CONSOLE)
.run(args);
}
}

View File

@@ -0,0 +1,56 @@
package cn.celess.common.config;
import cn.celess.common.util.EnvironmentUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.logging.DeferredLog;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.regex.Matcher;
@Component
public class CommonEnvPostProcessor implements EnvironmentPostProcessor, ApplicationListener<ApplicationEvent>, Ordered {
public static final DeferredLog log = new DeferredLog();
private static final String CONFIG_PATH = "/HBlog/config/blog.properties";
private static final String SOURCE_NAME = "localize";
@Override
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
EnvironmentUtil.setEnvironment(configurableEnvironment);
log.info("加载本地配置文件--");
//获取环境变量
String homeEnv = EnvironmentUtil.getEnv("BLOG_HOME", EnvironmentUtil.getEnv("USERPROFILE"));
String configPath = (homeEnv + CONFIG_PATH).replaceAll("[\\|/]+", Matcher.quoteReplacement(File.separator));
try (InputStream input = new FileInputStream(configPath)) {
Properties properties = new Properties();
properties.load(input);
PropertiesPropertySource propertySource = new PropertiesPropertySource(SOURCE_NAME, properties);
configurableEnvironment.getPropertySources().addLast(propertySource);
log.info("成功加载本地配置文件:)");
} catch (Exception e) {
log.info("加载本地[" + configPath + "]的配置文件失败:(");
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
log.replayTo(CommonEnvPostProcessor.class);
}
@Override
public int getOrder() {
return 0;
}
}

View File

@@ -1,4 +1,4 @@
package cn.celess.blog.enmu; package cn.celess.common.constant;
import lombok.Getter; import lombok.Getter;

View File

@@ -1,96 +1,96 @@
package cn.celess.blog.enmu; package cn.celess.common.constant;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 15:37 * @date : 2019/03/28 15:37
*/ */
public enum ResponseEnum { public enum ResponseEnum {
// Response enum // Response enum
SUCCESS(0, "成功"), SUCCESS(0, "成功"),
FAILURE(-1, "失败"), FAILURE(-1, "失败"),
ERROR(-2, "错误"), ERROR(-2, "错误"),
DATA_IS_DELETED(1000, "数据已被删除"), DATA_IS_DELETED(1000, "数据已被删除"),
//文章类 //文章类
ARTICLE_NOT_EXIST(2010, "文章不存在"), ARTICLE_NOT_EXIST(2010, "文章不存在"),
ARTICLE_HAS_EXIST(2020, "文章已存在"), ARTICLE_HAS_EXIST(2020, "文章已存在"),
ARTICLE_NOT_PUBLIC(2030, "文章暂未公开"), ARTICLE_NOT_PUBLIC(2030, "文章暂未公开"),
ARTICLE_NOT_BELONG_YOU(2040, "无权限操作别人的文章"), ARTICLE_NOT_BELONG_YOU(2040, "无权限操作别人的文章"),
//用户类 //用户类
HAVE_NOT_LOG_IN(3010, "还未登录"), HAVE_NOT_LOG_IN(3010, "还未登录"),
PERMISSION_ERROR(3020, "没有此权限"), PERMISSION_ERROR(3020, "没有此权限"),
USER_NOT_EXIST(3030, "用户不存在"), USER_NOT_EXIST(3030, "用户不存在"),
USERNAME_HAS_EXIST(3040, "用户名已存在"), USERNAME_HAS_EXIST(3040, "用户名已存在"),
USERNAME_TOO_SHORT(3050, "用户名太短"), USERNAME_TOO_SHORT(3050, "用户名太短"),
PASSWORD_TOO_SHORT_OR_LONG(3060, "密码长度过长或者过短"), PASSWORD_TOO_SHORT_OR_LONG(3060, "密码长度过长或者过短"),
LOGIN_FAILURE(3100, "登录失败,用户名/密码不正确"), LOGIN_FAILURE(3100, "登录失败,用户名/密码不正确"),
USEREMAIL_NULL(3310, "未设置邮箱"), USEREMAIL_NULL(3310, "未设置邮箱"),
USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"), USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"),
LOGIN_LATER(3500, "错误次数已达5次请稍后再试"), LOGIN_LATER(3500, "错误次数已达5次请稍后再试"),
PWD_SAME(3601, "新密码与原密码相同"), PWD_SAME(3601, "新密码与原密码相同"),
PWD_NOT_SAME(3602, "新密码与原密码不相同"), PWD_NOT_SAME(3602, "新密码与原密码不相同"),
LOGIN_EXPIRED(3700, "登陆过期"), LOGIN_EXPIRED(3700, "登陆过期"),
LOGOUT(3710, "账户已注销"), LOGOUT(3710, "账户已注销"),
CAN_NOT_USE(3711, "账户不可用"), CAN_NOT_USE(3711, "账户不可用"),
PWD_WRONG(3800, "密码不正确"), PWD_WRONG(3800, "密码不正确"),
JWT_EXPIRED(3810, "Token过期"), JWT_EXPIRED(3810, "Token过期"),
JWT_MALFORMED(3820, "Token格式不对"), JWT_MALFORMED(3820, "Token格式不对"),
JWT_SIGNATURE(3830, "Token签名错误"), JWT_SIGNATURE(3830, "Token签名错误"),
JWT_NOT_SUPPORT(3840, "不支持的Token"), JWT_NOT_SUPPORT(3840, "不支持的Token"),
//标签 //标签
TAG_NOT_EXIST(4010, "标签不存在"), TAG_NOT_EXIST(4010, "标签不存在"),
TAG_HAS_EXIST(4020, "标签已存在"), TAG_HAS_EXIST(4020, "标签已存在"),
//分类 //分类
CATEGORY_NOT_EXIST(5010, "分类不存在"), CATEGORY_NOT_EXIST(5010, "分类不存在"),
CATEGORY_HAS_EXIST(5020, "分类已存在"), CATEGORY_HAS_EXIST(5020, "分类已存在"),
//评论/留言 //评论/留言
COMMENT_NOT_EXIST(6010, "评论/留言不存在"), COMMENT_NOT_EXIST(6010, "评论/留言不存在"),
COMMENT_HAS_EXIST(6020, "评论/留言已存在,请不要重复提交"), COMMENT_HAS_EXIST(6020, "评论/留言已存在,请不要重复提交"),
//webUdpateInfo amd PartnerSite //webUdpateInfo amd PartnerSite
DATA_NOT_EXIST(7010, "数据不存在"), DATA_NOT_EXIST(7010, "数据不存在"),
DATA_HAS_EXIST(7020, "数据已存在"), DATA_HAS_EXIST(7020, "数据已存在"),
//其他 //其他
APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"), APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"),
DATA_EXPIRED(7300, "数据过期"), DATA_EXPIRED(7300, "数据过期"),
CANNOT_GET_DATA(7400, "暂无法获取到数据"), CANNOT_GET_DATA(7400, "暂无法获取到数据"),
NO_FILE(7500, "未选择文件,请重新选择"), NO_FILE(7500, "未选择文件,请重新选择"),
//提交更新之前没有获取数据/, //提交更新之前没有获取数据/,
DID_NOT_GET_THE_DATA(8020, "非法访问"), DID_NOT_GET_THE_DATA(8020, "非法访问"),
IMG_CODE_TIMEOUT(8100, "验证码已失效"), IMG_CODE_TIMEOUT(8100, "验证码已失效"),
IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"), IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"),
VERIFY_ERROR(8300, "验证失败"), VERIFY_ERROR(8300, "验证失败"),
PARAMETERS_ERROR(8500, "参数错误"), PARAMETERS_ERROR(8500, "参数错误"),
PARAMETERS_URL_ERROR(8510, "链接格式错误"), PARAMETERS_URL_ERROR(8510, "链接格式错误"),
PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"), PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"),
PARAMETERS_PHONE_ERROR(8530, "手机格式错误"), PARAMETERS_PHONE_ERROR(8530, "手机格式错误"),
PARAMETERS_QQ_ERROR(8540, "QQ格式错误"), PARAMETERS_QQ_ERROR(8540, "QQ格式错误"),
PARAMETERS_PWD_ERROR(8550, "密码格式错误"), PARAMETERS_PWD_ERROR(8550, "密码格式错误"),
VERIFY_OUT(8400, "已经验证过了"); VERIFY_OUT(8400, "已经验证过了");
private final int code; private final int code;
private final String msg; private final String msg;
ResponseEnum(int code, String msg) { ResponseEnum(int code, String msg) {
this.code = code; this.code = code;
this.msg = msg; this.msg = msg;
} }
public int getCode() { public int getCode() {
return code; return code;
} }
public String getMsg() { public String getMsg() {
return msg; return msg;
} }
} }

View File

@@ -1,4 +1,4 @@
package cn.celess.blog.enmu; package cn.celess.common.constant;
import lombok.Getter; import lombok.Getter;

View File

@@ -1,4 +1,4 @@
package cn.celess.blog.enmu; package cn.celess.common.constant;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.annotation.JsonValue;

View File

@@ -1,63 +1,64 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.io.Serializable;
import java.util.List; import java.util.Date;
import java.util.List;
/**
* @author : xiaohai /**
* @date : 2019/03/28 14:51 * @author : xiaohai
*/ * @date : 2019/03/28 14:51
@Data */
public class Article { @Data
private Long id; public class Article implements Serializable {
private Long id;
/**
* 标题 /**
*/ * 标题
private String title; */
private String title;
/**
* 摘要 /**
*/ * 摘要
private String summary; */
private String summary;
/**
* Markdown正文 /**
*/ * Markdown正文
private String mdContent; */
private String mdContent;
/**
* 文章类型 true(1)为原创 false(0)为转载 /**
*/ * 文章类型 true(1)为原创 false(0)为转载
private Boolean type; */
private Boolean type;
/**
* 若为转载 则为转载文章的url /**
*/ * 若为转载 则为转载文章的url
private String url = null; */
private String url = null;
private Date publishDate;
private Date publishDate;
private Date updateDate = null;
private Date updateDate = null;
private Long readingNumber;
private Long readingNumber;
/**
* 文章的状态 true公开 false:不公开 /**
*/ * 文章的状态 true公开 false:不公开
private Boolean open; */
private Boolean open;
private Category category;
private Category category;
private List<Tag> tags;
private List<Tag> tags;
private Integer likeCount;
private Integer likeCount;
private Integer dislikeCount;
private Integer dislikeCount;
private User user;
private User user;
private boolean deleted = false;
} private boolean deleted = false;
}

View File

@@ -1,9 +1,11 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.io.Serializable;
/** /**
* @Author: 小海 * @Author: 小海
* @Date: 2020-05-24 14:52 * @Date: 2020-05-24 14:52
@@ -12,7 +14,7 @@ import lombok.NoArgsConstructor;
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class ArticleTag { public class ArticleTag implements Serializable {
private Long id; private Long id;
private Article article; private Article article;

View File

@@ -1,13 +1,15 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.io.Serializable;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 22:18 * @date : 2019/03/28 22:18
*/ */
@NoArgsConstructor @NoArgsConstructor
public class Category extends TagCategory { public class Category extends TagCategory implements Serializable {
public Category(String name) { public Category(String name) {
super.setName(name); super.setName(name);
} }

View File

@@ -1,34 +1,35 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.io.Serializable;
import java.util.Date;
/**
* @author : xiaohai /**
* @date : 2019/03/29 16:47 * @author : xiaohai
*/ * @date : 2019/03/29 16:47
*/
@Data
public class Comment { @Data
public class Comment implements Serializable {
private Long id;
private Long id;
private int status;
private int status;
private String pagePath;
private String pagePath;
private String content;
private String content;
private Date date;
private Date date;
private User fromUser;
private User fromUser;
private User toUser;
/** private User toUser;
* 评论的父ID /**
*/ * 评论的父ID
private Long pid; */
private Long pid;
// private boolean delete;
} // private boolean delete;
}

View File

@@ -1,40 +1,42 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.Data; import lombok.Data;
/** import java.io.Serializable;
* 友链
* /**
* @author : xiaohai * 友链
* @date : 2019/05/12 11:33 *
*/ * @author : xiaohai
@Data * @date : 2019/05/12 11:33
public class PartnerSite { */
@Data
private Long id; public class PartnerSite implements Serializable {
private String name; private Long id;
private String url; private String name;
private Boolean open; private String url;
private String iconPath; private Boolean open;
private String desc; private String iconPath;
private Boolean delete = false; private String desc;
private String email; private Boolean delete = false;
private Boolean notification = true; private String email;
public PartnerSite() { private Boolean notification = true;
}
public PartnerSite() {
public PartnerSite(String name, String url, Boolean open) { }
this.name = name;
this.url = url; public PartnerSite(String name, String url, Boolean open) {
this.open = open; this.name = name;
} this.url = url;
} this.open = open;
}
}

View File

@@ -1,65 +1,65 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import cn.celess.blog.enmu.ResponseEnum; import cn.celess.common.constant.ResponseEnum;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data; import lombok.Data;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import java.io.Serializable; import java.io.Serializable;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 15:24 * @date : 2019/03/28 15:24
*/ */
@Data @Data
public class Response<T> implements Serializable { public class Response<T> implements Serializable {
private int code; private int code;
private String msg; private String msg;
private T result; private T result;
public Response() { public Response() {
} }
public Response(int code, String msg, T result) { public Response(int code, String msg, T result) {
this.code = code; this.code = code;
this.msg = msg; this.msg = msg;
this.result = result; this.result = result;
} }
/** /**
* 成功相应 * 成功相应
* *
* @param result 结果 * @param result 结果
* @return Response * @return Response
*/ */
public static <T> Response<T> success(T result) { public static <T> Response<T> success(T result) {
return new Response<T>(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result); return new Response<T>(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result);
} }
/** /**
* 失败的响应 * 失败的响应
* *
* @param result 结果 * @param result 结果
* @return Response * @return Response
*/ */
public static Response<String> failure(String result) { public static Response<String> failure(String result) {
return new Response<String>(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result); return new Response<String>(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result);
} }
/** /**
* 其他的响应 * 其他的响应
* *
* @param r 枚举常量 * @param r 枚举常量
* @param result 结果 * @param result 结果
* @return Response * @return Response
*/ */
public static <T> Response<T> response(ResponseEnum r, T result) { public static <T> Response<T> response(ResponseEnum r, T result) {
return new Response<T>(r.getCode(), r.getMsg(), result); return new Response<T>(r.getCode(), r.getMsg(), result);
} }
@SneakyThrows @SneakyThrows
@Override @Override
public String toString() { public String toString() {
return new ObjectMapper().writeValueAsString(this); return new ObjectMapper().writeValueAsString(this);
} }
} }

View File

@@ -1,13 +1,15 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.io.Serializable;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 22:19 * @date : 2019/03/28 22:19
*/ */
@NoArgsConstructor @NoArgsConstructor
public class Tag extends TagCategory { public class Tag extends TagCategory implements Serializable {
public Tag(String name) { public Tag(String name) {
super.setName(name); super.setName(name);

View File

@@ -1,14 +1,16 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
/** /**
* @Author: 小海 * @Author: 小海
* @Date: 2020-05-24 14:03 * @Date: 2020-05-24 14:03
* @Desc: * @Desc:
*/ */
@Data @Data
public class TagCategory { public class TagCategory implements Serializable {
private Long id; private Long id;
private String name; private String name;

View File

@@ -1,53 +1,54 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.util.Date; import java.io.Serializable;
import java.util.Date;
/**
* @author : xiaohai /**
* @date : 2019/03/28 14:52 * @author : xiaohai
*/ * @date : 2019/03/28 14:52
@Data */
@NoArgsConstructor @Data
public class User { @NoArgsConstructor
private Long id; public class User implements Serializable {
private Long id;
/**
* 邮箱 /**
*/ * 邮箱
private String email; */
private String email;
/**
* 密码 /**
*/ * 密码
@JsonIgnore */
private String pwd; @JsonIgnore
private String pwd;
/**
* 昵称 /**
*/ * 昵称
private String displayName; */
private String displayName;
private Boolean emailStatus = false;
private Boolean emailStatus = false;
/**
* 头像地址 /**
*/ * 头像地址
private String avatarImgUrl; */
private String avatarImgUrl;
private String desc;
private String desc;
private Date recentlyLandedDate;
private Date recentlyLandedDate;
private String role = "user";
private String role = "user";
private int status;
private int status;
public User(String email, String pwd) {
this.email = email; public User(String email, String pwd) {
this.pwd = pwd; this.email = email;
} this.pwd = pwd;
} }
}

View File

@@ -1,28 +1,29 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.io.Serializable;
import java.util.Date;
/**
* @author : xiaohai /**
* @date : 2019/04/02 22:14 * @author : xiaohai
*/ * @date : 2019/04/02 22:14
@Data */
public class Visitor { @Data
public class Visitor implements Serializable {
private long id;
private String ip; private long id;
private Date date; private String ip;
private String ua; private Date date;
private boolean delete; private String ua;
private boolean delete;
public Visitor(String ip, Date date, String ua) {
this.ip = ip; public Visitor(String ip, Date date, String ua) {
this.date = date; this.ip = ip;
this.ua = ua; this.date = date;
} this.ua = ua;
}
public Visitor() {
} public Visitor() {
} }
}

View File

@@ -1,28 +1,29 @@
package cn.celess.blog.entity; package cn.celess.common.entity;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.io.Serializable;
import java.util.Date;
/**
* @author : xiaohai /**
* @date : 2019/05/12 11:29 * @author : xiaohai
*/ * @date : 2019/05/12 11:29
@Data */
public class WebUpdate { @Data
public class WebUpdate implements Serializable {
private long id;
private long id;
private String updateInfo;
private String updateInfo;
private Date updateTime;
private Date updateTime;
private boolean delete;
private boolean delete;
public WebUpdate() {
} public WebUpdate() {
}
public WebUpdate(String updateInfo) {
this.updateInfo = updateInfo; public WebUpdate(String updateInfo) {
} this.updateInfo = updateInfo;
} }
}

View File

@@ -1,19 +1,21 @@
package cn.celess.blog.entity.request; package cn.celess.common.entity.dto;
import lombok.Data; import lombok.Data;
/** import java.io.Serializable;
* @author : xiaohai
* @date : 2019/06/01 22:46 /**
*/ * @author : xiaohai
@Data * @date : 2019/06/01 22:46
public class ArticleReq { */
private Long id; @Data
private String title; public class ArticleReq implements Serializable {
private String mdContent; private Long id;
private String[] tags; private String title;
private Boolean type; private String mdContent;
private String url; private String[] tags;
private String category; private Boolean type;
private Boolean open = true; private String url;
} private String category;
private Boolean open = true;
}

View File

@@ -1,16 +1,18 @@
package cn.celess.blog.entity.request; package cn.celess.common.entity.dto;
import lombok.Data; import lombok.Data;
/** import java.io.Serializable;
* @author : xiaohai
* @date : 2019/06/02 10:35 /**
*/ * @author : xiaohai
@Data * @date : 2019/06/02 10:35
public class CommentReq { */
private Long id; @Data
private String content; public class CommentReq implements Serializable {
private long pid = -1; private Long id;
private String pagePath; private String content;
private long toUserId = -1; private long pid = -1;
} private String pagePath;
private long toUserId = -1;
}

View File

@@ -1,13 +1,15 @@
package cn.celess.blog.entity.request; package cn.celess.common.entity.dto;
import lombok.Data; import lombok.Data;
import java.io.Serializable;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2020/07/31 20:50 * @date : 2020/07/31 20:50
*/ */
@Data @Data
public class LinkApplyReq { public class LinkApplyReq implements Serializable {
private String name; private String name;
private String email; private String email;
private String url; private String url;

View File

@@ -1,17 +1,19 @@
package cn.celess.blog.entity.request; package cn.celess.common.entity.dto;
import lombok.Data; import lombok.Data;
/** import java.io.Serializable;
* @author : xiaohai
* @date : 2019/06/02 11:40 /**
*/ * @author : xiaohai
@Data * @date : 2019/06/02 11:40
public class LinkReq { */
private long id; @Data
private String name; public class LinkReq implements Serializable {
private String url; private long id;
private String iconPath; private String name;
private String desc; private String url;
private boolean open; private String iconPath;
} private String desc;
private boolean open;
}

View File

@@ -1,23 +1,25 @@
package cn.celess.blog.entity.request; package cn.celess.common.entity.dto;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
/** import java.io.Serializable;
* @author : xiaohai
* @date : 2019/06/01 22:47 /**
*/ * @author : xiaohai
@Data * @date : 2019/06/01 22:47
@NoArgsConstructor */
@AllArgsConstructor @Data
public class LoginReq { @NoArgsConstructor
private String email; @AllArgsConstructor
private String password; public class LoginReq implements Serializable {
/** private String email;
* isRememberMe默认为false private String password;
*/ /**
private Boolean isRememberMe = false; * isRememberMe默认为false
*/
} private Boolean isRememberMe = false;
}

View File

@@ -1,26 +1,28 @@
package cn.celess.blog.entity.request; package cn.celess.common.entity.dto;
import lombok.Data; import lombok.Data;
/** import java.io.Serializable;
* @Author: 小海
* @Date 2019/09/06 13:33 /**
* @Description * @Author: 小海
*/ * @Date 2019/09/06 13:33
@Data * @Description
public class UserReq { */
private Long id; @Data
public class UserReq implements Serializable {
private String email; private Long id;
private String pwd; private String email;
private String displayName; private String pwd;
private Boolean emailStatus; private String displayName;
private String desc; private Boolean emailStatus;
private String role; private String desc;
} private String role;
}

View File

@@ -1,87 +1,88 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import cn.celess.blog.entity.Tag; import cn.celess.common.entity.Tag;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.util.List; import java.io.Serializable;
import java.util.List;
/**
* @author : xiaohai /**
* @date : 2019/04/23 12:02 * @author : xiaohai
*/ * @date : 2019/04/23 12:02
@Getter */
@Setter @Getter
public class ArticleModel { @Setter
private Long id; public class ArticleModel implements Serializable {
private Long id;
/**
* 标题 /**
*/ * 标题
private String title; */
private String title;
/**
* 摘要 /**
*/ * 摘要
private String summary; */
private String summary;
/**
* Markdown正文 /**
*/ * Markdown正文
private String mdContent; */
private String mdContent;
/**
* 文章类型 true(1)为原创 false(0)为转载 /**
*/ * 文章类型 true(1)为原创 false(0)为转载
private Boolean original; */
private Boolean original;
/**
* 若为转载 则为转载文章的url /**
*/ * 若为转载 则为转载文章的url
private String url; */
private String url;
/**
* 发布时间 /**
*/ * 发布时间
private String publishDateFormat; */
private String publishDateFormat;
/**
* 更新时间 /**
*/ * 更新时间
private String updateDateFormat; */
private String updateDateFormat;
/**
* 分类 /**
*/ * 分类
private String category; */
private String category;
/**
* 标签 /**
*/ * 标签
private List<Tag> tags; */
private List<Tag> tags;
/**
* 作者 /**
*/ * 作者
private UserModel author; */
private UserModel author;
private ArticleModel preArticle;
private ArticleModel preArticle;
private ArticleModel nextArticle;
private ArticleModel nextArticle;
/**
* 阅读数 /**
*/ * 阅读数
private Long readingNumber; */
private Long readingNumber;
private Integer likeCount;
private Integer likeCount;
private Integer dislikeCount;
private Integer dislikeCount;
/**
* 文章的状态 true公开 false:不公开 /**
*/ * 文章的状态 true公开 false:不公开
private Boolean open; */
private Boolean open;
private boolean deleted;
} private boolean deleted;
}

View File

@@ -1,9 +1,10 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List; import java.util.List;
/** /**
@@ -14,7 +15,7 @@ import java.util.List;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class CategoryModel { public class CategoryModel implements Serializable {
private Long id; private Long id;
private String name; private String name;

View File

@@ -1,44 +1,45 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import java.util.List; import java.io.Serializable;
import java.util.List;
/**
* @author : xiaohai /**
* @date : 2019/04/22 21:50 * @author : xiaohai
*/ * @date : 2019/04/22 21:50
@Setter */
@Getter @Setter
public class CommentModel { @Getter
private long id; public class CommentModel implements Serializable {
private long id;
private UserModel fromUser;
private UserModel fromUser;
private UserModel toUser;
private UserModel toUser;
/**
* 内容 /**
*/ * 内容
private String content; */
private String content;
/**
* 文章标题 /**
*/ * 文章标题
private String pagePath; */
private String pagePath;
/**
* 发布日期 /**
*/ * 发布日期
private String date; */
private String date;
/**
* 评论的父ID /**
*/ * 评论的父ID
private Long pid; */
private Long pid;
private List<CommentModel> respComment;
private List<CommentModel> respComment;
private int status;
} private int status;
}

View File

@@ -1,10 +1,11 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List; import java.util.List;
/** /**
@@ -15,7 +16,7 @@ import java.util.List;
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class PageData<T> { public class PageData<T> implements Serializable {
private List<T> list; private List<T> list;

View File

@@ -0,0 +1,15 @@
package cn.celess.common.entity.vo;
import java.io.Serializable;
/**
* @author : xiaohai
* @date : 2019/04/21 22:43
*/
public class QiniuResponse implements Serializable {
public String key;
public String hash;
public String bucket;
public long fsize;
}

View File

@@ -1,9 +1,10 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List; import java.util.List;
/** /**
@@ -14,7 +15,7 @@ import java.util.List;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class TagModel { public class TagModel implements Serializable {
private Long id; private Long id;
private String name; private String name;

View File

@@ -1,43 +1,45 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import cn.celess.blog.enmu.UserAccountStatusEnum; import cn.celess.common.constant.UserAccountStatusEnum;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
/** import java.io.Serializable;
* @author : xiaohai
* @date : 2019/04/22 23:13 /**
*/ * @author : xiaohai
@Getter * @date : 2019/04/22 23:13
@Setter */
public class UserModel { @Getter
@Setter
private Long id; public class UserModel implements Serializable {
/** private Long id;
* 邮箱
*/ /**
private String email; * 邮箱
*/
/** private String email;
* 昵称
*/ /**
private String displayName; * 昵称
*/
private Boolean emailStatus = false; private String displayName;
/** private Boolean emailStatus = false;
* 头像地址
*/ /**
private String avatarImgUrl; * 头像地址
*/
private String desc; private String avatarImgUrl;
private String recentlyLandedDate; private String desc;
private String role = "user"; private String recentlyLandedDate;
private String token; private String role = "user";
private UserAccountStatusEnum status; private String token;
}
private UserAccountStatusEnum status;
}

View File

@@ -1,24 +1,26 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import lombok.Data; import lombok.Data;
/** import java.io.Serializable;
* @author : xiaohai
* @date : 2019/05/05 16:05 /**
*/ * @author : xiaohai
@Data * @date : 2019/05/05 16:05
public class VisitorModel { */
private long id; @Data
public class VisitorModel implements Serializable {
private String ip; private long id;
private String date; private String ip;
private String browserName; private String date;
private String browserVersion; private String browserName;
private String OSName; private String browserVersion;
private String location; private String OSName;
}
private String location;
}

View File

@@ -1,26 +1,28 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
/** import java.io.Serializable;
* @author : xiaohai
* @date : 2019/05/12 11:32 /**
*/ * @author : xiaohai
@Data * @date : 2019/05/12 11:32
@NoArgsConstructor */
public class WebUpdateModel { @Data
private long id; @NoArgsConstructor
public class WebUpdateModel implements Serializable {
private String info; private long id;
private String time; private String info;
public WebUpdateModel(long id, String info, String time) { private String time;
this.id = id;
this.info = info; public WebUpdateModel(long id, String info, String time) {
this.time = time; this.id = id;
} this.info = info;
this.time = time;
private boolean deleted; }
}
private boolean deleted;
}

View File

@@ -1,111 +1,98 @@
package cn.celess.blog.exception; package cn.celess.common.exception;
import cn.celess.blog.enmu.ResponseEnum; import cn.celess.common.constant.ResponseEnum;
import cn.celess.blog.entity.Response; import cn.celess.common.entity.Response;
import cn.celess.blog.service.MailService; import cn.celess.common.service.MailService;
import cn.celess.blog.util.DateFormatUtil; import cn.celess.common.util.DateFormatUtil;
import org.slf4j.Logger; import cn.celess.common.util.EnvironmentUtil;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.SimpleMailMessage;
import org.springframework.validation.BindException; import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult; import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequest; /**
import javax.validation.ConstraintViolation; * @author : xiaohai
import javax.validation.ConstraintViolationException; * @date : 2019/03/28 17:02
import javax.validation.ValidationException; */
import java.util.Set;
@ControllerAdvice
/** public class BlogExceptionHandler {
* @author : xiaohai public static final Logger logger = LoggerFactory.getLogger(BlogExceptionHandler.class);
* @date : 2019/03/28 17:02 @Autowired
*/ MailService mailService;
@Autowired
@ControllerAdvice HttpServletRequest request;
public class ExceptionHandle {
public static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class)
@Autowired @ResponseBody
MailService mailService; public Response handle(Exception e) {
@Autowired //自定义错误
HttpServletRequest request; if (e instanceof BlogResponseException) {
@Value("${spring.profiles.active}") BlogResponseException exception = (BlogResponseException) e;
private String activeModel; logger.debug("返回了自定义的exception,[code={},msg={},result={}]", exception.getCode(), e.getMessage(), exception.getResult());
return new Response(exception.getCode(), e.getMessage(), exception.getResult());
@ExceptionHandler(value = Exception.class) }
@ResponseBody //请求路径不支持该方法
public Response handle(Exception e) { if (e instanceof HttpRequestMethodNotSupportedException) {
//自定义错误 logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={}path:{},method:{}]", e.getMessage(), request.getRequestURL(), request.getMethod());
if (e instanceof MyException) { return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null);
MyException exception = (MyException) e; }
logger.debug("返回了自定义的exception,[code={},msg={},result={}]", exception.getCode(), e.getMessage(), exception.getResult()); //数据输入类型不匹配
return new Response<>(exception.getCode(), e.getMessage(), exception.getResult()); if (e instanceof MethodArgumentTypeMismatchException) {
} logger.debug("输入类型不匹配,[msg={}]", e.getMessage());
//请求路径不支持该方法 return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null);
if (e instanceof HttpRequestMethodNotSupportedException) { }
logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={}path:{},method:{}]", e.getMessage(), request.getRequestURL(), request.getMethod()); //数据验证失败
return new Response<>(ResponseEnum.ERROR.getCode(), e.getMessage(), null); if (e instanceof BindException) {
} logger.debug("数据验证失败,[msg={}]", e.getMessage());
//数据输入类型不匹配 return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null);
if (e instanceof MethodArgumentTypeMismatchException) { }
logger.debug("输入类型不匹配,[msg={}]", e.getMessage()); //数据输入不完整
return new Response<>(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null); if (e instanceof MissingServletRequestParameterException) {
} logger.debug("数据输入不完整,[msg={}]", e.getMessage());
//数据验证失败 return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null);
if (e instanceof BindException) { }
logger.debug("数据验证失败,[msg={}]", e.getMessage());
return new Response<>(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null); // 发送错误信息到邮箱
} if ("prod".equals(EnvironmentUtil.getProperties("spring.profiles.active", "dev"))) {
//数据输入不完整 logger.debug("有一个未捕获的bug已发送到邮箱");
if (e instanceof MissingServletRequestParameterException) { sendMessage(e);
logger.debug("数据输入不完整,[msg={}]", e.getMessage()); }
return new Response<>(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null); e.printStackTrace();
} return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null);
if (e instanceof MethodArgumentNotValidException) { }
logger.debug("数据验证失败,[msg: {}]", e.getMessage());
BindingResult violations = ((MethodArgumentNotValidException) e).getBindingResult(); /**
return new Response<>(ResponseEnum.PARAMETERS_ERROR.getCode(), violations.getAllErrors().get(0).getDefaultMessage(), null); * 发送错误信息
} *
* @param e 错误
// 发送错误信息到邮箱 */
if ("prod".equals(activeModel)) { private void sendMessage(Exception e) {
logger.debug("有一个未捕获的bug已发送到邮箱"); SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
sendMessage(e); simpleMailMessage.setTo("a@celess.cn");
} simpleMailMessage.setSubject("服务器出现了错误");
e.printStackTrace(); StringBuilder msg = new StringBuilder();
return new Response<>(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null); String queryString = request.getQueryString();
} msg.append("requirePath:\n").append(request.getRequestURL().toString());
if (queryString != null) {
/** msg.append("?").append(queryString);
* 发送错误信息 }
* msg.append("\n\n\n");
* @param e 错误 msg.append("msg:\n").append(e.getMessage()).append("\n\n\n");
*/ msg.append("date:\n").append(DateFormatUtil.getNow()).append("\n\n\n");
private void sendMessage(Exception e) { msg.append("from:\n").append(request.getHeader("User-Agent")).append("\n\n\n");
SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); msg.append("ip:\n").append(request.getRemoteAddr()).append("\n\n\n");
simpleMailMessage.setTo("a@celess.cn"); simpleMailMessage.setText(msg.toString());
simpleMailMessage.setSubject("服务器出现了错误"); mailService.AsyncSend(simpleMailMessage);
StringBuilder msg = new StringBuilder(); }
String queryString = request.getQueryString();
msg.append("requirePath:\n").append(request.getRequestURL().toString()); }
if (queryString != null) {
msg.append("?").append(queryString);
}
msg.append("\n\n\n");
msg.append("msg:\n").append(e.getMessage()).append("\n\n\n");
msg.append("date:\n").append(DateFormatUtil.getNow()).append("\n\n\n");
msg.append("from:\n").append(request.getHeader("User-Agent")).append("\n\n\n");
msg.append("ip:\n").append(request.getRemoteAddr()).append("\n\n\n");
simpleMailMessage.setText(msg.toString());
mailService.AsyncSend(simpleMailMessage);
}
}

View File

@@ -1,41 +1,41 @@
package cn.celess.blog.exception; package cn.celess.common.exception;
import cn.celess.blog.enmu.ResponseEnum; import cn.celess.common.constant.ResponseEnum;
import lombok.Data; import lombok.Data;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 16:56 * @date : 2019/03/28 16:56
*/ */
@Data @Data
public class MyException extends RuntimeException { public class BlogResponseException extends RuntimeException {
private int code; private int code;
private Object result; private Object result;
public MyException(int code, String msg) { public BlogResponseException(int code, String msg) {
super(msg); super(msg);
this.code = code; this.code = code;
} }
public MyException(ResponseEnum e) { public BlogResponseException(ResponseEnum e) {
super(e.getMsg()); super(e.getMsg());
this.code = e.getCode(); this.code = e.getCode();
} }
public MyException(ResponseEnum e, Object result) { public BlogResponseException(ResponseEnum e, Object result) {
super(e.getMsg()); super(e.getMsg());
this.code = e.getCode(); this.code = e.getCode();
this.result = result; this.result = result;
} }
public MyException(ResponseEnum e, String msg) { public BlogResponseException(ResponseEnum e, String msg) {
super(msg + e.getMsg()); super(msg + e.getMsg());
this.code = e.getCode(); this.code = e.getCode();
} }
public MyException(ResponseEnum e, String msg, Object result) { public BlogResponseException(ResponseEnum e, String msg, Object result) {
super(e.getMsg()); super(e.getMsg());
this.code = e.getCode(); this.code = e.getCode();
this.result = result; this.result = result;
} }
} }

View File

@@ -1,52 +1,55 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.Article; import cn.celess.common.entity.Article;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.List;
/**
* @Author: 小海 /**
* @Date 2019/06/27 20:43 * @Author: 小海
* @Description * @Date 2019/06/27 20:43
*/ * @Description
@Mapper */
@Repository @Mapper
public interface ArticleMapper { @Repository
public interface ArticleMapper {
int insert(Article a);
int insert(Article a);
int delete(long id);
int delete(long id);
int update(Article a);
int update(Article a);
Article getLastestArticle();
Article getLastestArticle();
Article findArticleById(long id);
Article findArticleById(long id);
boolean existsByTitle(String title);
boolean existsByTitle(String title);
boolean isDeletedById(long id);
boolean isDeletedById(long id);
List<Article> findAllByAuthorId(long authorId);
List<Article> findAllByAuthorId(long authorId);
List<Article> findAllByOpen(boolean isOpen);
List<Article> findAllByOpen(boolean isOpen);
String getTitleById(long id);
String getTitleById(long id);
List<Article> findAllByCategoryId(long id);
List<Article> findAllByCategoryId(long id);
List<Article> findAllByCategoryIdAndOpen(long id);
List<Article> findAllByCategoryIdAndOpen(long id);
List<Article> findAll();
List<Article> findAll();
Article getPreArticle(Long id);
@Cacheable(value = {"articleDao"}, key = "'getPreArticle:'+#id")
Article getNextArticle(Long id); Article getPreArticle(Long id);
int updateReadingNumber(long id); @Cacheable(value = {"articleDao"}, key = "'getNextArticle:'+#id")
Article getNextArticle(Long id);
long count();
int updateReadingNumber(long id);
}
long count();
}

View File

@@ -1,6 +1,7 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.ArticleTag; import cn.celess.common.entity.ArticleTag;
import cn.celess.common.entity.Tag;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@@ -27,6 +28,8 @@ public interface ArticleTagMapper {
List<ArticleTag> findAllByArticleId(Long articleId); List<ArticleTag> findAllByArticleId(Long articleId);
List<Tag> findTagByArticleId(Long articleId);
int deleteMultiById(List<ArticleTag> articleTags); int deleteMultiById(List<ArticleTag> articleTags);
List<ArticleTag> findArticleByTag(Long tagId); List<ArticleTag> findArticleByTag(Long tagId);

View File

@@ -1,42 +1,42 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.Category; import cn.celess.common.entity.Category;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
/** /**
* @Author: 小海 * @Author: 小海
* @Date 2019/06/30 12:56 * @Date 2019/06/30 12:56
* @Description * @Description
*/ */
@Mapper @Mapper
@Repository @Repository
public interface CategoryMapper { public interface CategoryMapper {
int insert(Category c); int insert(Category c);
int delete(long id); int delete(long id);
int update(Category c); int update(Category c);
boolean existsByName(String name); boolean existsByName(String name);
boolean existsById(long id); boolean existsById(long id);
Category findCategoryByName(String name); Category findCategoryByName(String name);
Category findCategoryById(long id); Category findCategoryById(long id);
List<Category> findAll(); List<Category> findAll();
List<String> getAllName(); List<String> getAllName();
String getNameById(long id); String getNameById(long id);
Long getIdByName(String name); Long getIdByName(String name);
Category getLastestCategory(); Category getLastestCategory();
long count(); long count();
} }

View File

@@ -1,44 +1,44 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.Comment; import cn.celess.common.entity.Comment;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
/** /**
* @Author: 小海 * @Author: 小海
* @Date: 2019/06/30 16:19 * @Date: 2019/06/30 16:19
* @Description: * @Description:
*/ */
@Mapper @Mapper
@Repository @Repository
public interface CommentMapper { public interface CommentMapper {
int insert(Comment c); int insert(Comment c);
int updateContent(String content, long id); int updateContent(String content, long id);
int delete(long id); int delete(long id);
int deleteByPagePath(String pagePath); int deleteByPagePath(String pagePath);
boolean existsById(long id); boolean existsById(long id);
Comment findCommentById(long id); Comment findCommentById(long id);
Comment getLastestComment(); Comment getLastestComment();
List<Comment> findAllByFromUser(long id); List<Comment> findAllByFromUser(long id);
List<Comment> findAllByPid(long pid); List<Comment> findAllByPid(long pid);
List<Comment> findAllByPagePath(String pagePath); List<Comment> findAllByPagePath(String pagePath);
List<Comment> findAllByPagePathAndFromUser(String pagePath, long userId); List<Comment> findAllByPagePathAndFromUser(String pagePath, long userId);
List<Comment> findAllByPagePathAndPidAndNormal(String pagePath, long pid); List<Comment> findAllByPagePathAndPidAndNormal(String pagePath, long pid);
long countByPagePath(String pagePath); long countByPagePath(String pagePath);
long count(); long count();
} }

View File

@@ -1,41 +1,41 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.PartnerSite; import cn.celess.common.entity.PartnerSite;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
/** /**
* @Author: 小海 * @Author: 小海
* @Date 2019/07/03 00:22 * @Date 2019/07/03 00:22
* @Description * @Description
*/ */
@Mapper @Mapper
@Repository @Repository
public interface PartnerMapper { public interface PartnerMapper {
int insert(PartnerSite site); int insert(PartnerSite site);
int delete(long id); int delete(long id);
int update(PartnerSite site); int update(PartnerSite site);
boolean existsById(long id); boolean existsById(long id);
boolean existsByName(String name); boolean existsByName(String name);
boolean existsByUrl(String url); boolean existsByUrl(String url);
PartnerSite findById(long id); PartnerSite findById(long id);
PartnerSite findByName(String name); PartnerSite findByName(String name);
PartnerSite findByUrl(String url); PartnerSite findByUrl(String url);
PartnerSite getLastest(); PartnerSite getLastest();
List<PartnerSite> findAll(); List<PartnerSite> findAll();
List<PartnerSite> findAll(Boolean deleted); List<PartnerSite> findAll(Boolean deleted);
} }

View File

@@ -1,34 +1,34 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.Tag; import cn.celess.common.entity.Tag;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
/** /**
* @Author: 小海 * @Author: 小海
* @Date 2019/06/29 22:00 * @Date 2019/06/29 22:00
* @Description * @Description
*/ */
@Mapper @Mapper
@Repository @Repository
public interface TagMapper { public interface TagMapper {
int insert(Tag tag); int insert(Tag tag);
int update(Tag tag); int update(Tag tag);
int delete(long id); int delete(long id);
Tag findTagById(long id); Tag findTagById(long id);
Tag findTagByName(String name); Tag findTagByName(String name);
Boolean existsByName(String name); Boolean existsByName(String name);
Tag getLastestTag(); Tag getLastestTag();
List<Tag> findAll(); List<Tag> findAll();
long count(); long count();
} }

View File

@@ -1,61 +1,61 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.User; import cn.celess.common.entity.User;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
/** /**
* @Author: 小海 * @Author: 小海
* @Date 2019/07/03 00:23 * @Date 2019/07/03 00:23
* @Description * @Description
*/ */
@Mapper @Mapper
@Repository @Repository
public interface UserMapper { public interface UserMapper {
int addUser(User user); int addUser(User user);
int updateInfo(String desc, String displayName, long id); int updateInfo(String desc, String displayName, long id);
int updateAvatarImgUrl(String avatarImgUrl, long id); int updateAvatarImgUrl(String avatarImgUrl, long id);
int updateLoginTime(String email); int updateLoginTime(String email);
int updateEmailStatus(String email, boolean status); int updateEmailStatus(String email, boolean status);
int updatePwd(String email, String pwd); int updatePwd(String email, String pwd);
String getPwd(String email); String getPwd(String email);
boolean existsByEmail(String email); boolean existsByEmail(String email);
User findByEmail(String email); User findByEmail(String email);
User findById(long id); User findById(long id);
String getAvatarImgUrlById(long id); String getAvatarImgUrlById(long id);
String getEmail(long id); String getEmail(long id);
String getDisPlayName(long id); String getDisPlayName(long id);
String getRoleByEmail(String email); String getRoleByEmail(String email);
String getRoleById(long id); String getRoleById(long id);
long count(); long count();
int delete(long id); int delete(long id);
int lock(long id); int lock(long id);
int setUserRole(Long id, String role); int setUserRole(Long id, String role);
List<User> findAll(Integer status); List<User> findAll(Integer status);
List<User> findAll(); List<User> findAll();
int update(User user); int update(User user);
} }

View File

@@ -1,26 +1,26 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.Visitor; import cn.celess.common.entity.Visitor;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
/** /**
* @Author: 小海 * @Author: 小海
* @Date 2019/07/03 00:23 * @Date 2019/07/03 00:23
* @Description * @Description
*/ */
@Repository @Repository
@Mapper @Mapper
public interface VisitorMapper { public interface VisitorMapper {
int insert(Visitor visitor); int insert(Visitor visitor);
int delete(long id); int delete(long id);
List<Visitor> findAll(); List<Visitor> findAll();
List<Visitor> findAllNotDeleted(); List<Visitor> findAllNotDeleted();
long count(); long count();
} }

View File

@@ -1,32 +1,32 @@
package cn.celess.blog.mapper; package cn.celess.common.mapper;
import cn.celess.blog.entity.WebUpdate; import cn.celess.common.entity.WebUpdate;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List; import java.util.List;
/** /**
* @Author: 小海 * @Author: 小海
* @Date 2019/07/03 00:24 * @Date 2019/07/03 00:24
* @Description * @Description
*/ */
@Mapper @Mapper
@Repository @Repository
public interface WebUpdateInfoMapper { public interface WebUpdateInfoMapper {
int insert(WebUpdate webUpdate); int insert(WebUpdate webUpdate);
int delete(long id); int delete(long id);
int update(long id, String info); int update(long id, String info);
boolean existsById(long id); boolean existsById(long id);
WebUpdate findById(long id); WebUpdate findById(long id);
List<WebUpdate> findAll(); List<WebUpdate> findAll();
List<WebUpdate> findAllNotDeleted(); List<WebUpdate> findAllNotDeleted();
WebUpdate getLastestOne(); WebUpdate getLastestOne();
} }

View File

@@ -1,85 +1,85 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.model.ArticleModel; import cn.celess.common.entity.dto.ArticleReq;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.ArticleModel;
import cn.celess.blog.entity.request.ArticleReq; import cn.celess.common.entity.vo.PageData;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 15:20 * @date : 2019/03/28 15:20
*/ */
@Service @Service
public interface ArticleService { public interface ArticleService {
/** /**
* 新增一篇文章 * 新增一篇文章
* *
* @param reqBody 请求文章的数据 * @param reqBody 请求文章的数据
* @return 文章数据 * @return 文章数据
*/ */
ArticleModel create(ArticleReq reqBody); ArticleModel create(ArticleReq reqBody);
/** /**
* 删除一篇文章 * 删除一篇文章
* *
* @param articleID 文章id * @param articleID 文章id
* @return 删除状态 true删除成功 false失败 * @return 删除状态 true删除成功 false失败
*/ */
boolean delete(long articleID); boolean delete(long articleID);
/** /**
* 更新一篇文章 * 更新一篇文章
* *
* @param reqBody 请求数据 * @param reqBody 请求数据
* @return 文章数据 * @return 文章数据
*/ */
ArticleModel update(ArticleReq reqBody); ArticleModel update(ArticleReq reqBody);
/** /**
* 获取一篇文章的数据 * 获取一篇文章的数据
* *
* @param articleId 文章id * @param articleId 文章id
* @param is4update 是否是因文章更新而请求数据 * @param is4update 是否是因文章更新而请求数据
* @return 文章数据 * @return 文章数据
*/ */
ArticleModel retrieveOneById(long articleId, boolean is4update); ArticleModel retrieveOneById(long articleId, boolean is4update);
/** /**
* 管理员 获取分页数据 * 管理员 获取分页数据
* *
* @param count 单页数据量 * @param count 单页数据量
* @param page 数据页 * @param page 数据页
* @return 分页数据 * @return 分页数据
*/ */
PageData<ArticleModel> adminArticles(int count, int page, Boolean deleted); PageData<ArticleModel> adminArticles(int count, int page, Boolean deleted);
/** /**
* 获取文章状态为开放的文章 * 获取文章状态为开放的文章
* *
* @param count 单页数据量 * @param count 单页数据量
* @param page 数据页 * @param page 数据页
* @return 分页数据 * @return 分页数据
*/ */
PageData<ArticleModel> retrievePageForOpen(int count, int page); PageData<ArticleModel> retrievePageForOpen(int count, int page);
/** /**
* 根据分类名获取文章数据 * 根据分类名获取文章数据
* *
* @param name 分类名 * @param name 分类名
* @param count 单页数据量 * @param count 单页数据量
* @param page 数据页 * @param page 数据页
* @return 分页数据 * @return 分页数据
*/ */
PageData<ArticleModel> findByCategory(String name, int page, int count); PageData<ArticleModel> findByCategory(String name, int page, int count);
/** /**
* 根据标签名获取文章数据 * 根据标签名获取文章数据
* *
* @param name 标签名 * @param name 标签名
* @param count 单页数据量 * @param count 单页数据量
* @param page 数据页 * @param page 数据页
* @return 分页数据 * @return 分页数据
*/ */
PageData<ArticleModel> findByTag(String name, int page, int count); PageData<ArticleModel> findByTag(String name, int page, int count);
} }

View File

@@ -1,45 +1,45 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.model.CategoryModel; import cn.celess.common.entity.vo.CategoryModel;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.PageData;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 22:42 * @date : 2019/03/28 22:42
*/ */
@Service @Service
public interface CategoryService { public interface CategoryService {
/** /**
* 增加一个分类 * 增加一个分类
* *
* @param name 分类名 * @param name 分类名
* @return 所增加的分类数据 * @return 所增加的分类数据
*/ */
CategoryModel create(String name); CategoryModel create(String name);
/** /**
* 通过id删除分类 * 通过id删除分类
* *
* @param id 分类id * @param id 分类id
* @return 删除状态 * @return 删除状态
*/ */
boolean delete(long id); boolean delete(long id);
/** /**
* 编辑分类的名字 * 编辑分类的名字
* *
* @param id 分类id * @param id 分类id
* @param name 分类名字 * @param name 分类名字
* @return 更新后的分类的数据 * @return 更新后的分类的数据
*/ */
CategoryModel update(Long id, String name); CategoryModel update(Long id, String name);
/** /**
* 获取全部的分类数据 * 获取全部的分类数据
* *
* @return 全部的分类数据 * @return 全部的分类数据
*/ */
PageData<CategoryModel> retrievePage(int page, int count); PageData<CategoryModel> retrievePage(int page, int count);
} }

View File

@@ -1,91 +1,92 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.model.CommentModel;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.dto.CommentReq;
import cn.celess.blog.entity.request.CommentReq; import cn.celess.common.entity.vo.CommentModel;
import org.springframework.stereotype.Service; import cn.celess.common.entity.vo.PageData;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.List;
/**
* @author : xiaohai /**
* @date : 2019/03/29 16:58 * @author : xiaohai
*/ * @date : 2019/03/29 16:58
@Service */
public interface CommentService { @Service
/** public interface CommentService {
* 新增数据 /**
* * 新增数据
* @param reqBody 请求数据体 *
* @return 增加的comment数据 * @param reqBody 请求数据
*/ * @return 增加的comment数据
CommentModel create(CommentReq reqBody); */
CommentModel create(CommentReq reqBody);
/**
* 删除数据 /**
* * 删除数据
* @param id comment的id *
* @return 删除状态 * @param id comment的id
*/ * @return 删除状态
boolean delete(long id); */
boolean delete(long id);
/**
* 更新数据 /**
* * 更新数据
* @param reqBody comment请求体 *
* @return 更新后的数据 * @param reqBody comment请求体
*/ * @return 更新后的数据
CommentModel update(CommentReq reqBody); */
CommentModel update(CommentReq reqBody);
/**
* 分页获取数据 /**
* * 分页获取数据
* @param pagePath pagePath *
* @param count 单页数据量 * @param pagePath pagePath
* @param page 数据 * @param count 单页数据
* @return 分页数据 * @param page 数据
*/ * @return 分页数据
PageData<CommentModel> retrievePage(String pagePath, int page, int count); */
PageData<CommentModel> retrievePage(String pagePath, int page, int count);
/**
* 通过pid获取数据 /**
* * 通过pid获取数据
* @param pid 父id *
* @return 分页数据 * @param pid 父id
*/ * @return 分页数据
List<CommentModel> retrievePageByPid(long pid); */
List<CommentModel> retrievePageByPid(long pid);
/**
* 根据评论者获取数据 /**
* * 根据评论者获取数据
* @param pagePath pagePath *
* @param count 单页数据量 * @param pagePath pagePath
* @param page 数据 * @param count 单页数据
* @return 分页数据 * @param page 数据
*/ * @return 分页数据
PageData<CommentModel> retrievePageByAuthor(String pagePath, int page, int count); */
PageData<CommentModel> retrievePageByAuthor(String pagePath, int page, int count);
/**
* 根据数据的type和pid获取数据 /**
* * 根据数据的type和pid获取数据
* @param pagePath pagePath *
* @param pid 父id * @param pagePath pagePath
* @param count 单页数据量 * @param pid 父id
* @param page 数据 * @param count 单页数据
* @return 分页数据 * @param page 数据
*/ * @return 分页数据
PageData<CommentModel> retrievePageByPageAndPid(String pagePath, long pid, int page, int count); */
PageData<CommentModel> retrievePageByPageAndPid(String pagePath, long pid, int page, int count);
/**
* 根据type获取数据 /**
* * 根据type获取数据
* @param pagePath pagePath *
* @param count 单页数据量 * @param pagePath pagePath
* @param page 数据 * @param count 单页数据
* @return 分页数据 * @param page 数据
*/ * @return 分页数据
PageData<CommentModel> retrievePageByPage(String pagePath, int page, int count); */
PageData<CommentModel> retrievePageByPage(String pagePath, int page, int count);
}
}

View File

@@ -1,59 +1,59 @@
package cn.celess.blog.service; package cn.celess.common.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/04/02 22:04 * @date : 2019/04/02 22:04
*/ */
@Service @Service
public interface CountService { public interface CountService {
/** /**
* 获取评论的数据量 * 获取评论的数据量
* *
* @return 评论的数据量 * @return 评论的数据量
*/ */
long getCommentCount(); long getCommentCount();
/** /**
* 获取文章的篇数 * 获取文章的篇数
* *
* @return 文章的篇数 * @return 文章的篇数
*/ */
long getArticleCount(); long getArticleCount();
/** /**
* 获取分类数量 * 获取分类数量
* *
* @return 分类数量 * @return 分类数量
*/ */
long getCategoriesCount(); long getCategoriesCount();
/** /**
* 获取标签数量 * 获取标签数量
* *
* @return 标签数量 * @return 标签数量
*/ */
long getTagsCount(); long getTagsCount();
/** /**
* 获取用户量 * 获取用户量
* *
* @return 用户量 * @return 用户量
*/ */
long getUserCount(); long getUserCount();
/** /**
* 获取总访问量 * 获取总访问量
* *
* @return 总访问量 * @return 总访问量
*/ */
long getVisitorCount(); long getVisitorCount();
/** /**
* 获取日访问量 * 获取日访问量
* *
* @return 日访问量 * @return 日访问量
*/ */
long getDayVisitCount(); long getDayVisitCount();
} }

View File

@@ -1,27 +1,27 @@
package cn.celess.blog.service; package cn.celess.common.service;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/04/22 14:25 * @date : 2019/04/22 14:25
*/ */
@Service @Service
public interface MailService { public interface MailService {
/** /**
* 异步发生邮件 * 异步发生邮件
* *
* @param message SimpleMailMessage对象 * @param message SimpleMailMessage对象
* @return // * @return //
*/ */
Boolean AsyncSend(SimpleMailMessage message); Boolean AsyncSend(SimpleMailMessage message);
/** /**
* 同步发送邮件 * 同步发送邮件
* *
* @param message SimpleMailMessage对象 * @param message SimpleMailMessage对象
* @return 发送状态 * @return 发送状态
*/ */
Boolean send(SimpleMailMessage message); Boolean send(SimpleMailMessage message);
} }

View File

@@ -1,72 +1,72 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.PartnerSite; import cn.celess.common.entity.PartnerSite;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.dto.LinkApplyReq;
import cn.celess.blog.entity.request.LinkApplyReq; import cn.celess.common.entity.dto.LinkReq;
import cn.celess.blog.entity.request.LinkReq; import cn.celess.common.entity.vo.PageData;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/05/12 11:42 * @date : 2019/05/12 11:42
*/ */
@Service @Service
public interface PartnerSiteService { public interface PartnerSiteService {
/** /**
* 新增数据 * 新增数据
* *
* @param reqBody 数据请求体 * @param reqBody 数据请求体
* @return 新增数据 * @return 新增数据
*/ */
PartnerSite create(LinkReq reqBody); PartnerSite create(LinkReq reqBody);
/** /**
* 删除数据 * 删除数据
* *
* @param id 数据id * @param id 数据id
* @return 删除状态 * @return 删除状态
*/ */
Boolean del(long id); Boolean del(long id);
/** /**
* 更新数据 * 更新数据
* *
* @param reqBody 数据请求体 * @param reqBody 数据请求体
* @return 更新后的数据 * @return 更新后的数据
*/ */
PartnerSite update(LinkReq reqBody); PartnerSite update(LinkReq reqBody);
/** /**
* 分页获取数据 * 分页获取数据
* *
* @param count 单页数据量 * @param count 单页数据量
* @param page 数据页 * @param page 数据页
* @return 分页数据 * @return 分页数据
*/ */
PageData<PartnerSite> partnerSitePages(int page, int count, Boolean deleted); PageData<PartnerSite> partnerSitePages(int page, int count, Boolean deleted);
/** /**
* 获取全部数据 * 获取全部数据
* *
* @return 全部友链数据 * @return 全部友链数据
*/ */
List<PartnerSite> findAll(); List<PartnerSite> findAll();
/** /**
* 申请友链 * 申请友链
* *
* @param linkApplyReq linkApplyReq * @param linkApplyReq linkApplyReq
* @return linkApplyReq * @return linkApplyReq
*/ */
PartnerSite apply(LinkApplyReq linkApplyReq); PartnerSite apply(LinkApplyReq linkApplyReq);
/** /**
* 重写申请友链 * 重写申请友链
* *
* @param key key * @param key key
* @return msg * @return msg
*/ */
String reapply(String key); String reapply(String key);
} }

View File

@@ -0,0 +1,31 @@
package cn.celess.common.service;
import cn.celess.common.entity.vo.QiniuResponse;
import com.qiniu.storage.model.FileInfo;
import org.springframework.stereotype.Service;
import java.io.InputStream;
/**
* @author : xiaohai
* @date : 2019/04/25 18:15
*/
@Service
public interface QiniuService {
/**
* 上传文件
*
* @param is InputStream流
* @param fileName 文件名
* @return 响应数据
*/
QiniuResponse uploadFile(InputStream is, String fileName);
/**
* 获取文件列表
*
* @return 文件列表
*/
FileInfo[] getFileList();
}

View File

@@ -1,56 +1,56 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.entity.model.TagModel; import cn.celess.common.entity.vo.TagModel;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 22:23 * @date : 2019/03/28 22:23
*/ */
@Service @Service
public interface TagService { public interface TagService {
/** /**
* 新增数据 * 新增数据
* *
* @param name 标签名 * @param name 标签名
* @return 新增后的数据 * @return 新增后的数据
*/ */
TagModel create(String name); TagModel create(String name);
/** /**
* 删除数据 * 删除数据
* *
* @param tagId 标签id * @param tagId 标签id
* @return 删除状态 * @return 删除状态
*/ */
boolean delete(long tagId); boolean delete(long tagId);
/** /**
* 更新数据 * 更新数据
* *
* @param id 标签id * @param id 标签id
* @param name 改名的name值 * @param name 改名的name值
* @return 更新后的数据 * @return 更新后的数据
*/ */
TagModel update(Long id, String name); TagModel update(Long id, String name);
/** /**
* 分页获取标签数据 * 分页获取标签数据
* *
* @param count 单页数据量 * @param count 单页数据量
* @param page 数据页 * @param page 数据页
* @return 分页数据 * @return 分页数据
*/ */
PageData<TagModel> retrievePage(int page, int count); PageData<TagModel> retrievePage(int page, int count);
/** /**
* 获取全部标签数据 * 获取全部标签数据
* *
* @return 标签数据列表 * @return 标签数据列表
*/ */
List<TagModel> findAll(); List<TagModel> findAll();
} }

View File

@@ -1,159 +1,159 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.dto.LoginReq;
import cn.celess.blog.entity.model.UserModel; import cn.celess.common.entity.dto.UserReq;
import cn.celess.blog.entity.request.LoginReq; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.entity.request.UserReq; import cn.celess.common.entity.vo.UserModel;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.InputStream; import java.io.InputStream;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/30 18:40 * @date : 2019/03/30 18:40
*/ */
@Service @Service
public interface UserService { public interface UserService {
/** /**
* 注册 * 注册
* *
* @param email 邮箱 * @param email 邮箱
* @param password 密码 * @param password 密码
* @return 注册状态 * @return 注册状态
*/ */
Boolean registration(String email, String password); Boolean registration(String email, String password);
/** /**
* 登录 * 登录
* *
* @param loginReq 请求数据 * @param loginReq 请求数据
* @return 用户数据 * @return 用户数据
*/ */
UserModel login(LoginReq loginReq); UserModel login(LoginReq loginReq);
/** /**
* 注销登录 * 注销登录
* *
* @return ** * @return **
*/ */
Object logout(); Object logout();
/** /**
* 更新用户数据 * 更新用户数据
* *
* @param desc 用户描述 * @param desc 用户描述
* @param displayName 显示昵称 * @param displayName 显示昵称
* @return 用户数据 * @return 用户数据
*/ */
UserModel update(String desc, String displayName); UserModel update(String desc, String displayName);
/** /**
* 更新头像 * 更新头像
* *
* @param is 头像文件的输入流 * @param is 头像文件的输入流
* @param mime 文件的mime * @param mime 文件的mime
* @return 响应数据 * @return 响应数据
*/ */
Object updateUserAavatarImg(InputStream is, String mime); Object updateUserAavatarImg(InputStream is, String mime);
/** /**
* 获取session中存储的用户资料 * 获取session中存储的用户资料
* *
* @return 用户资料 * @return 用户资料
*/ */
UserModel getUserInfoBySession(); UserModel getUserInfoBySession();
/** /**
* 获取用户的角色 * 获取用户的角色
* *
* @param email 用户的邮箱 * @param email 用户的邮箱
* @return role * @return role
*/ */
String getUserRoleByEmail(String email); String getUserRoleByEmail(String email);
/** /**
* 获取邮箱是否注册过 * 获取邮箱是否注册过
* *
* @param email 用户邮箱 * @param email 用户邮箱
* @return 注册状态 * @return 注册状态
*/ */
boolean isExistOfEmail(String email); boolean isExistOfEmail(String email);
/** /**
* 发送重置密码邮件 * 发送重置密码邮件
* *
* @param email 用户邮箱 * @param email 用户邮箱
* @return 发送状态 * @return 发送状态
*/ */
Object sendResetPwdEmail(String email); Object sendResetPwdEmail(String email);
/** /**
* 发送验证邮箱邮件 * 发送验证邮箱邮件
* *
* @param email 用户邮箱 * @param email 用户邮箱
* @return 发送状态 * @return 发送状态
*/ */
Object sendVerifyEmail(String email); Object sendVerifyEmail(String email);
/** /**
* 验证邮箱 * 验证邮箱
* *
* @param verifyId 验证码 * @param verifyId 验证码
* @param email 邮箱 * @param email 邮箱
* @return 验证状态 * @return 验证状态
*/ */
Object verifyEmail(String verifyId, String email); Object verifyEmail(String verifyId, String email);
/** /**
* 重置密码 * 重置密码
* *
* @param verifyId 验证码 * @param verifyId 验证码
* @param email 邮箱 * @param email 邮箱
* @param pwd 新密码 * @param pwd 新密码
* @return 修改状态 * @return 修改状态
*/ */
Object reSetPwd(String verifyId, String email, String pwd); Object reSetPwd(String verifyId, String email, String pwd);
/** /**
* 删除用户 * 删除用户
* *
* @param id 用户id的数组 * @param id 用户id的数组
* @return 对应id 的删除状态 * @return 对应id 的删除状态
*/ */
Object deleteUser(Integer[] id); Object deleteUser(Integer[] id);
/** /**
* 获取用户列表 * 获取用户列表
* *
* @param count 单页数据量 * @param count 单页数据量
* @param page 数据页 * @param page 数据页
* @return 分页数据 * @return 分页数据
*/ */
PageData<UserModel> getUserList(Integer page, Integer count, Integer status); PageData<UserModel> getUserList(Integer page, Integer count, Integer status);
/** /**
* 更改用户信息 * 更改用户信息
* *
* @param user 用户数据 * @param user 用户数据
* @return 用户信息 * @return 用户信息
*/ */
UserModel adminUpdate(UserReq user); UserModel adminUpdate(UserReq user);
/** /**
* 获取电子邮件的存在状态 * 获取电子邮件的存在状态
* *
* @param email email * @param email email
* @return true:存在 false不存在 * @return true:存在 false不存在
*/ */
boolean getStatusOfEmail(String email); boolean getStatusOfEmail(String email);
/** /**
* 设置密码 * 设置密码
* *
* @param pwd pwd * @param pwd pwd
* @param newPwd newPwd * @param newPwd newPwd
* @param confirmPwd confirmPwd * @param confirmPwd confirmPwd
* @return UserModel * @return UserModel
*/ */
UserModel setPwd(String pwd, String newPwd, String confirmPwd); UserModel setPwd(String pwd, String newPwd, String confirmPwd);
} }

View File

@@ -1,40 +1,40 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.model.PageData; import cn.celess.common.entity.vo.PageData;
import cn.celess.blog.entity.model.VisitorModel; import cn.celess.common.entity.vo.VisitorModel;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/04/02 23:03 * @date : 2019/04/02 23:03
*/ */
@Service @Service
public interface VisitorService { public interface VisitorService {
/** /**
* 分页获取访客数据 * 分页获取访客数据
* *
* @param count 单页数据量 * @param count 单页数据量
* @param page 数据页 * @param page 数据页
* @param showLocation 是否显示位置信息 开启改选项数据响应超慢 * @param showLocation 是否显示位置信息 开启改选项数据响应超慢
* @return 分页数据 * @return 分页数据
*/ */
PageData<VisitorModel> visitorPage(int page, int count, boolean showLocation); PageData<VisitorModel> visitorPage(int page, int count, boolean showLocation);
/** /**
* 新增访客 * 新增访客
* *
* @param request HttpServletRequest * @param request HttpServletRequest
* @return 返回状态 null: 访客信息已记录爬虫 * @return 返回状态 null: 访客信息已记录爬虫
*/ */
VisitorModel addVisitor(HttpServletRequest request); VisitorModel addVisitor(HttpServletRequest request);
/** /**
* 获取位置信息 * 获取位置信息
* *
* @param ip ip地址 * @param ip ip地址
* @return 位置信息 * @return 位置信息
*/ */
String location(String ip); String location(String ip);
} }

View File

@@ -1,63 +1,64 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.WebUpdateModel; import cn.celess.common.entity.vo.PageData;
import org.springframework.stereotype.Service; import cn.celess.common.entity.vo.WebUpdateModel;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map; import java.util.List;
import java.util.Map;
/**
* @author : xiaohai /**
* @date : 2019/05/12 11:42 * @author : xiaohai
*/ * @date : 2019/05/12 11:42
@Service */
public interface WebUpdateInfoService { @Service
/** public interface WebUpdateInfoService {
* 新增记录 /**
* * 新增记录
* @param info 更新内容 *
* @return 创建状态 * @param info 更新内容
*/ * @return 创建状态
WebUpdateModel create(String info); */
WebUpdateModel create(String info);
/**
* 删除数据 /**
* * 删除数据
* @param id 数据id *
* @return 删除状态 * @param id 数据id
*/ * @return 删除状态
Boolean del(long id); */
Boolean del(long id);
/**
* 更新数据 /**
* * 更新数据
* @param id 数据id *
* @param info 新内容 * @param id 数据id
* @return 数据 * @param info 新内容
*/ * @return 数据
WebUpdateModel update(long id, String info); */
WebUpdateModel update(long id, String info);
/**
* 分页获取更新记录 /**
* * 分页获取更新记录
* @param count 单页数据量 *
* @param page 数据 * @param count 单页数据
* @return 分页数据 * @param page 数据
*/ * @return 分页数据
PageData<WebUpdateModel> pages(int count, int page); */
PageData<WebUpdateModel> pages(int count, int page);
/**
* 获取全部的更新记录 /**
* * 获取全部的更新记录
* @return 更新记录 *
*/ * @return 更新记录
List<WebUpdateModel> findAll(); */
List<WebUpdateModel> findAll();
/**
* 获取最后更新时间 /**
* * 获取最后更新时间
* @return *
*/ * @return
Map<String, Object> getLastestUpdateTime(); */
} Map<String, Object> getLastestUpdateTime();
}

View File

@@ -0,0 +1,41 @@
package cn.celess.common.test;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import redis.embedded.RedisServer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
/**
* @author : xiaohai
* @date : 2020/08/14 16:20
*/
@Configuration
@Slf4j
public class BaseRedisTest extends BaseTest {
private static RedisServer redisServer;
@PostConstruct
public static void startRedis() {
try {
if (redisServer == null) {
redisServer = new RedisServer(6380);
redisServer.start();
log.info("start Redis success");
}
} catch (IOException e) {
log.error("start Redis failed");
e.printStackTrace();
}
}
@PreDestroy()
public static void stopRedis() {
if (redisServer.isActive()) {
redisServer.stop();
log.info("stop Redis success");
}
}
}

View File

@@ -1,35 +1,34 @@
package cn.celess.blog; package cn.celess.common.test;
import cn.celess.common.entity.Response;
import cn.celess.blog.entity.Response; import cn.celess.common.entity.dto.LoginReq;
import cn.celess.blog.entity.model.FileInfo; import cn.celess.common.entity.vo.QiniuResponse;
import cn.celess.blog.entity.model.FileResponse; import cn.celess.common.entity.vo.UserModel;
import cn.celess.blog.entity.model.UserModel; import cn.celess.common.service.MailService;
import cn.celess.blog.entity.request.LoginReq; import cn.celess.common.service.QiniuService;
import cn.celess.blog.service.MailService; import com.fasterxml.jackson.core.JsonParser;
import cn.celess.blog.service.FileManager;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.storage.model.FileInfo;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.SimpleMailMessage;
import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockHttpSession;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
@@ -37,28 +36,21 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; import static cn.celess.common.constant.ResponseEnum.SUCCESS;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.junit.Assert.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/** /**
* @Author: 小海 * @Author: 小海
* @Date: 2019/08/22 12:46 * @Date: 2019/08/22 12:46
* @Description: 测试基类 * @Description: 测试基类
*/ */
@SpringBootTest
@RunWith(SpringRunner.class)
@WebAppConfiguration @WebAppConfiguration
@ActiveProfiles("test") @ActiveProfiles("test")
public class BaseTest { public abstract class BaseTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final Logger logger = LoggerFactory.getLogger(this.getClass());
@@ -71,7 +63,6 @@ public class BaseTest {
/** /**
* jackson 序列化/反序列化Json * jackson 序列化/反序列化Json
*/ */
protected final ObjectMapper mapper = new ObjectMapper();
protected static final TypeReference<?> BOOLEAN_TYPE = new TypeReference<Response<Boolean>>() { protected static final TypeReference<?> BOOLEAN_TYPE = new TypeReference<Response<Boolean>>() {
}; };
protected static final TypeReference<?> STRING_TYPE = new TypeReference<Response<String>>() { protected static final TypeReference<?> STRING_TYPE = new TypeReference<Response<String>>() {
@@ -136,9 +127,9 @@ public class BaseTest {
protected String login(LoginReq req) { protected String login(LoginReq req) {
String str = null; String str = null;
try { try {
str = getMockData(post("/login"), null, req) str = getMockData(MockMvcRequestBuilders.post("/login"), null, req)
.andReturn().getResponse().getContentAsString(); .andReturn().getResponse().getContentAsString();
Response<UserModel> response = mapper.readValue(str, new TypeReference<Response<UserModel>>() { Response<UserModel> response = new ObjectMapper().readValue(str, new TypeReference<Response<UserModel>>() {
}); });
assertEquals(SUCCESS.getCode(), response.getCode()); assertEquals(SUCCESS.getCode(), response.getCode());
String token = response.getResult().getToken(); String token = response.getResult().getToken();
@@ -152,20 +143,6 @@ public class BaseTest {
return null; return null;
} }
@Test
public void test() {
// 测试登录
assertNotNull(userLogin());
assertNotNull(adminLogin());
assertNotEquals(userLogin(), adminLogin());
try {
// 测试getMockData方法
assertNotNull(getMockData(get("/headerInfo")));
getMockData((get("/headerInfo"))).andDo(result -> assertNotNull(getResponse(result, OBJECT_TYPE)));
} catch (Exception e) {
e.printStackTrace();
}
}
/** /**
* 产生指定长度的随机字符 * 产生指定长度的随机字符
@@ -221,13 +198,14 @@ public class BaseTest {
protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token, Object content) throws Exception { protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token, Object content) throws Exception {
// MockHttpServletRequestBuilder mockHttpServletRequestBuilder = get(url); // MockHttpServletRequestBuilder mockHttpServletRequestBuilder = get(url);
if (token != null) { if (token != null) {
builder.header("Authorization", token); builder.header("Authorization", "Bearer "+token);
} }
if (content != null) { if (content != null) {
ObjectMapper mapper = new ObjectMapper();
builder.content(mapper.writeValueAsString(content)).contentType(MediaType.APPLICATION_JSON); builder.content(mapper.writeValueAsString(content)).contentType(MediaType.APPLICATION_JSON);
logger.debug("param::json->{}", mapper.writeValueAsString(content)); logger.debug("param::json->{}", mapper.writeValueAsString(content));
} }
return mockMvc.perform(builder).andExpect(status().isOk()); return mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isOk());
} }
@@ -249,7 +227,9 @@ public class BaseTest {
protected <T> Response<T> getResponse(String json, TypeReference<?> responseType) { protected <T> Response<T> getResponse(String json, TypeReference<?> responseType) {
Response<T> response = null; Response<T> response = null;
try { try {
response = mapper.readValue(json, responseType); ObjectMapper mapper = new ObjectMapper();
mapper.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
response = (Response<T>) mapper.readValue(json, responseType);
} catch (IOException e) { } catch (IOException e) {
logger.error("解析json Response对象错误json:[{}]", json); logger.error("解析json Response对象错误json:[{}]", json);
e.printStackTrace(); e.printStackTrace();
@@ -296,6 +276,7 @@ public class BaseTest {
@Slf4j @Slf4j
@Service("mailService")
public static class TestMailServiceImpl implements MailService { public static class TestMailServiceImpl implements MailService {
@Override @Override
@@ -327,29 +308,24 @@ public class BaseTest {
} }
@Slf4j @Slf4j
public static class TestFileManager implements FileManager { @Service("qiniuService")
public static class TestQiNiuServiceImpl implements QiniuService {
@Override @Override
public FileResponse uploadFile(InputStream is, String fileName) { public QiniuResponse uploadFile(InputStream is, String fileName) {
FileResponse response = new FileResponse(); QiniuResponse response = new QiniuResponse();
log.debug("上传文件请求,[fileName:{}]", fileName); log.debug("上传文件请求,[fileName:{}]", fileName);
response.key = "key"; response.key = "key";
response.type = "test"; response.bucket = "bucket";
response.hash = "hash"; response.hash = "hash";
response.size = 1; response.fsize = 1;
return response; return response;
} }
@Override @Override
public List<FileInfo> getFileList() { public FileInfo[] getFileList() {
log.debug("获取文件列表请求"); log.debug("获取文件列表请求");
return new ArrayList<>(); return new FileInfo[0];
}
@Override
public boolean deleteFile(String fileName) {
log.debug("删除[{}]成功", fileName);
return true;
} }
} }
} }

View File

@@ -1,42 +1,42 @@
package cn.celess.blog.util; package cn.celess.common.util;
import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.datatype.XMLGregorianCalendar;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 17:22 * @date : 2019/03/28 17:22
*/ */
public class DateFormatUtil { public class DateFormatUtil {
public static String get(Date date) { public static String get(Date date) {
if (date == null) { if (date == null) {
return null; return null;
} }
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date); return sdf.format(date);
} }
public static String getForXmlDate(Date date) { public static String getForXmlDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZ");
GregorianCalendar gc = new GregorianCalendar(); GregorianCalendar gc = new GregorianCalendar();
String dateString = sdf.format(date); String dateString = sdf.format(date);
try { try {
gc.setTime(sdf.parse(dateString)); gc.setTime(sdf.parse(dateString));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
return date2.toString(); return date2.toString();
} catch (DatatypeConfigurationException | ParseException e) { } catch (DatatypeConfigurationException | ParseException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
public static String getNow() { public static String getNow() {
return get(new Date()); return get(new Date());
} }
} }

View File

@@ -0,0 +1,43 @@
package cn.celess.common.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
@Slf4j
public class EnvironmentUtil {
private static Environment environment;
public static String getEnv(String name) {
String value = System.getenv(name);
if (StringUtils.isBlank(value)) {
log.error("没有找到环境变量:" + name);
}
return value;
}
public static String getEnv(String name, String defaultValue) {
String env = getEnv(name);
if (env == null) {
return defaultValue;
}
return env;
}
public static String getProperties(String key) {
String value = environment.getProperty(key);
if (StringUtils.isBlank(value)) {
log.error("没有找到配置项: {}", key);
}
return value;
}
public static String getProperties(String key, String defaultValue) {
return environment.getProperty(key, defaultValue);
}
public static void setEnvironment(Environment environment) {
EnvironmentUtil.environment = environment;
}
}

View File

@@ -1,15 +1,13 @@
package cn.celess.blog.util; package cn.celess.common.util;
import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController; import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlPage;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException; import java.io.IOException;
import java.util.Objects;
/** /**
* @Author: 小海 * @Author: 小海
@@ -17,23 +15,37 @@ import java.util.Objects;
* @Desc: * @Desc:
*/ */
public class HttpUtil { public class HttpUtil {
private static final OkHttpClient CLIENT = new OkHttpClient();
public static String get(String urlStr) { /**
Request request = new Request.Builder() * 获取http请求的响应
.url(urlStr) *
.get() * @param url url链接
.build(); * @return 请求的响应
try (Response response = CLIENT.newCall(request).execute()) { */
return Objects.requireNonNull(response.body()).string(); public static String getHttpResponse(String url) {
try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setDownloadImages(false);
webClient.getOptions().setActiveXNative(false);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
Page clientPage = webClient.getPage(url);
return clientPage.getWebResponse().getContentAsString();
} catch (IOException e) { } catch (IOException e) {
return null; return null;
} }
} }
/**
* 获取渲染后的网页数据
*
* @param url url链接
* @return 经js渲染后的网页源代码
*/
public static String getAfterRendering(String url) { public static String getAfterRendering(String url) {
try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) { try (final WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED)) {
webClient.getOptions().setCssEnabled(false); webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(true); webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);

View File

@@ -1,8 +1,9 @@
package cn.celess.blog.util; package cn.celess.common.util;
import cn.celess.blog.enmu.UserAccountStatusEnum;
import cn.celess.blog.entity.*; import cn.celess.common.constant.UserAccountStatusEnum;
import cn.celess.blog.entity.model.*; import cn.celess.common.entity.*;
import cn.celess.common.entity.vo.*;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
/** /**

View File

@@ -1,126 +1,126 @@
package cn.celess.blog.util; package cn.celess.common.util;
import com.dyuproject.protostuff.LinkedBuffer; import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil; import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema; import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema; import com.dyuproject.protostuff.runtime.RuntimeSchema;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
/** /**
* ProtoStuffSerializerUtil * ProtoStuffSerializerUtil
* *
* @author Sirius * @author Sirius
* @date 2019-1-8 * @date 2019-1-8
*/ */
public class ProtoStuffSerializerUtil { public class ProtoStuffSerializerUtil {
/** /**
* 序列化对象 * 序列化对象
* *
* @param obj * @param obj
* @return * @return
*/ */
public static <T> byte[] serialize(T obj) { public static <T> byte[] serialize(T obj) {
if (obj == null) { if (obj == null) {
throw new RuntimeException("序列化对象(" + obj + ")!"); throw new RuntimeException("序列化对象(" + obj + ")!");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(obj.getClass()); Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(obj.getClass());
LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024); LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
byte[] protostuff = null; byte[] protostuff = null;
try { try {
protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer); protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e); throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e);
} finally { } finally {
buffer.clear(); buffer.clear();
} }
return protostuff; return protostuff;
} }
/** /**
* 反序列化对象 * 反序列化对象
* *
* @param paramArrayOfByte * @param paramArrayOfByte
* @param targetClass * @param targetClass
* @return * @return
*/ */
public static <T> T deserialize(byte[] paramArrayOfByte, Class<T> targetClass) { public static <T> T deserialize(byte[] paramArrayOfByte, Class<T> targetClass) {
if (paramArrayOfByte == null || paramArrayOfByte.length == 0) { if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
throw new RuntimeException("反序列化对象发生异常,byte序列为空!"); throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
} }
T instance = null; T instance = null;
try { try {
instance = targetClass.newInstance(); instance = targetClass.newInstance();
} catch (InstantiationException e1) { } catch (InstantiationException e1) {
throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e1); throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e1);
} catch (IllegalAccessException e2) { } catch (IllegalAccessException e2) {
throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e2); throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e2);
} }
Schema<T> schema = RuntimeSchema.getSchema(targetClass); Schema<T> schema = RuntimeSchema.getSchema(targetClass);
ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema); ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema);
return instance; return instance;
} }
/** /**
* 序列化列表 * 序列化列表
* *
* @param objList * @param objList
* @return * @return
*/ */
public static <T> byte[] serializeList(List<T> objList) { public static <T> byte[] serializeList(List<T> objList) {
if (objList == null || objList.isEmpty()) { if (objList == null || objList.isEmpty()) {
throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!"); throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(objList.get(0).getClass()); Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(objList.get(0).getClass());
LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024); LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
byte[] protostuff = null; byte[] protostuff = null;
ByteArrayOutputStream bos = null; ByteArrayOutputStream bos = null;
try { try {
bos = new ByteArrayOutputStream(); bos = new ByteArrayOutputStream();
ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer); ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer);
protostuff = bos.toByteArray(); protostuff = bos.toByteArray();
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e); throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e);
} finally { } finally {
buffer.clear(); buffer.clear();
try { try {
if (bos != null) { if (bos != null) {
bos.close(); bos.close();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
return protostuff; return protostuff;
} }
/** /**
* 反序列化列表 * 反序列化列表
* *
* @param paramArrayOfByte * @param paramArrayOfByte
* @param targetClass * @param targetClass
* @return * @return
*/ */
public static <T> List<T> deserializeList(byte[] paramArrayOfByte, Class<T> targetClass) { public static <T> List<T> deserializeList(byte[] paramArrayOfByte, Class<T> targetClass) {
if (paramArrayOfByte == null || paramArrayOfByte.length == 0) { if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
throw new RuntimeException("反序列化对象发生异常,byte序列为空!"); throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
} }
Schema<T> schema = RuntimeSchema.getSchema(targetClass); Schema<T> schema = RuntimeSchema.getSchema(targetClass);
List<T> result = null; List<T> result = null;
try { try {
result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema); result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("反序列化对象列表发生异常!", e); throw new RuntimeException("反序列化对象列表发生异常!", e);
} }
return result; return result;
} }
} }

View File

@@ -1,80 +1,80 @@
package cn.celess.blog.util; package cn.celess.common.util;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/05/12 11:04 * @date : 2019/05/12 11:04
*/ */
public class RegexUtil { public class RegexUtil {
/** /**
* 网址匹配 * 网址匹配
* *
* @param url * @param url
* @return * @return
*/ */
public static boolean urlMatch(String url) { public static boolean urlMatch(String url) {
if (url == null || url.replaceAll(" ", "").isEmpty()) { if (url == null || url.replaceAll(" ", "").isEmpty()) {
return false; return false;
} }
//正则 http(s)://www.celess/xxxx,www.celess.cn/xxx //正则 http(s)://www.celess/xxxx,www.celess.cn/xxx
String pattern = "^(http://|https://|)([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$"; String pattern = "^(http://|https://|)([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$";
return match(url, pattern); return match(url, pattern);
} }
/** /**
* 邮箱验证 * 邮箱验证
* *
* @param email * @param email
* @return * @return
*/ */
public static boolean emailMatch(String email) { public static boolean emailMatch(String email) {
if (email == null || email.replaceAll(" ", "").isEmpty()) { if (email == null || email.replaceAll(" ", "").isEmpty()) {
return false; return false;
} }
//正则 //正则
String pattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$"; String pattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
return match(email, pattern); return match(email, pattern);
} }
/** /**
* 手机号匹配 * 手机号匹配
* *
* @param phone * @param phone
* @return * @return
*/ */
public static boolean phoneMatch(String phone) { public static boolean phoneMatch(String phone) {
if (phone == null || phone.replaceAll(" ", "").isEmpty()) { if (phone == null || phone.replaceAll(" ", "").isEmpty()) {
return false; return false;
} }
//正则 //正则
String pattern = "^([1][3,4,5,6,7,8,9])\\d{9}$"; String pattern = "^([1][3,4,5,6,7,8,9])\\d{9}$";
return match(phone, pattern); return match(phone, pattern);
} }
/** /**
* 密码正则 * 密码正则
* 最短6位最长16位 {6,16} * 最短6位最长16位 {6,16}
* 可以包含小写大母 [a-z] 和大写字母 [A-Z] * 可以包含小写大母 [a-z] 和大写字母 [A-Z]
* 可以包含数字 [0-9] * 可以包含数字 [0-9]
* 可以包含下划线 [ _ ] 和减号 [ - ] * 可以包含下划线 [ _ ] 和减号 [ - ]
* *
* @param pwd * @param pwd
* @return * @return
*/ */
public static boolean pwdMatch(String pwd) { public static boolean pwdMatch(String pwd) {
if (pwd == null || pwd.replaceAll(" ", "").isEmpty()) { if (pwd == null || pwd.replaceAll(" ", "").isEmpty()) {
return false; return false;
} }
//正则 //正则
String pattern = "^[\\w_-]{6,16}$"; String pattern = "^[\\w_-]{6,16}$";
return match(pwd, pattern); return match(pwd, pattern);
} }
private static boolean match(String str, String pattern) { private static boolean match(String str, String pattern) {
Pattern r = Pattern.compile(pattern); Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str); Matcher m = r.matcher(str);
return m.matches(); return m.matches();
} }
} }

View File

@@ -0,0 +1,42 @@
package cn.celess.common.util;
import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpServletRequest;
/**
* @author : xiaohai
* @date : 2019/03/28 17:21
*/
public class StringUtil {
/**
* 从html中提取纯文本
*
* @param html html string
* @return 纯文本
*/
public static String getString(String html) {
//剔出<html>的标签
String txtcontent = html.replaceAll("</?[^>]+>", "");
//去除字符串中的空格,回车,换行符,制表符
txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");
return txtcontent;
}
/**
* 生成MD5
*
* @param str 源数据
* @return md5 内容
*/
public static String getMD5(String str) {
return DigestUtils.md5DigestAsHex(str.getBytes());
}
public static String getCompleteUrlAndMethod(HttpServletRequest request) {
// like this : GET:/articles?page=1&count=5
return request.getMethod() + ":" + request.getRequestURI() +
(request.getQueryString() == null ? "" : "?" + request.getQueryString());
}
}

View File

@@ -1,90 +1,89 @@
package cn.celess.blog.util; package cn.celess.common.util;
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.util.Random; import java.util.Random;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/04/11 15:42 * @date : 2019/04/11 15:42
*/ */
public class VeriCodeUtil { public class VeriCodeUtil {
// 验证码字符集 // 验证码字符集
private static final char[] chars = { private static final char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
// 字符数量 // 字符数量
private static final int SIZE = 4; private static final int SIZE = 4;
// 干扰线数量 // 干扰线数量
private static final int LINES = 5; private static final int LINES = 5;
// 宽度 // 宽度
private static final int WIDTH = 80; private static final int WIDTH = 80;
// 高度 // 高度
private static final int HEIGHT = 40; private static final int HEIGHT = 40;
// 字体大小 // 字体大小
private static final int FONT_SIZE = 30; private static final int FONT_SIZE = 30;
/** /**
* 生成随机验证码及图片 * 生成随机验证码及图片
* Object[0]验证码字符串 * Object[0]验证码字符串
* Object[1]验证码图片 * Object[1]验证码图片
*/ */
public static Object[] createImage() { public static Object[] createImage() {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
// 1.创建空白图片 // 1.创建空白图片
BufferedImage image = new BufferedImage( BufferedImage image = new BufferedImage(
WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
// 2.获取图片画笔 // 2.获取图片画笔
Graphics graphic = image.getGraphics(); Graphics graphic = image.getGraphics();
// 3.设置画笔颜色 // 3.设置画笔颜色
graphic.setColor(Color.LIGHT_GRAY); graphic.setColor(Color.LIGHT_GRAY);
// 4.绘制矩形背景 // 4.绘制矩形背景
graphic.fillRect(0, 0, WIDTH, HEIGHT); graphic.fillRect(0, 0, WIDTH, HEIGHT);
// 5.画随机字符 // 5.画随机字符
Random ran = new Random(); Random ran = new Random();
for (int i = 0; i < SIZE; i++) { for (int i = 0; i < SIZE; i++) {
// 取随机字符索引 // 取随机字符索引
int n = ran.nextInt(chars.length); int n = ran.nextInt(chars.length);
// 设置随机颜色 // 设置随机颜色
graphic.setColor(getRandomColor()); graphic.setColor(getRandomColor());
// 设置字体大小 // 设置字体大小
graphic.setFont(new Font( graphic.setFont(new Font(
null, Font.BOLD + Font.ITALIC, FONT_SIZE)); null, Font.BOLD + Font.ITALIC, FONT_SIZE));
// 画字符 // 画字符
graphic.drawString( graphic.drawString(
chars[n] + "", i * WIDTH / SIZE, HEIGHT * 2 / 3); chars[n] + "", i * WIDTH / SIZE, HEIGHT * 2 / 3);
// 记录字符 // 记录字符
sb.append(chars[n]); sb.append(chars[n]);
} }
// 6.画干扰线 // 6.画干扰线
for (int i = 0; i < LINES; i++) { for (int i = 0; i < LINES; i++) {
// 设置随机颜色 // 设置随机颜色
graphic.setColor(getRandomColor()); graphic.setColor(getRandomColor());
// 随机画线 // 随机画线
graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT), graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT)); ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
} }
// 7.返回验证码和图片 // 7.返回验证码和图片
return new Object[]{sb.toString(), image}; return new Object[]{sb.toString(), image};
} }
/** /**
* 随机取色 * 随机取色
*/ */
public static Color getRandomColor() { public static Color getRandomColor() {
Random ran = new Random(); Random ran = new Random();
Color color = new Color(ran.nextInt(256), return new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256)); ran.nextInt(256), ran.nextInt(256));
return color; }
}
}
}

View File

@@ -0,0 +1,2 @@
org.springframework.boot.env.EnvironmentPostProcessor=cn.celess.common.config.CommonEnvPostProcessor
org.springframework.context.ApplicationListener=cn.celess.common.config.CommonEnvPostProcessor

Some files were not shown because too many files have changed in this diff Show More