Compare commits

..

209 Commits

Author SHA1 Message Date
禾几海
14c9a95a61 修复缺失依赖 2021-10-05 16:35:22 +08:00
dependabot[bot]
2d649b0373 build(deps): bump htmlunit from 2.45.0 to 2.53.0
Bumps [htmlunit](https://github.com/HtmlUnit/htmlunit) from 2.45.0 to 2.53.0.
- [Release notes](https://github.com/HtmlUnit/htmlunit/releases)
- [Commits](https://github.com/HtmlUnit/htmlunit/compare/2.45.0...2.53.0)

---
updated-dependencies:
- dependency-name: net.sourceforge.htmlunit:htmlunit
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-10-05 07:33:48 +00: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
禾几海
0ba7e06695 Merge pull request #12 from xiaohai2271/dependabot/maven/junit-junit-4.13.1
build(deps): bump junit from 4.12 to 4.13.1
2020-10-14 07:56:21 +08:00
dependabot[bot]
512d04f3e9 build(deps): bump junit from 4.12 to 4.13.1
Bumps [junit](https://github.com/junit-team/junit4) from 4.12 to 4.13.1.
- [Release notes](https://github.com/junit-team/junit4/releases)
- [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.12.md)
- [Commits](https://github.com/junit-team/junit4/compare/r4.12...r4.13.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-13 17:49:19 +00:00
禾几海
ada8f67171 Merge remote-tracking branch 'origin/master' 2020-10-09 18:57:42 +08:00
禾几海
6e12331e61 feat: 添加文件上传接口 2020-10-09 18:56:59 +08:00
禾几海
81ee71adf1 Create codeql-analysis.yml 2020-10-03 18:02:48 +08:00
禾几海
7e7332694e docs: typo 2020-09-07 12:28:07 +08:00
禾几海
8db690a55f Update issue templates 2020-09-07 12:23:44 +08:00
禾几海
0b40522e93 feat: 默认返回位置信息 2020-09-05 16:35:45 +08:00
禾几海
9026ba0732 refactor: 简化代码 2020-09-05 15:43:43 +08:00
禾几海
f5f2437fa4 refactor: 简化代码 2020-09-05 15:42:03 +08:00
禾几海
0bcca091e1 refactor: 简化代码 2020-09-04 13:02:36 +08:00
禾几海
3c69baa4ad Merge branch 'feature-ip2region' 2020-09-04 12:29:18 +08:00
禾几海
baf5b1bbb7 feat: 添加对jdk8以上环境的支持 2020-09-04 12:23:15 +08:00
禾几海
38621bcfa4 refactor: 换用ip2region 2020-09-04 12:11:14 +08:00
禾几海
cf435a588f refactor: 添加ip2region 2020-09-04 09:42:55 +08:00
禾几海
feab26f4f7 docs: add some badge 2020-09-01 08:30:26 +08:00
禾几海
578dbe6cc5 docs: api参数变化
- '/admin/articles' deleted 参数   可缺省
- '/admin/users'    status  参数
可缺省
- '/admin/links'    deleted 参数   可缺省
2020-08-31 13:14:37 +08:00
禾几海
f3b03f4853 ci: 调整webhook地址 2020-08-31 13:06:35 +08:00
禾几海
ee85b1f175 Merge pull request #11 from xiaohai2271/dev
分离不同状态的数据
2020-08-31 13:01:09 +08:00
禾几海
925e816f7a fix(login): 账户不存在时引发的空值异常 2020-08-31 12:47:19 +08:00
禾几海
a59bb7f231 feat(login): 非正常账户不可登录 2020-08-31 12:45:49 +08:00
禾几海
7f17c20e01 移除无效脚本 2020-08-31 10:34:34 +08:00
禾几海
6eabb3ab22 refactor: 精简代码 2020-08-31 10:10:21 +08:00
禾几海
72674f4612 test: 补单元测试 2020-08-31 10:02:12 +08:00
禾几海
9b460ff33c feat(link): 分离不同状态的数据 2020-08-31 09:46:15 +08:00
禾几海
a26946a583 feat: 反序列化 2020-08-31 01:10:12 +08:00
禾几海
01407aba7e feat: 分离不同状态的数据 2020-08-31 00:53:48 +08:00
禾几海
a54e04abf3 feat: 序列化 2020-08-31 00:51:01 +08:00
禾几海
450b4a40bd feat(user): 修改status字段类型 2020-08-31 00:17:21 +08:00
禾几海
9f883d12df feat(article): 修改参数 2020-08-30 23:45:18 +08:00
禾几海
c17b56b436 style: 修改部分代码格式 2020-08-30 14:17:34 +08:00
禾几海
b55a50d548 fix(test): 不合理的测试例 2020-08-30 14:01:19 +08:00
禾几海
4c9b193857 Merge branch 'dev' 2020-08-15 16:08:44 +08:00
禾几海
18a8c916c3 Update README.md 2020-08-15 16:07:41 +08:00
禾几海
99f2907621 Update README.md 2020-08-15 16:07:41 +08:00
禾几海
939b06d0a9 切换到jackson(#10)
切换到jackson
2020-08-15 16:05:39 +08:00
禾几海
a7f947a017 fix: 修复部分测试异常 2020-08-15 16:03:22 +08:00
禾几海
40e1f4d6ab fix: 空值异常 2020-08-15 16:00:05 +08:00
禾几海
6b77655c16 style: optimize imports 2020-08-15 15:44:34 +08:00
禾几海
7ff44fd73e Merge branch 'dev' into feature-trans2jackson 2020-08-15 15:33:04 +08:00
禾几海
c9f91bf2c1 fix(test):外键约束引发的异常,替换随机字符串的生成 2020-08-15 15:26:41 +08:00
禾几海
03fcddb971 fix(test):外键约束引发的异常,替换随机字符串的生成 2020-08-15 15:12:07 +08:00
禾几海
dc851e84a4 fix(test): 唯一索引引发的异常 2020-08-15 15:03:16 +08:00
禾几海
b34acee733 refactor: 修改当日剩余时间的计算方法 2020-08-15 15:00:07 +08:00
禾几海
d46dada23a refactor: 替换net.sf.json为fastJson 2020-08-15 14:59:45 +08:00
禾几海
47e5030f52 refactor: 替换net.sf.json为fastJson 2020-08-15 14:39:39 +08:00
禾几海
94c9fc1c46 refactor(Test): 将测试类中随机字符串的生成提到基类中 2020-08-15 12:16:39 +08:00
禾几海
bdcfaef5f8 refactor(Test): 重构 MultipleSubmitFilter 2020-08-15 12:13:08 +08:00
禾几海
3b6439c5cf refactor(Test): 重构 AuthorizationFilter 2020-08-15 12:10:48 +08:00
禾几海
938a051487 refactor(Test): 重构 WebUpdateInfoControllerTest 2020-08-15 12:01:41 +08:00
禾几海
a04b51a82e refactor(Test): 重构 VisitorControllerTest 2020-08-15 11:49:19 +08:00
禾几海
ee4c4bd87e Update README.md 2020-08-15 09:48:19 +08:00
禾几海
e70ad72523 Update README.md 2020-08-15 09:47:34 +08:00
禾几海
c466ddddea 重新配置集成测试(#9) 2020-08-15 02:39:45 +08:00
禾几海
7257f23ef6 refactor(ci): 重新配置ci 2020-08-15 02:27:40 +08:00
禾几海
7c96151830 fix(test): 修复后台服务未开启时测试不通过的情况 2020-08-14 21:37:17 +08:00
禾几海
5a47803611 fix(test): 修改内嵌redis的启动端口 2020-08-14 21:30:40 +08:00
禾几海
af9f243a83 refactor(ci): 重新配置ci 2020-08-14 21:19:53 +08:00
禾几海
3c8abc895a fix(mvnw): 重新生成mvnw 2020-08-14 21:06:14 +08:00
禾几海
9ffa293d24 refactor(Test): 修改上传文件到图床的实现方式 2020-08-14 17:58:08 +08:00
禾几海
d13ab4e522 add(Test): 测试的配置文件 2020-08-14 17:55:36 +08:00
禾几海
2fce2d8a1c refactor(Test): 内嵌redis 2020-08-14 17:17:36 +08:00
禾几海
6eb7d01875 style:修改sql格式 2020-08-14 17:17:35 +08:00
禾几海
aa751dbba1 refactor(Test):内嵌h2 2020-08-14 17:16:49 +08:00
禾几海
14ff60ecfc Update README.md 2020-08-10 16:43:50 +08:00
禾几海
5dae647885 Merge remote-tracking branch 'origin/master' 2020-08-10 16:40:12 +08:00
禾几海
bf2abd6072 Update README.md 2020-08-10 16:39:50 +08:00
禾几海
a62b395a8a Update LICENSE 2020-08-10 16:24:06 +08:00
禾几海
5059859ae4 Update README.md 2020-08-10 16:20:28 +08:00
禾几海
ecdbf8e21c Add Build document 2020-08-10 16:15:43 +08:00
禾几海
c69eee7027 Add api document 2020-08-10 15:59:30 +08:00
禾几海
8e8a7c809d 修复id异常 2020-08-04 22:25:20 +08:00
禾几海
c6a97e4c5b 外键约束 2020-08-04 22:01:02 +08:00
禾几海
d50cd93e55 移动sql位置,开启初始化数据库的设置 2020-08-04 21:47:46 +08:00
禾几海
e32600d892 Update README.md 2020-08-02 11:45:44 +08:00
禾几海
d473b5931b Update test.yml 2020-08-02 11:40:34 +08:00
禾几海
ab6f9d894d Rename deplay.yml to build.yml 2020-08-02 11:38:34 +08:00
禾几海
49ee7c73e2 空值异常 2020-08-01 23:56:10 +08:00
禾几海
4a65df2a7d Update deplay.yml 2020-08-01 21:46:17 +08:00
禾几海
b6c6cda4ae Merge pull request #7 from xiaohai2271/dev
最近的一些修改
2020-08-01 21:26:45 +08:00
禾几海
a9efb1c04d Merge pull request #6 from xiaohai2271/feature-#5
Feature #5  申请友链时自动抓取网页信息
2020-08-01 21:24:46 +08:00
禾几海
4ac430445d remove jacoco 2020-08-01 21:09:29 +08:00
禾几海
d6cede718b null值异常 2020-07-25 12:08:44 +08:00
禾几海
7922ea558f 调整UserController的测试类 2020-07-25 11:23:03 +08:00
禾几海
f65c96fa2d 调整TagController的测试类 2020-07-24 22:02:24 +08:00
禾几海
1bfd2d713e . 2020-07-24 21:08:49 +08:00
禾几海
ffed0d5cd0 调整LinkController的测试类 2020-07-24 21:08:40 +08:00
禾几海
b9094c1345 . 2020-07-24 20:24:34 +08:00
禾几海
e9209d1852 调整CommentController的测试类 2020-07-24 20:24:13 +08:00
禾几海
9900605e1a . 2020-07-24 20:06:59 +08:00
禾几海
883a78e872 调整CategoryController的测试类 2020-07-24 20:06:01 +08:00
禾几海
c7016dcf5f 修改getResponse的类型参数 2020-07-24 20:05:17 +08:00
禾几海
66b2b26b15 注销导致token无效的bug 2020-07-24 16:46:35 +08:00
禾几海
f1d3a79919 ... 2020-07-24 13:51:44 +08:00
禾几海
003f74f5f1 调整ArticleController的测试类 2020-07-24 13:49:18 +08:00
禾几海
2f6253c175 抽离json -> Response 对象的方法 2020-07-24 13:48:50 +08:00
禾几海
aa3ee5db72 ... 2020-07-24 00:46:46 +08:00
禾几海
d340ba8218 ... 2020-07-24 00:36:13 +08:00
禾几海
7be1c9dfb0 调整ArticleController的测试类 2020-07-24 00:22:40 +08:00
禾几海
b7f26cbfdb 调整测试基类 2020-07-24 00:21:55 +08:00
禾几海
de5e40e6b8 pr进行ci测试 2020-05-27 18:30:08 +08:00
禾几海
d1f08b58c0 Merge pull request #1 from xiaohai2271/dev
调整数据库字段,优化部分接口
2020-05-27 16:45:02 +08:00
禾几海
8b255372dd Merge remote-tracking branch 'origin/master' 2020-05-19 19:56:02 +08:00
小海
f88bf105a9 Update README.md 2020-05-19 19:55:26 +08:00
禾几海
0e26eab2e6 Merge branch 'dev' 2020-05-18 08:36:19 +08:00
小海
778c2dba58 Update README.md 2020-05-03 22:32:48 +08:00
226 changed files with 16289 additions and 10705 deletions

38
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

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

49
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,49 @@
name: Build
on:
push:
branches: [ master ]
paths-ignore:
- "doc/**"
- "**/README.md"
pull_request:
branches: [ master ]
paths-ignore:
- "doc/**"
- "**/README.md"
jobs:
build:
if: "!contains(github.event.head_commit.message, '[skip ci]')" # 如果 commit 信息包含以下关键字则跳过该任务
runs-on: ubuntu-latest
env:
KEY: ${{ secrets.WEB_HOOK_ACCESS_KEY }}
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Sync repository
uses: x-dr/sync-repo-to-gitee@v1.0
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
- name: Cache local Maven repository
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,47 +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: Deplay
on:
push:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
env:
APPLICATION_PROPERTIES_TEST: ${{ secrets.APPLICATION_PROPERTIES_TEST }}
APPLICATION_PROPERTIES_PROD: ${{ secrets.APPLICATION_PROPERTIES_PROD }}
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Build jar file
run: echo $APPLICATION_PROPERTIES_PROD|base64 -d> src/main/resources/application-prod.properties && mvn -B package --file pom.xml
- name: SCP
uses: appleboy/scp-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USERNAME }}
password: ${{ secrets.SSH_PASSWORD }}
port: ${{ secrets.SSH_PORT }}
source: "target/blog-0.0.1-SNAPSHOT.jar"
target: "/www/wwwroot/api.celess.cn"
- name: Run SSH command
uses: garygrossgarten/github-action-ssh@v0.5.0
with:
command: cd /www/wwwroot/api.celess.cn && bash build.sh
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USERNAME }}
password: ${{ secrets.SSH_PASSWORD }}
port: ${{ secrets.SSH_PORT }}

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: pr Test
on:
push:
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
env:
APPLICATION_PROPERTIES_TEST: ${{ secrets.APPLICATION_PROPERTIES_TEST }}
APPLICATION_PROPERTIES_PROD: ${{ secrets.APPLICATION_PROPERTIES_PROD }}
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Test
run: echo $APPLICATION_PROPERTIES_TEST|base64 -d > src/main/resources/application-test.properties && mvn -B test --file pom.xml

4
.gitignore vendored
View File

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

View File

@@ -1,11 +1,11 @@
/* /*
* Copyright 2012-2019 the original author or authors. * Copyright 2007-present the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* https://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
import java.nio.channels.*; import java.nio.channels.*;
@@ -21,12 +20,12 @@ import java.util.Properties;
public class MavenWrapperDownloader { public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.5"; private static final String WRAPPER_VERSION = "0.5.6";
/** /**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/ */
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/** /**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
@@ -55,7 +54,7 @@ public class MavenWrapperDownloader {
// wrapperUrl parameter. // wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL; String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) { if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null; FileInputStream mavenWrapperPropertyFileInputStream = null;
try { try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
@@ -66,7 +65,7 @@ public class MavenWrapperDownloader {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally { } finally {
try { try {
if (mavenWrapperPropertyFileInputStream != null) { if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close(); mavenWrapperPropertyFileInputStream.close();
} }
} catch (IOException e) { } catch (IOException e) {
@@ -77,8 +76,8 @@ public class MavenWrapperDownloader {
System.out.println("- Downloading from: " + url); System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) { if(!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) { if(!outputFile.getParentFile().mkdirs()) {
System.out.println( System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
} }

Binary file not shown.

View File

@@ -1,2 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.2/apache-maven-3.6.2-bin.zip distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

View File

@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2019 小 Copyright (c) 2020 禾几
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,11 +1,23 @@
# 小海博客后端管理系统 <h1 align="center">
![Build Staus](https://github.com/xiaohai2271/blog-backEnd/workflows/Blog%20backEnd%20CI/badge.svg?branch=master&event=push) ![coverage report](https://gitlab.com/xiaohai2271/blog-backEnd/badges/master/coverage.svg) ![GitHub](https://img.shields.io/github/license/xiaohai2271/blog-backEnd) [![Website](https://img.shields.io/website?up_message=%E5%B0%8F%E6%B5%B7%E5%8D%9A%E5%AE%A2&url=https%3A%2F%2Fwww.celess.cn)](https://www.celess.cn) 小海博客后端管理系统
## 基于Springboot的后端博客管理系统 </h1>
<div align="center">
基于Springboot的后端博客管理系统
[![Build](https://github.com/xiaohai2271/blog-backEnd/workflows/Build/badge.svg)](https://github.com/xiaohai2271/blog-backEnd)
[![Test](https://github.com/xiaohai2271/blog-backEnd/workflows/Test/badge.svg)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub tag (latest SemVer)](https://img.shields.io/github/v/tag/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub](https://img.shields.io/github/license/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub top language](https://img.shields.io/github/languages/top/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub commit activity](https://img.shields.io/github/commit-activity/m/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![GitHub last commit](https://img.shields.io/github/last-commit/xiaohai2271/blog-backEnd)](https://github.com/xiaohai2271/blog-backEnd)
[![Website](https://img.shields.io/website?up_message=%E5%B0%8F%E6%B5%B7%E5%8D%9A%E5%AE%A2&url=https%3A%2F%2Fwww.celess.cn)](https://www.celess.cn)
</div>
### 主要使用的技术 > 请配合前端项目一起食用 [https://github.com/xiaohai2271/blog-frontEnd](https://github.com/xiaohai2271/blog-frontEnd)
## 🎈主要使用的技术
| 使用的技术 | 名称 | 版本 | | 使用的技术 | 名称 | 版本 |
| :--------------: | :--------: | :-----------: | | :--------------: | :--------: | :-----------: |
@@ -18,18 +30,16 @@
| 接口文档 | Swagger | 2.6.1 | | 接口文档 | Swagger | 2.6.1 |
| 数据库连接池 | druid | 1.1.14 | | 数据库连接池 | druid | 1.1.14 |
| 缓存(线上环境) | redis | 3.0.6 | | 缓存(线上环境) | redis | 3.0.6 |
|数据库|mysql|5.7| | 数据库 |mysql |5.7 |
### 接口文档 ## 🔨如何构建
详情参照[Build](./doc/Build.md)文档
项目采用swagger2接口文档自动生成具体为 http://ip:端口/swagger-ui.html
### 📝TODO ## 📒接口文档
项目采用swagger2接口文档自动生成具体为 http://ip:port/doc.html
- [x] 密码重置 或者参照[离线API文档](./doc/API.md)
- [x] 信息修改
- [ ] 接入qq登录
### 📌FIXME ## ☀授权协议
[MIT](./LICENSE)
- [ ] `/write` 图片上传的跨域问题

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

View File

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

@@ -0,0 +1,303 @@
package cn.celess.article.controller;
import cn.celess.article.ArticleBaseTest;
import cn.celess.common.entity.Article;
import cn.celess.common.entity.Response;
import cn.celess.common.entity.Tag;
import cn.celess.common.entity.dto.ArticleReq;
import cn.celess.common.entity.vo.ArticleModel;
import cn.celess.common.entity.vo.PageData;
import cn.celess.common.mapper.ArticleMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Test;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import javax.annotation.Resource;
import java.util.List;
import static cn.celess.common.constant.ResponseEnum.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
public class ArticleControllerTest extends ArticleBaseTest {
@Resource
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>>>() {
};
@Test
public void create() {
ArticleReq articleReq = new ArticleReq();
// 应该正常通过
articleReq.setTitle("test-" + randomStr());
articleReq.setMdContent("# test title");
articleReq.setCategory("随笔");
String[] tagList = {"tag", "category"};
articleReq.setTags(tagList);
articleReq.setOpen(true);
articleReq.setType(true);
articleReq.setUrl("http://xxxx.com");
MockHttpServletRequestBuilder post = post("/admin/article/create");
try {
getMockData(post, adminLogin(), articleReq).andDo(result -> {
Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult());
ArticleModel articleModel = response.getResult();
assertNotNull(articleModel.getId());
assertNotNull(articleModel.getTitle());
assertNotNull(articleModel.getSummary());
assertNotNull(articleModel.getOriginal());
assertNotNull(articleModel.getTags());
assertNotNull(articleModel.getCategory());
assertNotNull(articleModel.getPublishDateFormat());
assertNotNull(articleModel.getMdContent());
assertNotNull(articleModel.getPreArticle());
assertNull(articleModel.getNextArticle());
assertNotNull(articleModel.getOpen());
assertNotNull(articleModel.getReadingNumber());
assertNotNull(articleModel.getAuthor());
assertNotNull(articleModel.getUrl());
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void delete() {
Article article;
do {
article = articleMapper.getLastestArticle();
create();
} while (article.isDeleted());
assertFalse(article.isDeleted());
MockHttpServletRequestBuilder delete = MockMvcRequestBuilders.delete("/admin/article/del?articleID=" + article.getId());
try {
Article finalArticle = article;
getMockData(delete, adminLogin()).andDo(result -> {
Response<Boolean> response = getResponse(result, BOOLEAN_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
// 断言删除成功
assertTrue(response.getResult());
assertTrue(articleMapper.isDeletedById(finalArticle.getId()));
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void update() {
Article article = articleMapper.getLastestArticle();
ArticleReq articleReq = new ArticleReq();
articleReq.setId(article.getId());
articleReq.setUrl("http://www.test.test");
articleReq.setType(!article.getType());
articleReq.setCategory("test");
articleReq.setMdContent("test-" + article.getMdContent());
articleReq.setOpen(!article.getOpen());
String tag1 = randomStr(4);
String tag2 = randomStr(4);
String[] tagList = {"test", tag1, tag2};
articleReq.setTags(tagList);
articleReq.setTitle("test-" + article.getTitle());
try {
getMockData(put("/admin/article/update"), adminLogin(), articleReq).andDo(result -> {
Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
ArticleModel a = response.getResult();
assertEquals(articleReq.getCategory(), a.getCategory());
assertEquals(articleReq.getUrl(), a.getUrl());
assertEquals(articleReq.getMdContent(), a.getMdContent());
assertEquals(articleReq.getTitle(), a.getTitle());
assertEquals(articleReq.getType(), a.getOriginal());
// Tag
List<Tag> asList = a.getTags();
assertEquals(3, asList.size());
assertEquals(articleReq.getOpen(), a.getOpen());
assertEquals(articleReq.getId(), a.getId());
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void retrieveOneById() {
try {
long articleID = 3;
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/" + articleID + "?update=false")).andDo(result -> {
Response<ArticleModel> response = getResponse(result, ARTICLE_MODEL_TYPE);
// 断言获取数据成功
assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult());
ArticleModel a = response.getResult();
assertNotNull(a.getTitle());
assertNotNull(a.getId());
assertNotNull(a.getSummary());
assertNotNull(a.getMdContent());
assertNotNull(a.getUrl());
assertNotNull(a.getUpdateDateFormat());
assertTrue(a.getPreArticle() != null || a.getNextArticle() != null);
assertNotNull(a.getReadingNumber());
assertNotNull(a.getOriginal());
assertNotNull(a.getPublishDateFormat());
assertNotNull(a.getCategory());
assertNotNull(a.getTags());
assertNotNull(a.getAuthor());
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void articles() {
try {
// 测试不带参数访问
getMockData(MockMvcRequestBuilders.get("/articles"));
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());
// 结果集非空
assertNotNull(response.getResult());
// 判断pageInfo是否包装完全
PageData<ArticleModel> pageData = response.getResult();
assertNotEquals(0, pageData.getTotal());
assertEquals(1, pageData.getPageNum());
assertEquals(5, pageData.getPageSize());
// 内容完整
for (ArticleModel a : pageData.getList()) {
assertNotNull(a.getTitle());
assertNotNull(a.getId());
assertNotNull(a.getSummary());
assertNotNull(a.getOriginal());
assertNotNull(a.getPublishDateFormat());
assertNotNull(a.getCategory());
assertNotNull(a.getTags());
assertNotNull(a.getAuthor());
assertNull(a.getOpen());
assertNull(a.getMdContent());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void adminArticles() {
try {
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=5"), userLogin()).andDo(result ->
assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, ARTICLE_MODEL_PAGE_TYPE).getCode())
);
for (int i = 0; i < 2; i++) {
// admin权限登陆
int finalI = i;
getMockData(get("/admin/articles?page=1&count=5&deleted=" + (i == 1)), adminLogin()).andDo(result -> {
Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult());
// 判断pageInfo是否包装完全
PageData<ArticleModel> pageData = response.getResult();
assertNotEquals(0, pageData.getTotal());
assertEquals(1, pageData.getPageNum());
assertEquals(5, pageData.getPageSize());
// 内容完整
for (ArticleModel a : pageData.getList()) {
assertNotNull(a.getTitle());
assertNotNull(a.getId());
assertNotNull(a.getOriginal());
assertNotNull(a.getPublishDateFormat());
assertNotNull(a.getOpen());
assertNotNull(a.getReadingNumber());
assertNotNull(a.getLikeCount());
assertNotNull(a.getDislikeCount());
assertEquals((finalI == 1), a.isDeleted());
assertNull(a.getMdContent());
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void findByCategory() {
try {
// 分类不存在
String categoryName = "NoSuchCategory";
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"))
.andDo(result -> {
Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
PageData<ArticleModel> pageData = response.getResult();
assertNotEquals(0, pageData.getTotal());
assertEquals(1, pageData.getPageNum());
assertEquals(10, pageData.getPageSize());
for (ArticleModel arc : pageData.getList()) {
assertNotEquals(0, arc.getId().longValue());
assertNotNull(arc.getTitle());
assertNotNull(arc.getSummary());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void findByTag() {
try {
// 分类不存在
String tagName = "NoSuchTag";
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"))
.andDo(result -> {
Response<PageData<ArticleModel>> response = getResponse(result, ARTICLE_MODEL_PAGE_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
PageData<ArticleModel> pageData = response.getResult();
assertNotEquals(0, pageData.getTotal());
assertEquals(1, pageData.getPageNum());
assertEquals(10, pageData.getPageSize());
for (ArticleModel arc : pageData.getList()) {
assertNotEquals(0, arc.getId().longValue());
assertNotNull(arc.getTitle());
assertNotNull(arc.getSummary());
}
});
} 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,58 +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 net.sf.json.JSONObject; 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.List; import java.util.List;
import java.util.Map;
/**
* @author : xiaohai /**
* @date : 2019/03/30 20:36 * @author : xiaohai
*/ * @date : 2019/03/30 20:36
@RestController */
public class TagController { @RestController
@Autowired public class TagController {
TagService tagService; @Autowired
TagService tagService;
@PostMapping("/admin/tag/create")
public Response addOne(@RequestParam("name") String name) { @PostMapping("/admin/tag/create")
return Response.success(tagService.create(name)); public Response addOne(@RequestParam("name") String name) {
} return Response.success(tagService.create(name));
}
@DeleteMapping("/admin/tag/del")
public Response delOne(@RequestParam("id") long id) { @DeleteMapping("/admin/tag/del")
return Response.success(tagService.delete(id)); public Response delOne(@RequestParam("id") long id) {
} return Response.success(tagService.delete(id));
}
@PutMapping("/admin/tag/update")
public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) { @PutMapping("/admin/tag/update")
return Response.success(tagService.update(id, name)); public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) {
} return Response.success(tagService.update(id, name));
}
@GetMapping("/tags")
public Response getPage(@RequestParam(required = false, defaultValue = "10", value = "count") int count, @GetMapping("/tags")
@RequestParam(required = false, defaultValue = "1", value = "page") int page) { public Response getPage(@RequestParam(required = false, defaultValue = "10", value = "count") int count,
return Response.success(tagService.retrievePage(page, count)); @RequestParam(required = false, defaultValue = "1", value = "page") int page) {
} return Response.success(tagService.retrievePage(page, count));
}
@GetMapping("/tags/nac")
public Response getTagNameAndCount() { @GetMapping("/tags/nac")
List<JSONObject> nameAndCount = new ArrayList<>(); public Response getTagNameAndCount() {
List<TagModel> all = tagService.findAll(); List<Map<String, Object>> nameAndCount = new ArrayList<>();
for (TagModel t : all) { List<TagModel> all = tagService.findAll();
JSONObject jsonObject = new JSONObject(); for (TagModel t : all) {
jsonObject.put("name", t.getName()); Map<String, Object> map = new HashMap<>(2);
jsonObject.put("size", t.getArticles().size()); map.put("name", t.getName());
nameAndCount.add(jsonObject); map.put("size", t.getArticles().size());
} nameAndCount.add(map);
return Response.success(nameAndCount); }
} return Response.success(nameAndCount);
}
}
}

View File

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

View File

@@ -1,100 +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;
/**
* @author : xiaohai /**
* @date : 2019/03/28 22:29 * @author : xiaohai
*/ * @date : 2019/03/28 22:29
@Service */
public class TagServiceImpl implements TagService { @Service
@Autowired public class TagServiceImpl implements TagService {
TagMapper tagMapper; @Autowired
@Autowired TagMapper tagMapper;
HttpServletRequest request; @Autowired
@Autowired HttpServletRequest request;
ArticleMapper articleMapper; @Autowired
@Autowired ArticleMapper articleMapper;
ArticleTagMapper articleTagMapper; @Autowired
ArticleTagMapper articleTagMapper;
@Override
public TagModel create(String name) { @Override
boolean b = tagMapper.existsByName(name); public TagModel create(String name) {
if (b) { boolean b = tagMapper.existsByName(name);
throw new MyException(ResponseEnum.TAG_HAS_EXIST); if (b) {
} throw new BlogResponseException(ResponseEnum.TAG_HAS_EXIST);
Tag tag = new Tag(); }
tag.setName(name); Tag tag = new Tag();
tagMapper.insert(tag); tag.setName(name);
return ModalTrans.tag(tag); tagMapper.insert(tag);
} return ModalTrans.tag(tag);
}
@Override
@Transactional(rollbackFor = Exception.class) @Override
public boolean delete(long tagId) { @Transactional(rollbackFor = Exception.class)
Tag tag = tagMapper.findTagById(tagId); public boolean delete(long tagId) {
if (tag == null) { Tag tag = tagMapper.findTagById(tagId);
throw new MyException(ResponseEnum.TAG_NOT_EXIST); if (tag == null) {
} 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())); // 删除文章
return tagMapper.delete(tagId) == 1; articleByTag.forEach(articleTag -> articleMapper.delete(articleTag.getArticle().getId()));
} return tagMapper.delete(tagId) == 1;
}
@Override
public TagModel update(Long id, String name) { @Override
if (id == null) { public TagModel update(Long id, String name) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID"); if (id == null) {
} throw new BlogResponseException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID");
Tag tag = tagMapper.findTagById(id); }
tag.setName(name); Tag tag = tagMapper.findTagById(id);
tagMapper.update(tag); tag.setName(name);
return ModalTrans.tag(tag); tagMapper.update(tag);
return ModalTrans.tag(tag);
}
}
@Override
public PageData<TagModel> retrievePage(int page, int count) { @Override
PageHelper.startPage(page, count); public PageData<TagModel> retrievePage(int page, int count) {
List<Tag> tagList = tagMapper.findAll(); PageHelper.startPage(page, count);
List<TagModel> modelList = new ArrayList<>(); List<Tag> tagList = tagMapper.findAll();
tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag))); List<TagModel> modelList = new ArrayList<>();
return new PageData<TagModel>(new PageInfo<Tag>(tagList), modelList); tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag)));
} return new PageData<>(new PageInfo<>(tagList), modelList);
}
@Override
public List<TagModel> findAll() { @Override
List<TagModel> list = new ArrayList<>(); public List<TagModel> findAll() {
tagMapper.findAll().forEach(e -> { return tagMapper.findAll().stream()
TagModel model = ModalTrans.tag(e); .map(ModalTrans::tag)
List<ArticleTag> articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(e.getId()); .peek(tagModel -> {
List<ArticleModel> articleModelList = new ArrayList<>(); List<ArticleTag> articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(tagModel.getId());
articleByTagAndOpen.forEach(articleTag -> articleModelList.add(ModalTrans.article(articleTag.getArticle(), true))); tagModel.setArticles(
model.setArticles(articleModelList); articleByTagAndOpen
list.add(model); .stream()
}); .map(articleTag -> ModalTrans.article(articleTag.getArticle(), true))
return list; .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

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

View File

@@ -0,0 +1,111 @@
package cn.celess.categorytag.controller;
import cn.celess.categorytag.CategoryTagBaseTest;
import cn.celess.common.entity.Response;
import cn.celess.common.entity.Tag;
import cn.celess.common.entity.vo.PageData;
import cn.celess.common.entity.vo.TagModel;
import cn.celess.common.mapper.TagMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Map;
import static cn.celess.common.constant.ResponseEnum.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
public class TagControllerTest extends CategoryTagBaseTest {
@Autowired
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_NAC_LIST_TYPE = new TypeReference<Response<List<Map<String, Object>>>>() {
};
@Test
public void addOne() throws Exception {
String name = randomStr(4);
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), userLogin()).andDo(result -> assertEquals(PERMISSION_ERROR.getCode(), getResponse(result, STRING_TYPE).getCode()));
getMockData(post("/admin/tag/create?name=" + name), adminLogin()).andDo(result -> {
Response<TagModel> response = getResponse(result, TAG_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
TagModel tag = response.getResult();
assertNotNull(tag.getId());
assertEquals(name, tag.getName());
});
}
@Test
public void delOne() throws Exception {
Tag lastestTag = tagMapper.getLastestTag();
assertNotNull(lastestTag.getId());
getMockData(delete("/admin/tag/del?id=" + lastestTag.getId()), adminLogin()).andDo(result -> {
Response<Boolean> response = getResponse(result, BOOLEAN_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
assertTrue(response.getResult());
});
long id = lastestTag.getId() * 2;
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 {
Tag tag = tagMapper.getLastestTag();
assertNotNull(tag.getId());
String name = randomStr(4);
getMockData(put("/admin/tag/update?id=" + tag.getId() + "&name=" + name), adminLogin()).andDo(result -> {
Response<TagModel> response = getResponse(result, TAG_MODEL_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult());
TagModel t = response.getResult();
assertEquals(name, t.getName());
assertEquals(tag.getId(), t.getId());
});
}
@Test
public void getPage() throws Exception {
getMockData(get("/tags?page=1&count=5")).andDo(result -> {
Response<PageData<TagModel>> response = getResponse(result, TAG_MODEL_PAGE_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
// 结果集非空
assertNotNull(response.getResult());
// 判断pageInfo是否包装完全
PageData<TagModel> pageData = response.getResult();
assertNotEquals(0, pageData.getTotal());
assertEquals(1, pageData.getPageNum());
assertEquals(5, pageData.getPageSize());
// 内容完整
for (TagModel t : pageData.getList()) {
assertNotNull(t.getId());
assertNotNull(t.getName());
}
});
}
@Test
public void getTagNameAndCount() throws Exception {
getMockData(get("/tags/nac")).andDo(result -> {
Response<List<Map<String, Object>>> response = getResponse(result, TAG_NAC_LIST_TYPE);
assertEquals(SUCCESS.getCode(), response.getCode());
assertNotNull(response.getResult());
response.getResult().forEach(o -> {
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,158 +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;
/** /**
* @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 MyException(ResponseEnum.PARAMETERS_ERROR); throw new BlogResponseException(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 MyException(ResponseEnum.PARAMETERS_ERROR); throw new BlogResponseException(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(-1L); 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 MyException(ResponseEnum.COMMENT_NOT_EXIST); throw new BlogResponseException(ResponseEnum.COMMENT_NOT_EXIST);
} }
if (b.getStatus() == CommentStatusEnum.DELETED.getCode()) { if (b.getStatus() == CommentStatusEnum.DELETED.getCode()) {
throw new MyException(ResponseEnum.DATA_IS_DELETED); throw new BlogResponseException(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 MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空"); throw new BlogResponseException(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);
List<CommentModel> commentModels = new ArrayList<>(); return allByPagePath
allByPagePath.forEach(comment -> { .stream()
if (comment.getStatus() != CommentStatusEnum.DELETED.getCode()) { .filter(comment -> comment.getStatus() != CommentStatusEnum.DELETED.getCode())
commentModels.add(ModalTrans.comment(comment)); .map(ModalTrans::comment)
} .collect(Collectors.toList());
}); }
return commentModels; @Override
} public PageData<CommentModel> retrievePageByAuthor(String pagePath, int page, int count) {
User user = redisUserUtil.get();
@Override PageHelper.startPage(page, count);
public PageData<CommentModel> retrievePageByAuthor(String pagePath, int page, int count) { List<Comment> list = commentMapper.findAllByPagePathAndFromUser(pagePath, user.getId());
User user = redisUserUtil.get(); return pageTrans(list);
PageHelper.startPage(page, count); }
List<Comment> list = commentMapper.findAllByPagePathAndFromUser(pagePath, user.getId());
return pageTrans(list); @Override
} public PageData<CommentModel> retrievePageByPageAndPid(String pagePath, long pid, int page, int count) {
PageHelper.startPage(page, count);
@Override List<Comment> list = commentMapper.findAllByPagePath(pagePath);
public PageData<CommentModel> retrievePageByPageAndPid(String pagePath, long pid, int page, int count) { return pageTrans(list, true);
PageHelper.startPage(page, count); }
List<Comment> list = commentMapper.findAllByPagePath(pagePath);
return pageTrans(list, true); @Override
} public PageData<CommentModel> retrievePageByPage(String pagePath, int page, int count) {
PageHelper.startPage(page, count);
@Override List<Comment> list = commentMapper.findAllByPagePath(pagePath);
public PageData<CommentModel> retrievePageByPage(String pagePath, int page, int count) { return pageTrans(list, true);
PageHelper.startPage(page, count); }
List<Comment> list = commentMapper.findAllByPagePath(pagePath);
return pageTrans(list, true); private PageData<CommentModel> pageTrans(List<Comment> commentList) {
} return pageTrans(commentList, false);
}
private PageData<CommentModel> pageTrans(List<Comment> commentList) {
return pageTrans(commentList, false); private PageData<CommentModel> pageTrans(List<Comment> commentList, boolean noResponseList) {
} PageInfo<Comment> p = PageInfo.of(commentList);
List<CommentModel> modelList = commentList
private PageData<CommentModel> pageTrans(List<Comment> commentList, boolean noResponseList) { .stream()
PageInfo<Comment> p = PageInfo.of(commentList); .map(ModalTrans::comment)
List<CommentModel> modelList = new ArrayList<>(); .peek(commentModel -> commentModel.setRespComment(this.retrievePageByPid(commentModel.getId())))
commentList.forEach(l -> { .collect(Collectors.toList());
CommentModel model = ModalTrans.comment(l); return new PageData<>(p, modelList);
if (!noResponseList) { }
model.setRespComment(this.retrievePageByPid(model.getId())); }
}
modelList.add(model);
});
return new PageData<CommentModel>(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

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

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

@@ -0,0 +1,116 @@
<?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.3.0</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>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.53.0</version>
</dependency>
<!-- protostuff序列化依赖 -->
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.1.6</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,93 +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, "账户已注销"),
PWD_WRONG(3800, "密码不正确"), CAN_NOT_USE(3711, "账户不可用"),
PWD_WRONG(3800, "密码不正确"),
JWT_EXPIRED(3810, "Token过期"),
JWT_MALFORMED(3820, "Token格式不对"), JWT_EXPIRED(3810, "Token过期"),
JWT_SIGNATURE(3830, "Token签名错误"), JWT_MALFORMED(3820, "Token格式不对"),
JWT_NOT_SUPPORT(3840, "不支持的Token"), JWT_SIGNATURE(3830, "Token签名错误"),
JWT_NOT_SUPPORT(3840, "不支持的Token"),
//标签
TAG_NOT_EXIST(4010, "标签不存在"), //标签
TAG_HAS_EXIST(4020, "标签存在"), TAG_NOT_EXIST(4010, "标签存在"),
TAG_HAS_EXIST(4020, "标签已存在"),
//分类
CATEGORY_NOT_EXIST(5010, "分类不存在"), //分类
CATEGORY_HAS_EXIST(5020, "分类存在"), CATEGORY_NOT_EXIST(5010, "分类存在"),
CATEGORY_HAS_EXIST(5020, "分类已存在"),
//评论/留言
COMMENT_NOT_EXIST(6010, "评论/留言不存在"), //评论/留言
COMMENT_HAS_EXIST(6020, "评论/留言存在,请不要重复提交"), COMMENT_NOT_EXIST(6010, "评论/留言存在"),
COMMENT_HAS_EXIST(6020, "评论/留言已存在,请不要重复提交"),
//webUdpateInfo amd PartnerSite
DATA_NOT_EXIST(7010, "数据不存在"), //webUdpateInfo amd PartnerSite
DATA_HAS_EXIST(7020, "数据存在"), DATA_NOT_EXIST(7010, "数据存在"),
DATA_HAS_EXIST(7020, "数据已存在"),
//其他
APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"), //其他
DATA_EXPIRED(7300, "数据过期"), APPLY_LINK_NO_ADD_THIS_SITE(7200, "暂未在您的网站中抓取到本站链接"),
CANNOT_GET_DATA(7400, "暂无法获取到数据"), DATA_EXPIRED(7300, "数据过期"),
CANNOT_GET_DATA(7400, "暂无法获取到数据"),
//提交更新之前没有获取数据/, NO_FILE(7500, "未选择文件,请重新选择"),
DID_NOT_GET_THE_DATA(8020, "非法访问"),
IMG_CODE_TIMEOUT(8100, "验证码已失效"),
IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"), //提交更新之前没有获取数据/,
VERIFY_ERROR(8300, "验证失败"), DID_NOT_GET_THE_DATA(8020, "非法访问"),
PARAMETERS_ERROR(8500, "参数错误"), IMG_CODE_TIMEOUT(8100, "验证码已失效"),
PARAMETERS_URL_ERROR(8510, "链接格式错误"), IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"),
PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"), VERIFY_ERROR(8300, "验证失败"),
PARAMETERS_PHONE_ERROR(8530, "手机格式错误"), PARAMETERS_ERROR(8500, "参数错误"),
PARAMETERS_QQ_ERROR(8540, "QQ格式错误"), PARAMETERS_URL_ERROR(8510, "链接格式错误"),
PARAMETERS_PWD_ERROR(8550, "密码格式错误"), PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"),
VERIFY_OUT(8400, "已经验证过了"); PARAMETERS_PHONE_ERROR(8530, "手机格式错误"),
private final int code; PARAMETERS_QQ_ERROR(8540, "QQ格式错误"),
private final String msg; PARAMETERS_PWD_ERROR(8550, "密码格式错误"),
VERIFY_OUT(8400, "已经验证过了");
private final int code;
ResponseEnum(int code, String msg) { private final String msg;
this.code = code;
this.msg = msg;
} ResponseEnum(int code, String msg) {
this.code = code;
public int getCode() { this.msg = msg;
return code; }
}
public int getCode() {
public String getMsg() { return code;
return msg; }
}
} public String getMsg() {
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

@@ -0,0 +1,72 @@
package cn.celess.common.constant;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: 小海
* @Date: 2020-05-22 21:32
* @Desc:
*/
public enum UserAccountStatusEnum {
/**
* 账户正常
*/
NORMAL(0, "正常"),
/**
* 账户被锁定
*/
LOCKED(1, "锁定"),
/**
* 账户被删除
*/
DELETED(2, "已删除");
private final int code;
private final String desc;
UserAccountStatusEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static UserAccountStatusEnum get(int code) {
for (UserAccountStatusEnum value : UserAccountStatusEnum.values()) {
if (value.code == code) {
return value;
}
}
return null;
}
@JsonCreator
public static UserAccountStatusEnum get(Map<String, Object> map) {
for (UserAccountStatusEnum value : UserAccountStatusEnum.values()) {
if (value.code == (int) map.get("code") && value.desc.equals(map.get("desc"))) {
return value;
}
}
return null;
}
@JsonValue
public Map<String, Object> toJson() {
Map<String, Object> map = new HashMap<>(2);
map.put("code", code);
map.put("desc", desc);
return map;
}
}

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,64 +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 lombok.Data; import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONObject; import lombok.Data;
import lombok.SneakyThrows;
import java.io.Serializable;
import java.io.Serializable;
/**
* @author : xiaohai /**
* @date : 2019/03/28 15:24 * @author : xiaohai
*/ * @date : 2019/03/28 15:24
@Data */
public class Response<T> implements Serializable { @Data
private int code; public class Response<T> implements Serializable {
private String msg; private int code;
private T result; private String msg;
private T result;
public Response() {
} public Response() {
}
public Response(int code, String msg, T result) {
this.code = code; public Response(int code, String msg, T result) {
this.msg = msg; this.code = code;
this.result = result; this.msg = msg;
} this.result = result;
}
/**
* 成功相应 /**
* * 成功相应
* @param result 结果 *
* @return Response * @param result 结果
*/ * @return Response
public static Response success(Object result) { */
return new Response(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result); public static <T> Response<T> success(T result) {
} return new Response<T>(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result);
}
/**
* 失败的响应 /**
* * 失败的响应
* @param result 结果 *
* @return Response * @param result 结果
*/ * @return Response
public static Response failure(String result) { */
return new Response(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result); public static Response<String> failure(String result) {
} return new Response<String>(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result);
}
/**
* 其他的响应 /**
* * 其他的响应
* @param r 枚举常量 *
* @param result 结果 * @param r 枚举常量
* @return Response * @param result 结果
*/ * @return Response
public static Response response(ResponseEnum r, String result) { */
return new Response(r.getCode(), r.getMsg(), result); public static <T> Response<T> response(ResponseEnum r, T result) {
} return new Response<T>(r.getCode(), r.getMsg(), result);
}
@Override
public String toString() { @SneakyThrows
JSONObject jsonObject = JSONObject.fromObject(this); @Override
return jsonObject.toString(); public String toString() {
} 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,19 +1,25 @@
package cn.celess.blog.entity.request; package cn.celess.common.entity.dto;
import lombok.Data; import lombok.AllArgsConstructor;
import lombok.Data;
/** import lombok.NoArgsConstructor;
* @author : xiaohai
* @date : 2019/06/01 22:47 import java.io.Serializable;
*/
@Data /**
public class LoginReq { * @author : xiaohai
private String email; * @date : 2019/06/01 22:47
private String password; */
/** @Data
* isRememberMe默认为false @NoArgsConstructor
*/ @AllArgsConstructor
private Boolean isRememberMe = false; public class LoginReq implements Serializable {
private String email;
} private String password;
/**
* 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

@@ -1,13 +1,15 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
/** import java.io.Serializable;
* @author : xiaohai
* @date : 2019/04/21 22:43 /**
*/ * @author : xiaohai
public class QiniuResponse { * @date : 2019/04/21 22:43
public String key; */
public String hash; public class QiniuResponse implements Serializable {
public String bucket; public String key;
public long fsize; 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,42 +1,45 @@
package cn.celess.blog.entity.model; package cn.celess.common.entity.vo;
import lombok.Getter; import cn.celess.common.constant.UserAccountStatusEnum;
import lombok.Setter; import lombok.Getter;
import lombok.Setter;
/**
* @author : xiaohai import java.io.Serializable;
* @date : 2019/04/22 23:13
*/ /**
@Getter * @author : xiaohai
@Setter * @date : 2019/04/22 23:13
public class UserModel { */
@Getter
private Long id; @Setter
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 int 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,95 +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.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/03/28 17:02 * @date : 2019/03/28 17:02
*/ */
@ControllerAdvice @ControllerAdvice
public class ExceptionHandle { public class BlogExceptionHandler {
public static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); public static final Logger logger = LoggerFactory.getLogger(BlogExceptionHandler.class);
@Autowired @Autowired
MailService mailService; MailService mailService;
@Autowired @Autowired
HttpServletRequest request; HttpServletRequest request;
@Value("${spring.profiles.active}")
private String activeModel; @ExceptionHandler(value = Exception.class)
@ResponseBody
@ExceptionHandler(value = Exception.class) public Response handle(Exception e) {
@ResponseBody //自定义错误
public Response handle(Exception e) { if (e instanceof BlogResponseException) {
//自定义错误 BlogResponseException exception = (BlogResponseException) e;
if (e instanceof MyException) { logger.debug("返回了自定义的exception,[code={},msg={},result={}]", exception.getCode(), e.getMessage(), exception.getResult());
MyException exception = (MyException) e; return new Response(exception.getCode(), e.getMessage(), exception.getResult());
logger.debug("返回了自定义的exception,[code={},msg={},result={}]", exception.getCode(), e.getMessage(), exception.getResult()); }
return new Response(exception.getCode(), e.getMessage(), exception.getResult()); //请求路径不支持该方法
} if (e instanceof HttpRequestMethodNotSupportedException) {
//请求路径不支持该方法 logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={}path:{},method:{}]", e.getMessage(), request.getRequestURL(), request.getMethod());
if (e instanceof HttpRequestMethodNotSupportedException) { return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null);
logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={}path:{},method:{}]", e.getMessage(), request.getRequestURL(), request.getMethod()); }
return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null); //数据输入类型不匹配
} if (e instanceof MethodArgumentTypeMismatchException) {
//数据输入类型不匹配 logger.debug("输入类型不匹配,[msg={}]", e.getMessage());
if (e instanceof MethodArgumentTypeMismatchException) { return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null);
logger.debug("输入类型不匹配,[msg={}]", e.getMessage()); }
return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null); //数据验证失败
} if (e instanceof BindException) {
//数据验证失败 logger.debug("数据验证失败,[msg={}]", e.getMessage());
if (e instanceof BindException) { return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null);
logger.debug("数据验证失败,[msg={}]", e.getMessage()); }
return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null); //数据输入不完整
} if (e instanceof MissingServletRequestParameterException) {
//数据输入不完整 logger.debug("数据输入不完整,[msg={}]", e.getMessage());
if (e instanceof MissingServletRequestParameterException) { return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null);
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 ("prod".equals(activeModel)) { sendMessage(e);
logger.debug("有一个未捕获的bug已发送到邮箱"); }
sendMessage(e); e.printStackTrace();
} return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null);
e.printStackTrace(); }
return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null);
} /**
* 发送错误信息
/** *
* 发送错误信息 * @param e 错误
* */
* @param e 错误 private void sendMessage(Exception e) {
*/ SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
private void sendMessage(Exception e) { simpleMailMessage.setTo("a@celess.cn");
SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setSubject("服务器出现了错误");
simpleMailMessage.setTo("a@celess.cn"); StringBuilder msg = new StringBuilder();
simpleMailMessage.setSubject("服务器出现了错误"); String queryString = request.getQueryString();
StringBuilder msg = new StringBuilder(); msg.append("requirePath:\n").append(request.getRequestURL().toString());
msg.append("requirePath:\n").append(request.getRequestURL().toString()).append("?").append(request.getQueryString()).append("\n\n\n"); if (queryString != null) {
msg.append("msg:\n").append(e.getMessage()).append("\n\n\n"); msg.append("?").append(queryString);
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("\n\n\n");
msg.append("ip:\n").append(request.getRemoteAddr()).append("\n\n\n"); msg.append("msg:\n").append(e.getMessage()).append("\n\n\n");
simpleMailMessage.setText(msg.toString()); msg.append("date:\n").append(DateFormatUtil.getNow()).append("\n\n\n");
mailService.AsyncSend(simpleMailMessage); 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

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

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,59 +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(); List<User> findAll(Integer status);
int update(User user); List<User> findAll();
}
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); 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

@@ -1,31 +1,31 @@
package cn.celess.blog.service; package cn.celess.common.service;
import cn.celess.blog.entity.model.QiniuResponse; import cn.celess.common.entity.vo.QiniuResponse;
import com.qiniu.storage.model.FileInfo; import com.qiniu.storage.model.FileInfo;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.InputStream; import java.io.InputStream;
/** /**
* @author : xiaohai * @author : xiaohai
* @date : 2019/04/25 18:15 * @date : 2019/04/25 18:15
*/ */
@Service @Service
public interface QiniuService { public interface QiniuService {
/** /**
* 上传文件 * 上传文件
* *
* @param is InputStream流 * @param is InputStream流
* @param fileName 文件名 * @param fileName 文件名
* @return 响应数据 * @return 响应数据
*/ */
QiniuResponse uploadFile(InputStream is, String fileName); QiniuResponse uploadFile(InputStream is, String fileName);
/** /**
* 获取文件列表 * 获取文件列表
* *
* @return 文件列表 * @return 文件列表
*/ */
FileInfo[] getFileList(); 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); 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 net.sf.json.JSONObject; import cn.celess.common.entity.vo.WebUpdateModel;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; 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
JSONObject 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,319 +1,331 @@
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.UserModel; import cn.celess.common.entity.vo.QiniuResponse;
import cn.celess.blog.entity.request.LoginReq; import cn.celess.common.entity.vo.UserModel;
import cn.celess.blog.service.MailService; import cn.celess.common.service.MailService;
import com.fasterxml.jackson.core.JsonProcessingException; import cn.celess.common.service.QiniuService;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j; import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.After; import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before; import com.qiniu.storage.model.FileInfo;
import org.junit.Test; import lombok.extern.slf4j.Slf4j;
import org.junit.runner.RunWith; import org.junit.After;
import org.slf4j.Logger; import org.junit.Before;
import org.slf4j.LoggerFactory; import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.beans.factory.annotation.Autowired;
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.test.context.ActiveProfiles; import org.springframework.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.ActiveProfiles;
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.setup.MockMvcBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.context.WebApplicationContext; import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.IOException;
import java.lang.reflect.Field; import java.io.InputStream;
import java.util.Map; import java.io.UnsupportedEncodingException;
import java.util.UUID; import java.lang.reflect.Field;
import java.util.Map;
import static cn.celess.blog.enmu.ResponseEnum.SUCCESS; import java.util.UUID;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static cn.celess.common.constant.ResponseEnum.SUCCESS;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.junit.Assert.assertNotNull;
/** /**
* @Author: 小海 * @Author: 小海
* @Date: 2019/08/22 12:46 * @Date: 2019/08/22 12:46
* @Description: 测试基类 * @Description: 测试基类
*/ */
@SpringBootTest @WebAppConfiguration
@RunWith(SpringRunner.class) @ActiveProfiles("test")
@WebAppConfiguration public abstract class BaseTest {
@ActiveProfiles("test")
public class BaseTest { private final Logger logger = LoggerFactory.getLogger(this.getClass());
protected MockMvc mockMvc;
private final Logger logger = LoggerFactory.getLogger(this.getClass()); protected final static String Code = "code";
protected final static String Result = "result";
protected MockMvc mockMvc; protected final static String USERE_MAIL = "zh56462271@qq.com";
protected final static String Code = "code"; protected final static String ADMIN_EMAIL = "a@celess.cn";
protected final static String Result = "result";
/** /**
* 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>>() { };
}; protected static final TypeReference<?> OBJECT_TYPE = new TypeReference<Response<Object>>() {
protected static final TypeReference<?> OBJECT_TYPE = new TypeReference<Response<Object>>() { };
}; protected static final TypeReference<?> MAP_OBJECT_TYPE = new TypeReference<Response<Map<String, Object>>>() {
protected static final TypeReference<?> MAP_OBJECT_TYPE = new TypeReference<Response<Map<String, Object>>>() { };
};
@Autowired @Autowired
private WebApplicationContext wac; private WebApplicationContext wac;
protected MockHttpSession session; protected MockHttpSession session;
@Before @Before
public void before() { public void before() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
session = new MockHttpSession(); session = new MockHttpSession();
System.out.println("==========> 开始测试 <========="); System.out.println("==========> 开始测试 <=========");
} }
@After @After
public void after() { public void after() {
System.out.println("==========> 测试结束 <========="); System.out.println("==========> 测试结束 <=========");
} }
/** /**
*  admin 权限用户登录 *  admin 权限用户登录
* *
* @return token * @return token
*/ */
protected String adminLogin() { protected String adminLogin() {
LoginReq req = new LoginReq(); LoginReq req = new LoginReq();
req.setEmail("a@celess.cn"); req.setEmail(ADMIN_EMAIL);
req.setPassword("123456789"); req.setPassword("123456789");
req.setIsRememberMe(true); req.setIsRememberMe(true);
String token = login(req); String token = login(req);
assertNotNull(token); assertNotNull(token);
return token; return token;
} }
/** /**
* user 权限用户登录 * user 权限用户登录
* *
* @return token * @return token
*/ */
protected String userLogin() { protected String userLogin() {
LoginReq req = new LoginReq(); LoginReq req = new LoginReq();
req.setEmail("zh56462271@qq.com"); req.setEmail(USERE_MAIL);
req.setPassword("123456789"); req.setPassword("123456789");
req.setIsRememberMe(true); req.setIsRememberMe(true);
String token = login(req); String token = login(req);
assertNotNull(token); assertNotNull(token);
return token; return token;
} }
/** /**
* 登录逻辑 * 登录逻辑
* *
* @param req 用户信息 * @param req 用户信息
* @return token | null * @return token | null
*/ */
private 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();
assertNotNull(token); assertNotNull(token);
return token; return token;
} catch (Exception e) { } catch (Exception e) {
logger.error("测试登录错误"); logger.error("测试登录错误");
e.printStackTrace(); e.printStackTrace();
} }
assertNotNull(str); assertNotNull(str);
return null; return null;
} }
@Test
public void test() { /**
// 测试登录 * 产生指定长度的随机字符
assertNotNull(userLogin()); *
assertNotNull(adminLogin()); * @param len len
assertNotEquals(userLogin(), adminLogin()); * @return str
try { */
// 测试getMockData方法 protected String randomStr(int len) {
assertNotNull(getMockData(get("/headerInfo"))); return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
getMockData((get("/headerInfo"))).andDo(result -> assertNotNull(getResponse(result, OBJECT_TYPE))); }
} catch (Exception e) {
e.printStackTrace(); /**
} * 产生指定长度的随机字符
} *
* @return str
/** */
* 产生指定长度的随机字符 protected String randomStr() {
* return UUID.randomUUID().toString();
* @param len len }
* @return str
*/ /**
protected String randomStr(int len) { * 抽离的mock请求方法
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len); *
} * @param builder MockHttpServletRequestBuilder get(...) post(...) ....
* @return 返回 ResultActions
/** * @throws Exception exc
* 产生指定长度的随机字符 */
* protected ResultActions getMockData(MockHttpServletRequestBuilder builder) throws Exception {
* @return str return getMockData(builder, null, null);
*/ }
protected String randomStr() {
return UUID.randomUUID().toString(); /**
} * 抽离的mock请求方法 重载
*
/** * @param builder ..
* 抽离的mock请求方法 * @param token 用户登录的token
* * @return ..
* @param builder MockHttpServletRequestBuilder get(...) post(...) .... * @throws Exception ..
* @return 返回 ResultActions */
* @throws Exception exc protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token) throws Exception {
*/ return getMockData(builder, token, null);
protected ResultActions getMockData(MockHttpServletRequestBuilder builder) throws Exception { }
return getMockData(builder, null, null);
} /**
* 抽离的mock请求方法 重载
/** *
* 抽离的mock请求方法 重载 * @param builder ..
* * @param token ..
* @param builder .. * @param content http中发送的APPLICATION_JSON的json数据
* @param token 用户登录的token * @return ..
* @return .. * @throws Exception ..
* @throws Exception .. */
*/ protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token, Object content) throws Exception {
protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token) throws Exception { // MockHttpServletRequestBuilder mockHttpServletRequestBuilder = get(url);
return getMockData(builder, token, null); if (token != null) {
} builder.header("Authorization", "Bearer "+token);
}
/** if (content != null) {
* 抽离的mock请求方法 重载 ObjectMapper mapper = new ObjectMapper();
* builder.content(mapper.writeValueAsString(content)).contentType(MediaType.APPLICATION_JSON);
* @param builder .. logger.debug("param::json->{}", mapper.writeValueAsString(content));
* @param token .. }
* @param content http中发送的APPLICATION_JSON的json数据 return mockMvc.perform(builder).andExpect(MockMvcResultMatchers.status().isOk());
* @return .. }
* @throws Exception ..
*/
protected ResultActions getMockData(MockHttpServletRequestBuilder builder, String token, Object content) throws Exception { protected <T> Response<T> getResponse(String json) {
// MockHttpServletRequestBuilder mockHttpServletRequestBuilder = get(url); return getResponse(json, OBJECT_TYPE);
if (token != null) { }
builder.header("Authorization", token);
} protected <T> Response<T> getResponse(MvcResult result) {
if (content != null) { return getResponse(result, OBJECT_TYPE);
builder.content(mapper.writeValueAsString(content)).contentType(MediaType.APPLICATION_JSON); }
}
return mockMvc.perform(builder).andExpect(status().isOk()); /**
} * 根据json 信息反序列化成Response对象
*
* @param json json
protected <T> Response<T> getResponse(String json) { * @param <T> 泛型
return getResponse(json, OBJECT_TYPE); * @return Response对象
} */
protected <T> Response<T> getResponse(String json, TypeReference<?> responseType) {
protected <T> Response<T> getResponse(MvcResult result) { Response<T> response = null;
return getResponse(result, OBJECT_TYPE); try {
} ObjectMapper mapper = new ObjectMapper();
mapper.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
/** response = mapper.readValue(json, responseType);
* 根据json 信息反序列化成Response对象 } catch (IOException e) {
* logger.error("解析json Response对象错误json:[{}]", json);
* @param json json e.printStackTrace();
* @param <T> 泛型 }
* @return Response对象 assertNotNull(response);
*/ return response;
protected <T> Response<T> getResponse(String json, TypeReference<?> responseType) { }
Response<T> response = null;
System.out.println(responseType.getType()); /**
try { * 根据json 信息反序列化成Response对象
response = mapper.readValue(json, responseType); *
} catch (IOException e) { * @param result MvcResult
logger.error("解析json Response对象错误json:[{}]", json); * @param <T> 泛型
e.printStackTrace(); * @return Response对象
} */
assertNotNull(response); protected <T> Response<T> getResponse(MvcResult result, TypeReference<?> responseType) {
return response; try {
} return getResponse(result.getResponse().getContentAsString(), responseType);
} catch (UnsupportedEncodingException e) {
/** logger.error("解析json Response对象错误result:[{}]", result);
* 根据json 信息反序列化成Response对象 e.printStackTrace();
* }
* @param result MvcResult return null;
* @param <T> 泛型 }
* @return Response对象
*/
protected <T> Response<T> getResponse(MvcResult result, TypeReference<?> responseType) { /**
try { * 修改 mailService 的实现类
return getResponse(result.getResponse().getContentAsString(), responseType); *
} catch (UnsupportedEncodingException e) { * @param service service
logger.error("解析json Response对象错误result:[{}]", result); * @param mailFiledName service 中自动注入的mailService字段名
e.printStackTrace(); */
} protected void mockInjectInstance(Object service, String mailFiledName, Object impl) {
return null; Field field;
} try {
assertNotNull(service);
field = service.getClass().getDeclaredField(mailFiledName);
/** field.setAccessible(true);
* 修改 mailService 的实现类 field.set(service, impl);
* } catch (NoSuchFieldException | IllegalAccessException e) {
* @param service service e.printStackTrace();
* @param mailFiledName service 中自动注入的mailService字段名 }
*/ }
protected void mockEmailServiceInstance(Object service, String mailFiledName) {
Field mailServiceField;
try { @Slf4j
mailServiceField = service.getClass().getDeclaredField(mailFiledName); @Service("mailService")
mailServiceField.setAccessible(true); public static class TestMailServiceImpl implements MailService {
mailServiceField.set(service, new TestMailServiceImpl());
} catch (NoSuchFieldException | IllegalAccessException e) { @Override
e.printStackTrace(); public Boolean AsyncSend(SimpleMailMessage message) {
} log.debug("异步邮件请求,SimpleMailMessage:[{}]", getJson(message));
} return true;
}
@Slf4j @Override
protected static class TestMailServiceImpl implements MailService { public Boolean send(SimpleMailMessage message) {
log.debug("邮件请求,SimpleMailMessage:[{}]", getJson(message));
@Override return true;
public Boolean AsyncSend(SimpleMailMessage message) { }
log.debug("异步邮件请求,SimpleMailMessage:[{}]", getJson(message));
return true; /**
} * 转json
*
@Override * @param o
public Boolean send(SimpleMailMessage message) { * @return
log.debug("邮件请求,SimpleMailMessage:[{}]", getJson(message)); */
return true; private String getJson(Object o) {
} ObjectMapper mapper = new ObjectMapper();
try {
/** return mapper.writeValueAsString(o);
* 转json } catch (JsonProcessingException e) {
* return null;
* @param o }
* @return }
*/ }
private String getJson(Object o) {
ObjectMapper mapper = new ObjectMapper(); @Slf4j
try { @Service("qiniuService")
return mapper.writeValueAsString(o); public static class TestQiNiuServiceImpl implements QiniuService {
} catch (JsonProcessingException e) { @Override
return null; public QiniuResponse uploadFile(InputStream is, String fileName) {
} QiniuResponse response = new QiniuResponse();
} log.debug("上传文件请求,[fileName:{}]", fileName);
}
response.key = "key";
} response.bucket = "bucket";
response.hash = "hash";
response.fsize = 1;
return response;
}
@Override
public FileInfo[] getFileList() {
log.debug("获取文件列表请求");
return new FileInfo[0];
}
}
}

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

@@ -0,0 +1,62 @@
package cn.celess.common.util;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.io.IOException;
/**
* @Author: 小海
* @Date: 2020-04-23 15:51
* @Desc:
*/
public class HttpUtil {
/**
* 获取http请求的响应
*
* @param url url链接
* @return 请求的响应
*/
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) {
return null;
}
}
/**
* 获取渲染后的网页数据
*
* @param url url链接
* @return 经js渲染后的网页源代码
*/
public static String getAfterRendering(String url) {
try (final WebClient webClient = new WebClient(BrowserVersion.BEST_SUPPORTED)) {
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setDownloadImages(false);
webClient.getOptions().setActiveXNative(false);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
final HtmlPage page = webClient.getPage(url);
return page.asXml();
} catch (IOException e) {
return null;
}
}
}

View File

@@ -1,7 +1,9 @@
package cn.celess.blog.util; package cn.celess.common.util;
import cn.celess.blog.entity.*;
import cn.celess.blog.entity.model.*; import cn.celess.common.constant.UserAccountStatusEnum;
import cn.celess.common.entity.*;
import cn.celess.common.entity.vo.*;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
/** /**
@@ -46,6 +48,7 @@ public class ModalTrans {
} }
UserModel userModel = new UserModel(); UserModel userModel = new UserModel();
BeanUtils.copyProperties(user, userModel); BeanUtils.copyProperties(user, userModel);
userModel.setStatus(UserAccountStatusEnum.get(user.getStatus()));
userModel.setAvatarImgUrl(user.getAvatarImgUrl() == null || user.getAvatarImgUrl().length() == 0 ? userModel.setAvatarImgUrl(user.getAvatarImgUrl() == null || user.getAvatarImgUrl().length() == 0 ?
null : null :
"http://cdn.celess.cn/" + user.getAvatarImgUrl()); "http://cdn.celess.cn/" + user.getAvatarImgUrl());

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;
} }
} }

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