Compare commits

...

97 Commits
v1 ... v2.1.0

Author SHA1 Message Date
禾几海
f375def613 active-profiles 2020-07-25 17:32:02 +08:00
禾几海
af43657b5b null值异常 2020-07-24 21:09:17 +08:00
禾几海
526b73b4f8 优化提示 2020-07-24 16:47:26 +08:00
禾几海
d9db98849a 调整测试基类 2020-07-23 23:32:42 +08:00
禾几海
6c3645ba15 增加获取已删除数据的选项 2020-07-23 23:08:03 +08:00
禾几海
43a5e2ab2f 抽离Mock请求的方法,过渡到jackson 2020-07-23 23:02:53 +08:00
禾几海
739256424f . 2020-07-18 16:48:04 +08:00
禾几海
3c839ad8ca 数据库建表语句和测试数据 2020-07-18 13:33:33 +08:00
禾几海
efbd5b3d72 删除逻辑 2020-07-18 13:32:50 +08:00
禾几海
5ba7e684fa 生成sitemap过滤文章 2020-07-18 12:32:42 +08:00
禾几海
f7c1726d51 添加deleted字段 2020-07-18 12:30:53 +08:00
禾几海
5504abe3e0 Other.java -> CommonController.java 2020-07-18 12:29:07 +08:00
禾几海
5aeec0cfe4 . 2020-07-11 14:14:36 +08:00
禾几海
e2fe41c2e0 换用knife4j,swaggerUI 2020-07-11 14:12:57 +08:00
禾几海
48f485b378 . 2020-07-11 10:52:24 +08:00
禾几海
6ee8fb65c3 ci 2020-07-11 10:52:13 +08:00
禾几海
2106bf4d94 pr 的ci测试 2020-05-27 18:11:27 +08:00
禾几海
72cef158a1 异常 2020-05-27 18:07:55 +08:00
禾几海
2ef9073650 调整评论的接口 2020-05-27 16:30:17 +08:00
禾几海
260ae53c8d 调整 2020-05-27 13:28:48 +08:00
禾几海
21adedea84 IDEA代码优化 2020-05-26 14:03:46 +08:00
禾几海
7d7a0fc82d 修改对象类型 2020-05-26 14:01:27 +08:00
禾几海
4770c37f4f 修改Response 2020-05-26 14:00:17 +08:00
禾几海
450978ecd9 修改Response 的date响应字段 2020-05-26 13:59:36 +08:00
禾几海
4035c7e024 更改sql文件 2020-05-26 12:56:57 +08:00
禾几海
7aebaaa98b . 2020-05-26 12:54:51 +08:00
禾几海
03cb04ab06 修复bug 2020-05-26 12:54:24 +08:00
禾几海
aa882406d0 Service,dao层,视图,模型修改 单元测试 2020-05-26 12:34:35 +08:00
禾几海
fde9b8511c Service层修改 单元测试 2020-05-26 00:27:50 +08:00
禾几海
9582725b3a 修改 单元测试 2020-05-26 00:16:09 +08:00
禾几海
2f27578bb0 dao层修改 2020-05-26 00:13:57 +08:00
禾几海
d3757c5880 dao层修改 2020-05-26 00:10:34 +08:00
禾几海
c39dac30fb Service层修改 单元测试 2020-05-26 00:10:09 +08:00
禾几海
73a1d3eadf Service层修改 单元测试 2020-05-25 23:04:41 +08:00
禾几海
4e383b6598 Service层修改 单元测试 2020-05-25 22:48:57 +08:00
禾几海
030aaaca25 Service层修改 单元测试 2020-05-25 22:44:18 +08:00
禾几海
d19e5b6286 Service层修改 单元测试 2020-05-25 22:18:50 +08:00
禾几海
c4ed6602e7 rename method 2020-05-25 22:06:13 +08:00
禾几海
ae7d063fdd Service层修改 单元测试 2020-05-25 22:05:46 +08:00
禾几海
67a1b1faf9 Service层修改 单元测试 2020-05-25 21:43:53 +08:00
禾几海
9e6868b638 dao层修改 单元测试 2020-05-25 14:48:05 +08:00
禾几海
9185ff8f58 dao层修改 单元测试 2020-05-25 13:50:11 +08:00
禾几海
190e1624ca dao层修改 单元测试 2020-05-25 00:20:36 +08:00
禾几海
86b6bae6e6 dao层修改 单元测试 2020-05-25 00:02:26 +08:00
禾几海
0adf936085 dao层修改 单元测试 2020-05-24 23:54:13 +08:00
禾几海
4f63f7b3d5 dao层修改 单元测试 2020-05-24 22:54:51 +08:00
禾几海
0136435a41 dao层修改 单元测试 2020-05-24 22:02:41 +08:00
禾几海
87de48b5a0 dao层修改 单元测试 2020-05-24 22:00:06 +08:00
禾几海
732bbe4444 修改sql 2020-05-24 19:22:38 +08:00
禾几海
9b6293fbeb 修改查询语句 2020-05-23 13:27:30 +08:00
禾几海
bc20173084 数据表改动 2020-05-23 00:16:08 +08:00
禾几海
59b7be00eb 添加密码修改的api 2020-05-19 19:53:38 +08:00
禾几海
2f6a9679da 修复跨域情况下前台获取不到Authorization响应字段 2020-05-18 08:30:50 +08:00
小海
5b8700930b 修改测试的接口地址 2020-04-23 17:57:05 +08:00
小海
18477706d1 添加github对应的url 2020-04-23 17:30:57 +08:00
小海
cd7e6b6378 修改接口名和响应内容 2020-04-23 16:34:04 +08:00
小海
d934fbe284 提取网络请求部分 2020-04-23 16:12:03 +08:00
小海
55589c6a59 修复响应码错误bug 2020-04-22 15:23:19 +08:00
小海
4ab402ccf8 更新readme 2020-04-17 13:27:21 +08:00
小海
c74aea6c3b 移除gitlab ci 2020-04-17 13:27:06 +08:00
小海
7c2b8d8d28 更新配置文件 2020-04-17 13:01:42 +08:00
小海
6798cae1b8 忘记添加环境变量 2020-04-17 12:41:19 +08:00
小海
ba7a02c5c0 Update mavenpublish.yml 2020-04-17 12:37:35 +08:00
小海
bd50cfc339 Update mavenpublish.yml 2020-04-17 12:13:51 +08:00
小海
e282e16fd3 update mavenpublish.yml 2020-04-17 11:56:43 +08:00
小海
18366b7aa4 Merge branch 'master' of https://github.com/xiaohai2271/blog-backEnd 2020-04-17 11:43:27 +08:00
小海
66dffbfefe 配置ci调整配置文件 2020-04-17 11:29:52 +08:00
小海
a7cd83a6b5 Update mavenpublish.yml 2020-04-17 11:11:12 +08:00
小海
0a5921b66d add github ci 2020-04-17 11:09:48 +08:00
小海
e04238f0c9 更新token 2020-04-16 23:26:41 +08:00
小海
09cb012b14 可能出现为空的情况 2020-04-16 23:25:49 +08:00
小海
922b83e169 修复小bug 2020-04-06 19:47:32 +08:00
小海
1cd6e0d7c9 修改部分api以及响应数据结构 2020-04-06 15:26:41 +08:00
小海
ec0b17151c 新增必应每日一图图片获取接口 2020-04-03 17:22:10 +08:00
小海
98430a34f6 修复一个小Bug 2020-03-29 14:17:29 +08:00
小海
23ee331609 修改响应码 2020-03-29 14:16:46 +08:00
小海
ebddbc0ecf 修改响应的Tag的articles字段类型 2020-03-29 14:16:17 +08:00
小海
8181fab48d 修改响应的Category的articles字段类型 2020-03-29 13:55:59 +08:00
小海
7ba287d261 更新Tag 2019-12-04 16:30:51 +08:00
小海
1745a5d821 Fix NullPointer Exception 2019-12-04 15:54:45 +08:00
小海
9a4a930426 用户访问情况记录 2019-12-04 15:28:01 +08:00
小海
a0eaddafec . 2019-12-04 15:25:50 +08:00
小海
450f308f1e 自动注入HttpServletRequest 2019-12-04 14:43:10 +08:00
小海
86bb5e1b13 . 2019-12-04 14:38:49 +08:00
小海
a4c2ec1272 修改JwtUtil的部分方法 2019-12-04 14:08:45 +08:00
小海
2945d091ee Update README.md 2019-12-04 12:08:03 +08:00
小海
900d84b15e Add Test coverage 2019-12-04 11:35:42 +08:00
小海
d9aac0fbd8 自动部署 2019-12-01 13:28:19 +08:00
小海
28aa7cf7e3 Add maven wrapper 2019-12-01 12:42:01 +08:00
小海
7972f4d473 . 2019-11-30 23:08:30 +08:00
小海
79ec6fcc91 Add CI status 2019-11-30 22:56:56 +08:00
小海
1f736dc9c9 修改获取测试资源的方式 2019-11-29 23:58:55 +08:00
小海
55ccff3451 关闭两个不稳定的测试 2019-11-29 23:26:53 +08:00
小海
a5811364c7 添加CI测试 2019-11-29 23:22:20 +08:00
小海
a77dc695f6 修复可能存在的异常 2019-11-29 23:21:32 +08:00
小海
753ea5c9a1 将私钥都分离放到配置文件中 2019-11-29 21:29:48 +08:00
小海
19e0697a01 . 2019-11-29 21:29:07 +08:00
125 changed files with 4779 additions and 3219 deletions

47
.github/workflows/deplay.yml vendored Normal file
View File

@@ -0,0 +1,47 @@
# 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 }}

29
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,29 @@
# 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

@@ -1,8 +1,10 @@
.idea/
*.imi
*.iml
target/
# 本地项目的私有文件
back-end/blog-dev.sql
src/main/resources/application-prod.properties
src/main/resources/application-dev.properties
src/main/resources/application-prod.properties
src/main/resources/application-test.properties

View File

@@ -1,38 +1,32 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.5";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
@@ -80,13 +74,13 @@ 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);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
@@ -102,6 +96,16 @@ public class MavenWrapperDownloader {
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());

Binary file not shown.

View File

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

View File

@@ -1,7 +1,5 @@
# 小海博客后端管理系统
![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的后端博客管理系统

149
blog.iml
View File

@@ -1,149 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="Spring" name="Spring">
<configuration />
</facet>
<facet type="web" name="Web">
<configuration>
<webroots />
<sourceRoots>
<root url="file://$MODULE_DIR$/src/main/java" />
<root url="file://$MODULE_DIR$/src/main/resources" />
</sourceRoots>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-web:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-autoconfigure:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-logging:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-classic:1.2.3" level="project" />
<orderEntry type="library" name="Maven: ch.qos.logback:logback-core:1.2.3" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-to-slf4j:2.11.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.logging.log4j:log4j-api:2.11.2" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.25" level="project" />
<orderEntry type="library" name="Maven: javax.annotation:javax.annotation-api:1.3.2" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.yaml:snakeyaml:1.23" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-json:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.9.8" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.8" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.8" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-tomcat:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-core:9.0.16" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-el:9.0.16" level="project" />
<orderEntry type="library" name="Maven: org.apache.tomcat.embed:tomcat-embed-websocket:9.0.16" level="project" />
<orderEntry type="library" name="Maven: org.hibernate.validator:hibernate-validator:6.0.14.Final" level="project" />
<orderEntry type="library" name="Maven: javax.validation:validation-api:2.0.1.Final" level="project" />
<orderEntry type="library" name="Maven: org.jboss.logging:jboss-logging:3.3.2.Final" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-web:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-beans:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-webmvc:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-aop:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-expression:5.1.5.RELEASE" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: mysql:mysql-connector-java:8.0.15" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-starter-test:2.1.3.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test:2.1.3.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework.boot:spring-boot-test-autoconfigure:2.1.3.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jayway.jsonpath:json-path:2.4.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.assertj:assertj-core:3.11.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mockito:mockito-core:2.23.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy:1.9.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.bytebuddy:byte-buddy-agent:1.9.10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.objenesis:objenesis:2.6" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-library:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.skyscreamer:jsonassert:1.5.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.vaadin.external.google:android-json:0.0.20131108.vaadin1" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-core:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jcl:5.1.5.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.springframework:spring-test:5.1.5.RELEASE" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.xmlunit:xmlunit-core:2.6.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: javax.xml.bind:jaxb-api:2.3.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: javax.activation:javax.activation-api:1.2.0" level="project" />
<orderEntry type="library" name="Maven: com.alibaba:druid:1.1.14" level="project" />
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.6" level="project" />
<orderEntry type="library" name="Maven: io.springfox:springfox-swagger2:2.6.1" level="project" />
<orderEntry type="library" name="Maven: io.swagger:swagger-annotations:1.5.10" level="project" />
<orderEntry type="library" name="Maven: io.swagger:swagger-models:1.5.10" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.9.0" level="project" />
<orderEntry type="library" name="Maven: io.springfox:springfox-spi:2.6.1" level="project" />
<orderEntry type="library" name="Maven: io.springfox:springfox-core:2.6.1" level="project" />
<orderEntry type="library" name="Maven: io.springfox:springfox-schema:2.6.1" level="project" />
<orderEntry type="library" name="Maven: io.springfox:springfox-swagger-common:2.6.1" level="project" />
<orderEntry type="library" name="Maven: io.springfox:springfox-spring-web:2.6.1" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:18.0" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml:classmate:1.4.0" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.25" level="project" />
<orderEntry type="library" name="Maven: org.springframework.plugin:spring-plugin-core:1.2.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.plugin:spring-plugin-metadata:1.2.0.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.mapstruct:mapstruct:1.0.0.Final" level="project" />
<orderEntry type="library" name="Maven: io.springfox:springfox-swagger-ui:2.6.1" level="project" />
<orderEntry type="library" name="Maven: com.youbenzi:MDTool:1.2.3" level="project" />
<orderEntry type="library" name="Maven: net.minidev:json-smart:2.3" level="project" />
<orderEntry type="library" name="Maven: net.minidev:accessors-smart:1.2" level="project" />
<orderEntry type="library" name="Maven: org.ow2.asm:asm:5.0.4" level="project" />
<orderEntry type="library" name="Maven: net.sf.json-lib:json-lib:jdk15:2.4" level="project" />
<orderEntry type="library" name="Maven: commons-beanutils:commons-beanutils:1.8.0" level="project" />
<orderEntry type="library" name="Maven: commons-collections:commons-collections:3.2.1" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.5" level="project" />
<orderEntry type="library" name="Maven: commons-logging:commons-logging:1.1.1" level="project" />
<orderEntry type="library" name="Maven: net.sf.ezmorph:ezmorph:1.0.6" level="project" />
<orderEntry type="library" name="Maven: com.qiniu:qiniu-java-sdk:7.2.27" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.squareup.okhttp3:okhttp:3.14.4" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.squareup.okio:okio:1.17.2" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.google.code.gson:gson:2.8.5" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-mail:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-context-support:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.sun.mail:javax.mail:1.6.2" level="project" />
<orderEntry type="library" name="Maven: javax.activation:activation:1.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-data-redis:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-redis:2.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-keyvalue:2.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework.data:spring-data-commons:2.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-tx:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-oxm:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.lettuce:lettuce-core:5.1.4.RELEASE" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-common:4.1.33.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-handler:4.1.33.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-buffer:4.1.33.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-codec:4.1.33.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-transport:4.1.33.Final" level="project" />
<orderEntry type="library" name="Maven: io.netty:netty-resolver:4.1.33.Final" level="project" />
<orderEntry type="library" name="Maven: io.projectreactor:reactor-core:3.2.6.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.reactivestreams:reactive-streams:1.0.2" level="project" />
<orderEntry type="library" name="Maven: org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.1" level="project" />
<orderEntry type="library" name="Maven: org.springframework.boot:spring-boot-starter-jdbc:2.1.3.RELEASE" level="project" />
<orderEntry type="library" name="Maven: com.zaxxer:HikariCP:3.2.0" level="project" />
<orderEntry type="library" name="Maven: org.springframework:spring-jdbc:5.1.5.RELEASE" level="project" />
<orderEntry type="library" name="Maven: org.mybatis.spring.boot:mybatis-spring-boot-autoconfigure:2.0.1" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis:3.5.1" level="project" />
<orderEntry type="library" name="Maven: org.mybatis:mybatis-spring:2.0.1" level="project" />
<orderEntry type="library" name="Maven: com.github.pagehelper:pagehelper-spring-boot-starter:1.2.12" level="project" />
<orderEntry type="library" name="Maven: com.github.pagehelper:pagehelper-spring-boot-autoconfigure:1.2.12" level="project" />
<orderEntry type="library" name="Maven: com.github.pagehelper:pagehelper:5.1.10" level="project" />
<orderEntry type="library" name="Maven: com.github.jsqlparser:jsqlparser:2.0" level="project" />
<orderEntry type="library" name="Maven: com.dyuproject.protostuff:protostuff-core:1.0.8" level="project" />
<orderEntry type="library" name="Maven: com.dyuproject.protostuff:protostuff-api:1.0.8" level="project" />
<orderEntry type="library" name="Maven: com.dyuproject.protostuff:protostuff-runtime:1.0.8" level="project" />
<orderEntry type="library" name="Maven: com.dyuproject.protostuff:protostuff-collectionschema:1.0.8" level="project" />
<orderEntry type="library" name="Maven: eu.bitwalker:UserAgentUtils:1.20" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" name="Maven: io.jsonwebtoken:jjwt:0.9.1" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.9.8" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.9.8" level="project" />
</component>
</module>

202
blog.sql
View File

@@ -1,58 +1,84 @@
CREATE DATABASE `blog`;
CREATE DATABASE if not exists `blog`;
USE blog;
CREATE TABLE `user`
(
`u_id` int not null primary key auto_increment,
`u_email` varchar(50) not null,
`u_pwd` varchar(40) not null comment '密码',
`u_email_status` boolean default false comment '邮箱验证状态',
`u_avatar` varchar(255) default null comment '用户头像',
`u_desc` tinytext COLLATE utf8mb4_unicode_ci default null comment '用户的描述',
`u_recently_landed_time` datetime default null comment '最近的登录时间',
`u_display_name` varchar(30) COLLATE utf8mb4_unicode_ci default null comment '展示的昵称',
`u_role` varchar(40) not null default 'user' comment '权限组',
`status` tinyint(1) not null default 0 comment '账户状态',
unique key `uni_user_id` (`u_id`),
unique key `uni_user_email` (`u_email`)
) comment '用户表';
CREATE TABLE `tag_category`
(
`t_id` bigint(20) primary key auto_increment,
`t_name` varchar(255) not null,
`is_category` boolean not null default true,
`is_delete` boolean not null default false comment '该数据是否被删除'
) comment '标签和分类表';
CREATE TABLE `article`
(
`a_id` bigint(20) primary key auto_increment,
`a_title` varchar(255) not null unique comment '文章标题',
`a_summary` varchar(255) not null comment '文章摘要',
`a_md_content` longtext not null comment '文章Markdown内容',
`a_tags_id` varchar(255) not null comment '标签id \',\'处于最尾端',
`a_category_id` bigint(20) not null comment '分类的id',
`a_title` varchar(255) COLLATE utf8mb4_unicode_ci not null unique comment '文章标题',
`a_summary` varchar(255) COLLATE utf8mb4_unicode_ci not null comment '文章摘要',
`a_md_content` longtext COLLATE utf8mb4_unicode_ci not null comment '文章Markdown内容',
`a_url` tinytext default null comment '转载文章的原文链接',
`a_author_id` bigint(20) not null comment '作者id',
`a_is_open` boolean default true comment '文章是否可见',
`a_author_id` int not null comment '作者id',
`a_is_original` boolean default true comment '文章是否原创',
`next_a_id` bigint(20) default -1 comment '下篇文章id',
`pre_a_id` bigint(20) default -1 comment '前一篇文章的id',
`a_reading_number` int default 0 comment '文章阅读数',
`a_publish_date` datetime not null comment '文章发布时间',
`a_update_date` datetime default null comment '文章的更新时间'
) DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_general_ci,comment '文章';
`a_like` int default 0 comment '文章点赞数',
`a_dislike` int default 0 comment '文章不喜欢数',
`a_category_id` bigint not null comment '文章分类id',
`a_publish_date` datetime default CURRENT_TIMESTAMP comment '文章发布时间',
`a_update_date` datetime default null comment '文章的更新时间',
`a_is_open` boolean default true comment '文章是否可见',
`is_delete` boolean not null default false comment '该数据是否被删除',
foreign key (a_category_id) references tag_category (t_id),
foreign key (a_author_id) references user (u_id)
) DEFAULT CHARSET = utf8mb4
COLLATE utf8mb4_general_ci,comment '文章表';
CREATE TABLE `tag`
CREATE TABLE `article_tag`
(
`tag_id` bigint(20) primary key auto_increment,
`tag_name` varchar(255) unique not null,
`articles` tinytext default null comment 'tag对应的文章id'
) comment '标签表';
CREATE table `category`
(
`c_id` bigint(20) primary key auto_increment,
`c_name` varchar(255) unique not null,
`articles` varchar(255) comment '分类下的文章'
)comment '分类表';
`at_id` bigint(20) primary key auto_increment,
`a_id` bigint(20) not null comment '文章id',
`t_id` bigint not null comment 'tag/category 的id',
foreign key (a_id) references article (a_id),
foreign key (t_id) references tag_category (t_id)
) comment '文章标签表';
CREATE TABLE `comment`
(
`co_id` bigint(20) primary key auto_increment,
`co_article_id` bigint(20) default -1 comment '文章id',
`is_comment` boolean default true comment '是否是评论',
`author_id` bigint(20) not null comment '留言者id',
`co_content` text not null comment '评论/留言内容',
`co_page_path` varchar(255) not null comment '评论/留言的页面',
`co_content` text COLLATE utf8mb4_unicode_ci not null comment '评论/留言内容',
`co_date` datetime not null comment '评论/留言的日期',
`co_status` tinyint not null default 0 comment '评论的状态',
`co_pid` bigint not null default -1 comment '评论/留言的父id',
`co_response_id` tinytext
) DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_general_ci,comment '评论/留言表';
`co_from_author_id` int not null comment '留言者id',
`co_to_author_id` int default null comment '评论的作者id'
) DEFAULT CHARSET = utf8mb4
COLLATE utf8mb4_general_ci,comment '评论/留言表';
CREATE TABLE `links`
(
`site_id` bigint(20) primary key auto_increment,
`site_name` varchar(255) not null comment '友站名称',
`is_open` boolean default true comment '是否公开',
`site_url` varchar(255) not null comment '首页地址'
`l_id` bigint(20) primary key auto_increment,
`l_name` varchar(255) COLLATE utf8mb4_unicode_ci not null comment '友站名称',
`l_is_open` boolean default true comment '是否公开',
`l_url` varchar(255) not null comment '首页地址',
`l_icon_path` varchar(255) not null comment '友链的icon地址',
`l_desc` varchar(255) COLLATE utf8mb4_unicode_ci not null comment '友链的说明描述',
`is_delete` boolean not null default false comment '该数据是否被删除'
) comment '友站表';
CREATE TABLE `visitor`
@@ -60,33 +86,91 @@ CREATE TABLE `visitor`
`v_id` bigint(20) primary key auto_increment,
`v_date` datetime not null comment '访问时间',
`v_ip` varchar(255) not null comment '访客ip',
`v_user_agent` text comment '访客ua'
`v_user_agent` text comment '访客ua',
`is_delete` boolean not null default false comment '该数据是否被删除'
) comment '访客表';
CREATE TABLE IF NOT EXISTS `web_update`
CREATE TABLE `web_update`
(
`update_id` bigint(20) primary key auto_increment,
`update_info` varchar(255) not null comment '更新内容',
`update_time` datetime not null comment '更新时间'
`wu_id` int primary key auto_increment,
`wu_info` varchar(255) COLLATE utf8mb4_unicode_ci not null comment '更新内容',
`wu_time` datetime not null comment '更新时间',
`is_delete` boolean not null default false comment '该数据是否被删除'
) comment '更新内容表';
create table `user`
(
`u_id` int not null primary key auto_increment,
`u_email` varchar(50) not null,
`u_uid` varchar(40) default null comment '用户唯一标识码',
`u_pwd` varchar(40) not null comment '密码',
`email_status` boolean default false comment '邮箱验证状态',
`u_avatar` varchar(255) comment '用户头像',
`u_desc` tinytext comment '用户的描述',
`recently_landed_time` datetime comment '最近的登录时间',
`email_verify_id` varchar(40) comment '用于找回密码或验证邮箱的id',
`display_name` varchar(30) comment '展示的昵称',
`role` varchar(40) not null default 'user' comment '权限组',
unique key `uni_user_id` (`u_id`),
unique key `uni_user_uid` (`u_uid`),
unique key `uni_user_email` (`u_email`)
) comment '用户表';
CREATE VIEW articleView
(articleId, title, summary, mdContent, url, isOriginal, readingCount, likeCount, dislikeCount,
publishDate, updateDate, isOpen,
categoryId, categoryName, tagId, tagName,
authorId, userEmail, userAvatar, userDisplayName, isDelete)
as
select article.a_id as articleId,
article.a_title as title,
article.a_summary as summary,
article.a_md_content as mdContent,
article.a_url as url,
article.a_is_original as isOriginal,
article.a_reading_number as readingCount,
article.a_like as likeCount,
article.a_dislike as dislikeCount,
article.a_publish_date as publishDate,
article.a_update_date as updateDate,
article.a_is_open as isOpen,
category.t_id as categoryId,
category.t_name as categoryName,
tag.t_id as tagId,
tag.t_name as tagName,
user.u_id as authorId,
user.u_email as userEmail,
user.u_avatar as userAvatar,
user.u_display_name as userDisplayName,
article.is_delete as isDelete
from article,
tag_category as tag,
tag_category as category,
article_tag,
user
where article.a_id = article_tag.a_id
and article_tag.t_id = tag.t_id
and tag.is_category = false
and article.a_category_id = category.t_id
and category.is_category = true
and article.a_author_id = user.u_id;
CREATE VIEW commentView
(commentId, pagePath, content, date, status, pid, toAuthorId, toAuthorEmail, toAuthorDisplayName,
toAuthorAvatar, fromAuthorId, fromAuthorEmail, fromAuthorDisplayName,
fromAuthorAvatar)
as
select cuT.co_id as commentId,
cuT.co_page_path as pagePath,
cuT.co_content as content,
cuT.co_date as date,
cuT.co_status as status,
cuT.co_pid as pid,
cuT.co_to_author_id as toAuthorId,
cuT.toEmail as toAuthorEmail,
cuT.toDisplayName as toAuthorDisplayName,
cuT.toAvatar as toAuthorAvatar,
userFrom.u_id as fromAuthorId,
userFrom.u_email as fromAuthorEmail,
userFrom.u_display_name as fromAuthorDisplayName,
userFrom.u_avatar as fromAuthorAvatar
from (select comment.co_id,
comment.co_page_path,
comment.co_content,
comment.co_date,
comment.co_status,
comment.co_pid,
comment.co_from_author_id,
comment.co_to_author_id,
userTo.u_email as toEmail,
userTo.u_display_name as toDisplayName,
userTo.u_avatar as toAvatar
from comment
left join user userTo on (comment.co_to_author_id = userTo.u_id)
) as cuT,
user as userFrom
where cuT.co_from_author_id = userFrom.u_id;

8
build.sh Normal file
View File

@@ -0,0 +1,8 @@
#!/bin/sh
echo "查询已存在进程"
pgrep -af blog-0.0.1-SNAPSHOT.jar
echo "结束已存在进程"
pkill -f blog-0.0.1-SNAPSHOT.jar
echo "开始运行小海博客"
nohup java -jar -Dfile.encoding=UTF-8 blog-0.0.1-SNAPSHOT.jar >blog.log &
echo "更新结束"

204
dev.sql Normal file

File diff suppressed because one or more lines are too long

116
mvnw vendored
View File

@@ -47,18 +47,19 @@ if [ -z "$MAVEN_SKIP_RC" ] ; then
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
cygwin=false
darwin=false
mingw=false
case "`uname`" in
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true ;;
Darwin*) darwin=true
Darwin*)
darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
export JAVA_HOME="$(/usr/libexec/java_home)"
else
export JAVA_HOME="/Library/Java/Home"
fi
@@ -68,7 +69,7 @@ esac
if [ -z "$JAVA_HOME" ]; then
if [ -r /etc/gentoo-release ]; then
JAVA_HOME=`java-config --jre-home`
JAVA_HOME=$(java-config --jre-home)
fi
fi
@@ -78,21 +79,21 @@ if [ -z "$M2_HOME" ] ; then
# need this for relative symlinks
while [ -h "$PRG" ]; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
ls=$(ls -ld "$PRG")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' >/dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
PRG="$(dirname "$PRG")/$link"
fi
done
saveddir=`pwd`
saveddir=$(pwd)
M2_HOME=`dirname "$PRG"`/..
M2_HOME=$(dirname "$PRG")/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
M2_HOME=$(cd "$M2_HOME" && pwd)
cd "$saveddir"
# echo Using m2 at $M2_HOME
@@ -101,36 +102,41 @@ fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
M2_HOME=$(cygpath --unix "$M2_HOME")
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
M2_HOME="$( (
cd "$M2_HOME"
pwd
))"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
JAVA_HOME="$( (
cd "$JAVA_HOME"
pwd
))"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
readLink=$(which readlink)
if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
if $darwin; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
javaHome="$(dirname \"$javaExecutable\")"
javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
javaExecutable="$(readlink -f \"$javaExecutable\")"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
javaHome="$(dirname \"$javaExecutable\")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
@@ -146,7 +152,7 @@ if [ -z "$JAVACMD" ] ; then
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
JAVACMD="$(which java)"
fi
fi
@@ -166,8 +172,7 @@ CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
if [ -z "$1" ]; then
echo "Path not specified to find_maven_basedir"
return 1
fi
@@ -181,7 +186,10 @@ find_maven_basedir() {
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
wdir=$(
cd "$wdir/.."
pwd
)
fi
# end of workaround
done
@@ -195,9 +203,9 @@ concat_lines() {
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
BASE_DIR=$(find_maven_basedir "$(pwd)")
if [ -z "$BASE_DIR" ]; then
exit 1;
exit 1
fi
##########################################################################################
@@ -212,31 +220,54 @@ else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
case "$key" in wrapperUrl)
jarUrl="$value"
break
;;
esac
done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
@@ -268,15 +299,20 @@ MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
M2_HOME=$(cygpath --path --windows "$M2_HOME")
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR")
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \

29
mvnw.cmd vendored
View File

@@ -37,7 +37,7 @@
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
@@ -120,23 +120,44 @@ SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end

28
pom.xml
View File

@@ -55,12 +55,12 @@
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<!--MarkDown 2 html -->
@@ -156,6 +156,26 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

View File

@@ -1,5 +1,6 @@
package cn.celess.blog.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
@@ -13,6 +14,9 @@ import org.springframework.web.filter.CorsFilter;
*/
@Configuration
public class CorsConfig {
@Value("${spring.profiles.active}")
private String activeModel;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
@@ -22,14 +26,17 @@ public class CorsConfig {
config.addAllowedOrigin("https://celess.cn");
config.addAllowedOrigin("https://www.celess.cn");
// 本地调试时的跨域
if (!"prod".equals(activeModel)) {
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedOrigin("http://127.0.0.1:4200");
}
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
config.addExposedHeader("Authorization");
config.setAllowCredentials(true);
config.setMaxAge(10800L);
source.registerCorsConfiguration("/**", config);

View File

@@ -19,11 +19,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MultipleSubmitFilter()).addPathPatterns("/*");
registry.addInterceptor(new MultipleSubmitFilter()).addPathPatterns("/**");
registry.addInterceptor(new VisitorRecord()).addPathPatterns("/**");
registry.addInterceptor(authenticationFilter()).addPathPatterns("/**");
// visitor 输出信息杂乱 暂时放弃使用
// registry.addInterceptor(new VisitorRecord()).addPathPatterns("/*");
}
@Bean
@@ -31,11 +29,11 @@ public class InterceptorConfig implements WebMvcConfigurer {
return new AuthenticationFilter();
}
// // session listener register bean
// @Bean
// public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
// ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
// slrBean.setListener(new SessionListener());
// return slrBean;
// }
@Bean
public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
// session listener register bean
ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
slrBean.setListener(new SessionListener());
return slrBean;
}
}

View File

@@ -7,6 +7,7 @@ import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@@ -25,7 +26,7 @@ public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable("dev".equals(environment))
.enable(!"prod".equals(environment))
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.celess.blog"))
@@ -37,7 +38,7 @@ public class SwaggerConfig {
return new ApiInfoBuilder()
.title("小海博客的APi")
.description("小海博客的APi")
.contact("小海")
.contact(new Contact("小海", "https://www.celess.cn", "a@celess.cn"))
.version("1.0")
.build();
}

View File

@@ -1,10 +1,10 @@
package cn.celess.blog.configuration.filter;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Response;
import cn.celess.blog.service.UserService;
import cn.celess.blog.util.JwtUtil;
import cn.celess.blog.util.RedisUtil;
import cn.celess.blog.util.ResponseUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -21,6 +21,11 @@ import java.io.IOException;
* @Description: 鉴权拦截器
*/
public class AuthenticationFilter implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);
private static final String USER_PREFIX = "/user";
private static final String ADMIN_PREFIX = "/admin";
private static final String ROLE_ADMIN = "admin";
private static final String ROLE_USER = "user";
@Autowired
JwtUtil jwtUtil;
@Autowired
@@ -28,25 +33,22 @@ public class AuthenticationFilter implements HandlerInterceptor {
@Autowired
UserService userService;
private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);
private static final String USER_PREFIX = "/user";
private static final String ADMIN_PREFIX = "/admin";
private static final String ROLE_ADMIN = "admin";
private static final String ROLE_USER = "user";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getRequestURI();
path = path.replaceAll("/+", "/");
int indexOf = path.indexOf("/", 1);
String rootPath = indexOf == -1 ? path : path.substring(0, indexOf);
String jwtStr = request.getHeader("Authorization");
if (jwtStr != null && !jwtStr.isEmpty() && !jwtUtil.isTokenExpired(jwtStr)) {
// 已登录 记录当前email
request.getSession().setAttribute("email", jwtUtil.getUsernameFromToken(jwtStr));
}
// 不需要鉴权的路径
if (!USER_PREFIX.equals(rootPath.toLowerCase()) && !ADMIN_PREFIX.equals(rootPath.toLowerCase())) {
return true;
}
String jwtStr = request.getHeader("Authorization");
if (jwtStr == null || jwtStr.isEmpty()) {
return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request);
}
@@ -54,11 +56,19 @@ public class AuthenticationFilter implements HandlerInterceptor {
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
}
String email = jwtUtil.getUsernameFromToken(jwtStr);
if (!redisUtil.hasKey(email + "-login") || jwtUtil.isTokenExpired(jwtStr)) {
if (jwtUtil.isTokenExpired(jwtStr)) {
// 登陆过期
return writeResponse(ResponseEnum.LOGIN_EXPIRED, response, request);
}
if (!redisUtil.hasKey(email + "-login")) {
return writeResponse(ResponseEnum.LOGOUT, response, request);
}
String role = userService.getUserRoleByEmail(email);
if (role.equals(ROLE_USER) || role.equals(ROLE_ADMIN)) {
// 更新token
String token = jwtUtil.updateTokenDate(jwtStr);
response.setHeader("Authorization", token);
}
if (role.equals(ROLE_ADMIN)) {
// admin
return true;
@@ -74,7 +84,7 @@ public class AuthenticationFilter implements HandlerInterceptor {
response.setHeader("Content-Type", "application/json;charset=UTF-8");
try {
logger.info("鉴权失败,[code:{},msg:{},path:{}]", e.getCode(), e.getMsg(), request.getRequestURI() + "?" + request.getQueryString());
response.getWriter().println(JSONObject.fromObject(ResponseUtil.response(e, null)));
response.getWriter().println(JSONObject.fromObject(Response.response(e, null)));
} catch (IOException ex) {
ex.printStackTrace();
}

View File

@@ -28,7 +28,7 @@ public class MultipleSubmitFilter implements HandlerInterceptor {
// 请求参数和路径均相同 且请求时间间隔小于 WAIT_TIME
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Response result = new Response(ResponseEnum.FAILURE.getCode(), "重复请求", null, System.currentTimeMillis());
Response result = new Response(ResponseEnum.FAILURE.getCode(), "重复请求", null);
response.getWriter().println(result.toString());
return false;
}

View File

@@ -21,7 +21,11 @@ public class VisitorRecord implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
HashMap<String, Integer> visitDetail = (HashMap<String, Integer>) session.getAttribute("visitDetail");
if (visitDetail == null) {
return true;
}
// 获取访问次数
Integer count = visitDetail.get(RequestUtil.getCompleteUrlAndMethod(request));
// 自增

View File

@@ -1,9 +1,7 @@
package cn.celess.blog.configuration.listener;
import cn.celess.blog.entity.User;
import cn.celess.blog.util.RedisUserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.annotation.WebListener;
@@ -17,20 +15,21 @@ import java.util.HashMap;
* @Date: 2019/10/18 15:33
* @Description: 监听session的情况
*/
@Log4j2
@WebListener
public class SessionListener implements HttpSessionListener {
@Autowired
RedisUserUtil redisUserUtil;
@Autowired
HttpServletRequest request;
private static final Logger logger = LoggerFactory.getLogger(SessionListener.class);
@Override
public void sessionCreated(HttpSessionEvent se) {
// TODO : can move 'visit' api to here
se.getSession().setAttribute("visitDetail", new HashMap<String, Integer>());
// se.getSession().setMaxInactiveInterval(10);// 10s for debug
logger.info("新增一个Session[{}]", se.getSession().getId());
// 10s for debug
// se.getSession().setMaxInactiveInterval(10);
// log.info("新增一个Session[{}]", se.getSession().getId());
}
@SuppressWarnings("unchecked")
@@ -39,12 +38,15 @@ public class SessionListener implements HttpSessionListener {
HashMap<String, Integer> visitDetail = (HashMap<String, Integer>) se.getSession().getAttribute("visitDetail");
StringBuilder sb = new StringBuilder();
sb.append("ip => ").append(se.getSession().getAttribute("ip"));
User user = redisUserUtil.get(request);
if (visitDetail.size() == 0) {
return;
}
sb.append("\t登录情况 => ");
sb.append(user == null ? "游客访问" : user.getEmail());
String email = (String) se.getSession().getAttribute("email");
sb.append(email == null ? "游客访问" : email);
visitDetail.forEach((s, integer) -> {
sb.append("\n").append("Method:[").append(s.split(":")[1]).append("]\tTimes:[").append(integer).append("]\tPath:[").append(s.split(":")[0]).append("]");
});
logger.info(sb.toString());
log.info(sb.toString());
}
}

View File

@@ -3,15 +3,17 @@ package cn.celess.blog.controller;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Response;
import cn.celess.blog.entity.model.ArticleModel;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.request.ArticleReq;
import cn.celess.blog.service.ArticleService;
import cn.celess.blog.util.RedisUserUtil;
import cn.celess.blog.util.ResponseUtil;
import cn.celess.blog.util.SitemapGenerateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author : xiaohai
@@ -36,7 +38,7 @@ public class ArticleController {
public Response create(@RequestBody ArticleReq body) {
ArticleModel articleModel = articleService.create(body);
sitemapGenerateUtil.createSitemap();
return ResponseUtil.success(articleModel);
return Response.success(articleModel);
}
/**
@@ -49,7 +51,7 @@ public class ArticleController {
public Response delete(@RequestParam("articleID") long articleId) {
boolean delete = articleService.delete(articleId);
sitemapGenerateUtil.createSitemap();
return ResponseUtil.success(delete);
return Response.success(delete);
}
/**
@@ -62,7 +64,7 @@ public class ArticleController {
public Response update(@RequestBody ArticleReq body) {
ArticleModel update = articleService.update(body);
sitemapGenerateUtil.createSitemap();
return ResponseUtil.success(update);
return Response.success(update);
}
/**
@@ -80,13 +82,13 @@ public class ArticleController {
public Response retrieveOneById(@PathVariable("articleID") long articleId,
@RequestParam(value = "update", defaultValue = "false") boolean is4update,
HttpServletRequest request) {
ArticleModel article = articleService.retrieveOneByID(articleId, is4update);
ArticleModel article = articleService.retrieveOneById(articleId, is4update);
if (article.getOpen()) {
return ResponseUtil.success(article);
} else if (article.getAuthorId().equals(redisUserUtil.get(request).getId())) {
return ResponseUtil.success(article);
return Response.success(article);
} else if (article.getAuthor().getId().equals(redisUserUtil.get().getId())) {
return Response.success(article);
}
return ResponseUtil.response(ResponseEnum.PERMISSION_ERROR, null);
return Response.response(ResponseEnum.PERMISSION_ERROR, null);
}
/**
@@ -99,7 +101,7 @@ public class ArticleController {
@GetMapping("/articles")
public Response articles(@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "count", defaultValue = "5") int count) {
return ResponseUtil.success(articleService.retrievePageForOpen(count, page));
return Response.success(articleService.retrievePageForOpen(count, page));
}
/**
@@ -111,8 +113,9 @@ public class ArticleController {
*/
@GetMapping("/admin/articles")
public Response adminArticles(@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "count", defaultValue = "10") int count) {
return ResponseUtil.success(articleService.adminArticles(count, page));
@RequestParam(name = "count", defaultValue = "10") int count,
@RequestParam(name = "deleted", defaultValue = "false") boolean deleted) {
return Response.success(articleService.adminArticles(count, page, deleted));
}
/**
@@ -127,7 +130,7 @@ public class ArticleController {
public Response findByCategory(@PathVariable("name") String name,
@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "count", defaultValue = "10") int count) {
return ResponseUtil.success(articleService.findByCategory(name, page, count));
return Response.success(articleService.findByCategory(name, page, count));
}
/**
@@ -142,13 +145,13 @@ public class ArticleController {
public Response findByTag(@PathVariable("name") String name,
@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "count", defaultValue = "10") int count) {
return ResponseUtil.success(articleService.findByTag(name, page, count));
return Response.success(articleService.findByTag(name, page, count));
}
@GetMapping("/createSitemap")
public Response createSitemap() {
sitemapGenerateUtil.createSitemap();
return ResponseUtil.success(null);
return Response.success(null);
}
}

View File

@@ -2,7 +2,6 @@ package cn.celess.blog.controller;
import cn.celess.blog.entity.Response;
import cn.celess.blog.service.CategoryService;
import cn.celess.blog.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -24,7 +23,7 @@ public class CategoryController {
*/
@PostMapping("/admin/category/create")
public Response addOne(@RequestParam("name") String name) {
return ResponseUtil.success(categoryService.create(name));
return Response.success(categoryService.create(name));
}
/**
@@ -35,7 +34,7 @@ public class CategoryController {
*/
@DeleteMapping("/admin/category/del")
public Response deleteOne(@RequestParam("id") long id) {
return ResponseUtil.success(categoryService.delete(id));
return Response.success(categoryService.delete(id));
}
/**
@@ -48,7 +47,7 @@ public class CategoryController {
@PutMapping("/admin/category/update")
public Response updateOne(@RequestParam("id") Long id,
@RequestParam("name") String name) {
return ResponseUtil.success(categoryService.update(id, name));
return Response.success(categoryService.update(id, name));
}
/**
@@ -57,7 +56,8 @@ public class CategoryController {
* @return Response
*/
@GetMapping("/categories")
public Response getPage() {
return ResponseUtil.success(categoryService.retrievePage());
public Response getPage(@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "count", defaultValue = "1000") int count) {
return Response.success(categoryService.retrievePage(page, count));
}
}

View File

@@ -1,10 +1,8 @@
package cn.celess.blog.controller;
import cn.celess.blog.entity.Comment;
import cn.celess.blog.entity.Response;
import cn.celess.blog.entity.request.CommentReq;
import cn.celess.blog.service.CommentService;
import cn.celess.blog.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -26,76 +24,96 @@ public class CommentController {
*/
@PostMapping("/user/comment/create")
public Response addOne(@RequestBody CommentReq reqBody) {
return ResponseUtil.success(commentService.create(reqBody));
return Response.success(commentService.create(reqBody));
}
@DeleteMapping("/user/comment/del")
public Response delete(@RequestParam("id") long id) {
return ResponseUtil.success(commentService.delete(id));
return Response.success(commentService.delete(id));
}
@PutMapping("/user/comment/update")
public Response update(@RequestBody CommentReq reqBody) {
return ResponseUtil.success(commentService.update(reqBody));
return Response.success(commentService.update(reqBody));
}
/**
* 获取所有的一级评论
* 获取所有的评论
*
* @param articleId 文章id
* @param pagePath pagePath
* @param count 单页数据量
* @param page 页码
* @return Response
*/
@GetMapping("/comments")
public Response commentsOfArticle(@RequestParam("articleId") long articleId,
@GetMapping("/comments/{pagePath}/{pid}")
public Response commentsOfArticle(@PathVariable("pagePath") String pagePath, @PathVariable(value = "pid") long pid,
@RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) {
return ResponseUtil.success(commentService.retrievePageByArticle(articleId, -1, page, count));
String path = "";
if (pagePath.contains("article+")) {
path = "article/" + pagePath.split("\\+", 2)[1];
} else {
path = pagePath;
}
if ("*".equals(pagePath)) {
path = null;
}
return Response.success(commentService.retrievePageByPageAndPid(path, pid, page, count));
}
/**
* 通过pid获取数据
*
* @param pid
* @param count
* @param page
* @return
* @param pagePath pagePath
* @param count count
* @param page page
* @return Response
*/
@GetMapping("/comment/pid/{pid}")
public Response retrievePage(@PathVariable("pid") long pid,
@GetMapping("/comment/pagePath/{pagePath}")
public Response retrievePage(@PathVariable("pagePath") String pagePath,
@RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) {
return ResponseUtil.success(commentService.retrievePageByPid(pid, page, count));
String path = "";
if (pagePath.contains("article+")) {
path = "article/" + pagePath.split("\\+", 2)[1];
} else {
path = pagePath;
}
if ("*".equals(pagePath)) {
path = null;
}
return Response.success(commentService.retrievePage(path, page, count));
}
/**
* 获取所以的一级留言
*
* @param count
* @param page
* @return
*/
@GetMapping("/leaveMsg")
public Response retrievePageOfLeaveMsg(@RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) {
return ResponseUtil.success(commentService.retrievePageByTypeAndPid(false, -1, page, count));
}
@GetMapping("/admin/comment/type/{type}")
public Response retrievePageAdmin(
@PathVariable("type") int isComment,
@GetMapping("/user/comment/pagePath/{pagePath}")
public Response userComment(@PathVariable("pagePath") String pagePath,
@RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) {
return ResponseUtil.success(commentService.retrievePageByType(1 == isComment, page, count));
String path = "";
if (pagePath.contains("article+")) {
path = "article/" + pagePath.split("\\+", 2)[1];
} else {
path = pagePath;
}
if ("*".equals(pagePath)) {
path = null;
}
return Response.success(commentService.retrievePageByAuthor(path, page, count));
}
@GetMapping("/user/comment/type/{type}")
public Response retrievePageByAuthor(
@PathVariable(value = "type") int isComment,
@GetMapping("/admin/comment/pagePath/{pagePath}")
public Response adminComment(@PathVariable("pagePath") String pagePath,
@RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page) {
return ResponseUtil.success(commentService.retrievePageByAuthor(1 == isComment, page, count));
String path = "";
if (pagePath.contains("article+")) {
path = "article/" + pagePath.split("\\+", 2)[1];
} else {
path = pagePath;
}
if ("*".equals(pagePath)) {
path = null;
}
return Response.success(commentService.retrievePageByPage(path, page, count));
}
}

View File

@@ -6,15 +6,19 @@ import cn.celess.blog.entity.model.QiniuResponse;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.service.CountService;
import cn.celess.blog.service.QiniuService;
import cn.celess.blog.util.HttpUtil;
import cn.celess.blog.util.RedisUtil;
import cn.celess.blog.util.ResponseUtil;
import cn.celess.blog.util.VeriCodeUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
@@ -33,7 +37,7 @@ import java.util.concurrent.TimeUnit;
* @date : 2019/04/02 22:03
*/
@RestController
public class Other {
public class CommonController {
public static final Logger logger = LoggerFactory.getLogger(Object.class);
@Autowired
@@ -51,11 +55,10 @@ public class Other {
Map<String, Long> countMap = new HashMap<>();
countMap.put("articleCount", countService.getArticleCount());
countMap.put("commentCount", countService.getCommentCount());
countMap.put("leaveMsgCount", countService.getLeaveMessageCount());
countMap.put("categoryCount", countService.getCategoriesCount());
countMap.put("tagCount", countService.getTagsCount());
countMap.put("visitorCount", countService.getVisitorCount());
return ResponseUtil.success(countMap);
return Response.success(countMap);
}
@@ -70,12 +73,13 @@ public class Other {
Map<String, Object> map = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
String str = null;
while ((str = headerNames.nextElement()) != null) {
while (headerNames.hasMoreElements()) {
str = headerNames.nextElement();
map.put(str, request.getHeader(str));
}
map.put("sessionID", request.getSession().getId());
map.put("request.getRemoteAddr()", request.getRemoteAddr());
return ResponseUtil.success(map);
return Response.success(map);
}
/**
@@ -118,10 +122,10 @@ public class Other {
if (code.equals(codeStr)) {
request.getSession().removeAttribute("code");
request.getSession().setAttribute("verImgCodeStatus", true);
return ResponseUtil.success("验证成功");
return Response.success("验证成功");
} else {
request.getSession().removeAttribute("code");
return ResponseUtil.failure("验证失败,请重新获取验证码");
return Response.failure("验证失败,请重新获取验证码");
}
}
@@ -158,7 +162,7 @@ public class Other {
if (".png".equals(mime.toLowerCase()) || ".jpg".equals(mime.toLowerCase()) ||
".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) {
QiniuResponse qiniuResponse = qiniuService.uploadFile(file.getInputStream(), "img_" + System.currentTimeMillis() + mime);
jsonObject.put("success", 0);
jsonObject.put("success", 1);
jsonObject.put("message", "上传成功");
jsonObject.put("url", "http://cdn.celess.cn/" + qiniuResponse.key);
response.getWriter().println(jsonObject.toString());
@@ -169,4 +173,18 @@ public class Other {
jsonObject.put("message", "上传失败,请上传图片文件");
response.getWriter().println(jsonObject.toString());
}
@GetMapping("/bingPic")
public Response bingPic() {
JSONObject imageObj;
try {
imageObj = JSONObject.fromObject(HttpUtil.get("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN"));
} catch (IOException e) {
return Response.failure(null);
}
JSONArray jsonArray = imageObj.getJSONArray("images");
String imageName = jsonArray.getJSONObject(0).getString("url");
return Response.success("https://cn.bing.com" + imageName);
}
}

View File

@@ -7,10 +7,9 @@ import cn.celess.blog.entity.request.LinkReq;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.service.MailService;
import cn.celess.blog.service.PartnerSiteService;
import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.RedisUtil;
import cn.celess.blog.util.RegexUtil;
import cn.celess.blog.util.ResponseUtil;
import cn.celess.blog.util.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.*;
@@ -37,17 +36,17 @@ public class LinksController {
@PostMapping("/admin/links/create")
public Response create(@RequestBody LinkReq reqBody) {
return ResponseUtil.success(partnerSiteService.create(reqBody));
return Response.success(partnerSiteService.create(reqBody));
}
@DeleteMapping("/admin/links/del/{id}")
public Response del(@PathVariable("id") long id) {
return ResponseUtil.success(partnerSiteService.del(id));
return Response.success(partnerSiteService.del(id));
}
@PutMapping("/admin/links/update")
public Response update(@RequestBody LinkReq reqBody) {
return ResponseUtil.success(partnerSiteService.update(reqBody));
return Response.success(partnerSiteService.update(reqBody));
}
@GetMapping("/links")
@@ -60,13 +59,13 @@ public class LinksController {
sites.add(p);
}
}
return ResponseUtil.success(sites);
return Response.success(sites);
}
@GetMapping("/admin/links")
public Response all(@RequestParam("page") int page,
@RequestParam("count") int count) {
return ResponseUtil.success(partnerSiteService.PartnerSitePages(page, count));
return Response.success(partnerSiteService.partnerSitePages(page, count));
}
@PostMapping("/apply")
@@ -74,10 +73,10 @@ public class LinksController {
@RequestParam("url") String url) {
// TODO :: 弃用发送邮件的方式。
if (name == null || name.replaceAll(" ", "").isEmpty()) {
return ResponseUtil.response(ResponseEnum.PARAMETERS_ERROR, null);
return Response.response(ResponseEnum.PARAMETERS_ERROR, null);
}
if (!RegexUtil.urlMatch(url)) {
return ResponseUtil.response(ResponseEnum.PARAMETERS_URL_ERROR, null);
return Response.response(ResponseEnum.PARAMETERS_URL_ERROR, null);
}
String applyTimeStr = redisUtil.get(request.getRemoteAddr() + "-Apply");
int applyTime = 0;
@@ -93,7 +92,6 @@ public class LinksController {
message.setText("name:" + name + "\nurl:" + url + "\n" + DateFormatUtil.getNow());
Boolean send = mailService.send(message);
redisUtil.setEx(request.getRemoteAddr() + "-Apply", applyTime + 1 + "", 2, TimeUnit.HOURS);
return send ? ResponseUtil.success("") : ResponseUtil.failure("");
return send ? Response.success("") : Response.failure("");
}
}

View File

@@ -1,9 +1,8 @@
package cn.celess.blog.controller;
import cn.celess.blog.entity.Response;
import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.TagModel;
import cn.celess.blog.service.TagService;
import cn.celess.blog.util.ResponseUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -23,48 +22,37 @@ public class TagController {
@PostMapping("/admin/tag/create")
public Response addOne(@RequestParam("name") String name) {
return ResponseUtil.success(tagService.create(name));
return Response.success(tagService.create(name));
}
@DeleteMapping("/admin/tag/del")
public Response delOne(@RequestParam("id") long id) {
return ResponseUtil.success(tagService.delete(id));
return Response.success(tagService.delete(id));
}
@PutMapping("/admin/tag/update")
public Response updateOne(@RequestParam("id") Long id, @RequestParam("name") String name) {
return ResponseUtil.success(tagService.update(id, name));
}
@GetMapping("/tag/id/{id}")
public Response retrieveOneById(@PathVariable("id") long id) {
return ResponseUtil.success(tagService.retrieveOneById(id));
}
@GetMapping("/tag/name/{name}")
public Response retrieveOneByName(@PathVariable("name") String name) {
return ResponseUtil.success(tagService.retrieveOneByName(name));
return Response.success(tagService.update(id, name));
}
@GetMapping("/tags")
public Response getPage(@RequestParam(required = false, defaultValue = "10", value = "count") int count,
@RequestParam(required = false, defaultValue = "1", value = "page") int page) {
return ResponseUtil.success(tagService.retrievePage(page, count));
return Response.success(tagService.retrievePage(page, count));
}
@GetMapping("/tags/nac")
public Response getTagNameAndCount() {
List<JSONObject> nameAndCount = new ArrayList<>();
List<Tag> all = tagService.findAll();
for (Tag t : all) {
List<TagModel> all = tagService.findAll();
for (TagModel t : all) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", t.getName());
String articles = t.getArticles();
jsonObject.put("size", articles == null ? 0 : articles.split(",").length);
jsonObject.put("size", t.getArticles().size());
nameAndCount.add(jsonObject);
}
return ResponseUtil.success(nameAndCount);
return Response.success(nameAndCount);
}
}

View File

@@ -4,7 +4,6 @@ import cn.celess.blog.entity.Response;
import cn.celess.blog.entity.request.LoginReq;
import cn.celess.blog.entity.request.UserReq;
import cn.celess.blog.service.UserService;
import cn.celess.blog.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@@ -23,28 +22,28 @@ public class UserController {
@PostMapping("/login")
public Response login(@RequestBody LoginReq loginReq) {
return ResponseUtil.success(userService.login(loginReq));
return Response.success(userService.login(loginReq));
}
@PostMapping("/registration")
public Response registration(@RequestParam("email") String email,
@RequestParam("password") String password) {
return ResponseUtil.success(userService.registration(email, password));
return Response.success(userService.registration(email, password));
}
@GetMapping("/logout")
public Response logout() {
return ResponseUtil.success(userService.logout());
return Response.success(userService.logout());
}
@PutMapping("/user/userInfo/update")
public Response updateInfo(String desc, String displayName) {
return ResponseUtil.success(userService.update(desc, displayName));
return Response.success(userService.update(desc, displayName));
}
@GetMapping("/user/userInfo")
public Response getUserInfo() {
return ResponseUtil.success(userService.getUserInfoBySession());
return Response.success(userService.getUserInfoBySession());
}
/**
@@ -58,7 +57,7 @@ public class UserController {
@ResponseBody
public Response upload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return ResponseUtil.failure("上传失败,请选择文件");
return Response.failure("上传失败,请选择文件");
}
String fileName = file.getOriginalFilename();
String mime = fileName.substring(fileName.lastIndexOf("."));
@@ -66,56 +65,64 @@ public class UserController {
".jpeg".equals(mime.toLowerCase()) || ".bmp".equals(mime.toLowerCase())) {
return (Response) userService.updateUserAavatarImg(file.getInputStream(), mime);
}
return ResponseUtil.failure("请上传图片文件");
return Response.failure("请上传图片文件");
}
@PostMapping("/sendResetPwdEmail")
public Response sendResetPwdEmail(@RequestParam("email") String email) {
return ResponseUtil.success(userService.sendResetPwdEmail(email));
return Response.success(userService.sendResetPwdEmail(email));
}
@PostMapping("/sendVerifyEmail")
public Response sendVerifyEmail(@RequestParam("email") String email) {
return ResponseUtil.success(userService.sendVerifyEmail(email));
return Response.success(userService.sendVerifyEmail(email));
}
@PostMapping("/emailVerify")
public Response emailVerify(@RequestParam("verifyId") String verifyId,
@RequestParam("email") String mail) {
return ResponseUtil.success(userService.verifyEmail(verifyId, mail));
return Response.success(userService.verifyEmail(verifyId, mail));
}
@PostMapping("/resetPwd")
public Response resetPwd(@RequestParam("verifyId") String verifyId,
@RequestParam("email") String email,
@RequestParam("pwd") String pwd) {
return ResponseUtil.success(userService.reSetPwd(verifyId, email, pwd));
return Response.success(userService.reSetPwd(verifyId, email, pwd));
}
@PostMapping("/user/setPwd")
public Response setPwd(@RequestParam("pwd") String pwd,
@RequestParam("newPwd") String newPwd,
@RequestParam("confirmPwd") String confirmPwd) {
return Response.success(userService.setPwd(pwd, newPwd, confirmPwd));
}
@DeleteMapping("/admin/user/delete")
public Response multipleDelete(@RequestBody Integer[] ids) {
return ResponseUtil.success(userService.deleteUser(ids));
return Response.success(userService.deleteUser(ids));
}
@DeleteMapping("/admin/user/delete/{id}")
public Response delete(@PathVariable("id") Integer id) {
return ResponseUtil.success(userService.deleteUser(new Integer[]{id}));
return Response.success(userService.deleteUser(new Integer[]{id}));
}
@PutMapping("/admin/user")
public Response updateInfoByAdmin(@RequestBody UserReq user) {
return ResponseUtil.success(userService.adminUpdate(user));
return Response.success(userService.adminUpdate(user));
}
@GetMapping("/admin/users")
public Response getAllUser(@RequestParam("page") int pageNum, @RequestParam("count") int count) {
return ResponseUtil.success(userService.getUserList(pageNum, count));
return Response.success(userService.getUserList(pageNum, count));
}
@GetMapping("/emailStatus/{email}")
public Response getEmailStatus(@PathVariable("email") String email) {
return ResponseUtil.success(userService.getStatusOfEmail(email));
return Response.success(userService.getStatusOfEmail(email));
}

View File

@@ -3,7 +3,6 @@ package cn.celess.blog.controller;
import cn.celess.blog.entity.Response;
import cn.celess.blog.service.CountService;
import cn.celess.blog.service.VisitorService;
import cn.celess.blog.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -22,29 +21,29 @@ public class VisitorController {
@GetMapping("/visitor/count")
public Response getVisitorCount() {
return ResponseUtil.success(countService.getVisitorCount());
return Response.success(countService.getVisitorCount());
}
@GetMapping("/admin/visitor/page")
public Response page(@RequestParam(value = "count", required = false, defaultValue = "10") int count,
@RequestParam(value = "page", required = false, defaultValue = "1") int page,
@RequestParam(value = "showLocation", required = false, defaultValue = "false") boolean showLocation) {
return ResponseUtil.success(visitorService.visitorPage(page, count, showLocation));
return Response.success(visitorService.visitorPage(page, count, showLocation));
}
@PostMapping("/visit")
public Response add(HttpServletRequest request) {
return ResponseUtil.success(visitorService.addVisitor(request));
return Response.success(visitorService.addVisitor(request));
}
@GetMapping("/dayVisitCount")
public Response dayVisitCount() {
return ResponseUtil.success(countService.getDayVisitCount());
return Response.success(countService.getDayVisitCount());
}
@GetMapping("/ip/{ip}")
public Response ipLocation(@PathVariable("ip") String ip) {
return ResponseUtil.success(visitorService.location(ip));
return Response.success(visitorService.location(ip));
}
/**
@@ -55,6 +54,6 @@ public class VisitorController {
*/
@GetMapping("/ip")
public Response getIp(HttpServletRequest request) {
return ResponseUtil.success(request.getRemoteAddr());
return Response.success(request.getRemoteAddr());
}
}

View File

@@ -2,7 +2,6 @@ package cn.celess.blog.controller;
import cn.celess.blog.entity.Response;
import cn.celess.blog.service.WebUpdateInfoService;
import cn.celess.blog.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@@ -17,31 +16,32 @@ public class WebUpdateInfoController {
@PostMapping("/admin/webUpdate/create")
public Response create(@RequestParam("info") String info) {
return ResponseUtil.success(webUpdateInfoService.create(info));
return Response.success(webUpdateInfoService.create(info));
}
@DeleteMapping("/admin/webUpdate/del/{id}")
public Response del(@PathVariable("id") long id) {
return ResponseUtil.success(webUpdateInfoService.del(id));
return Response.success(webUpdateInfoService.del(id));
}
@PutMapping("/admin/webUpdate/update")
public Response update(@RequestParam("id") long id, @RequestParam("info") String info) {
return ResponseUtil.success(webUpdateInfoService.update(id, info));
return Response.success(webUpdateInfoService.update(id, info));
}
@GetMapping("/webUpdate")
public Response findAll() {
return ResponseUtil.success(webUpdateInfoService.findAll());
return Response.success(webUpdateInfoService.findAll());
}
@GetMapping("/webUpdate/pages")
public Response page(@RequestParam("page") int page, @RequestParam("count") int count) {
return ResponseUtil.success(webUpdateInfoService.pages(count, page));
return Response.success(webUpdateInfoService.pages(count, page));
}
@GetMapping("/lastestUpdateTime")
@GetMapping("/lastestUpdate")
public Response lastestUpdateTime() {
return ResponseUtil.success(webUpdateInfoService.getLastestUpdateTime());
return Response.success(webUpdateInfoService.getLastestUpdateTime());
}

View File

@@ -0,0 +1,23 @@
package cn.celess.blog.enmu;
import lombok.Getter;
/**
* @Author: 小海
* @Date: 2020-05-25 08:58
* @Desc:
*/
@Getter
public enum CommentStatusEnum {
// 正常
NORMAL(0, "正常"),
DELETED(3, "已删除");
private final int code;
private final String msg;
CommentStatusEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
}

View File

@@ -1,27 +0,0 @@
package cn.celess.blog.enmu;
import lombok.Getter;
/**
* @Author: 小海
* @Date 2019/06/29 00:00
* @Description 文章数据模型转换的级别(响应参数的选择)
*/
@Getter
public enum LevelEnum {
//低级
LOW(0),
//中级
MIDDLE(1),
//另一个级别的转化
BETWEEN_M_AND_H(2),
//高级
HEIGHT(3);
private int levelCode;
LevelEnum(int levelCode) {
this.levelCode = levelCode;
}
}

View File

@@ -11,59 +11,68 @@ public enum ResponseEnum {
FAILURE(-1, "失败"),
ERROR(-2, "错误"),
DATA_IS_DELETED(1000, "数据已被删除"),
//文章类
ARTICLE_NOT_EXIST(201, "文章不存在"),
ARTICLE_HAS_EXIST(202, "文章已存在"),
ARTICLE_NOT_PUBLIC(203, "文章暂未公开"),
ARTICLE_NOT_BELONG_YOU(204, "无权限操作别人的文章"),
ARTICLE_NOT_EXIST(2010, "文章不存在"),
ARTICLE_HAS_EXIST(2020, "文章已存在"),
ARTICLE_NOT_PUBLIC(2030, "文章暂未公开"),
ARTICLE_NOT_BELONG_YOU(2040, "无权限操作别人的文章"),
//用户类
HAVE_NOT_LOG_IN(301, "还未登录"),
PERMISSION_ERROR(302, "没有此权限"),
USER_NOT_EXIST(303, "用户不存在"),
USERNAME_HAS_EXIST(304, "用户名已存在"),
USERNAME_TOO_SHORT(305, "用户名太短"),
PASSWORD_TOO_SHORT_OR_LONG(306, "密码长度过长或者过短"),
LOGIN_FAILURE(310, "登录失败,用户名/密码不正确"),
USEREMAIL_NULL(331, "未设置邮箱"),
USEREMAIL_NOT_VERIFY(332, "邮箱未验证"),
LOGIN_LATER(350, "错误次数已达5次请稍后再试"),
PWD_SAME(360, "新密码与原密码相同"),
LOGIN_EXPIRED(370, "登陆过期"),
HAVE_NOT_LOG_IN(3010, "还未登录"),
PERMISSION_ERROR(3020, "没有此权限"),
USER_NOT_EXIST(3030, "用户不存在"),
USERNAME_HAS_EXIST(3040, "用户名已存在"),
USERNAME_TOO_SHORT(3050, "用户名太短"),
PASSWORD_TOO_SHORT_OR_LONG(3060, "密码长度过长或者过短"),
LOGIN_FAILURE(3100, "登录失败,用户名/密码不正确"),
USEREMAIL_NULL(3310, "未设置邮箱"),
USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"),
LOGIN_LATER(3500, "错误次数已达5次请稍后再试"),
PWD_SAME(3601, "新密码与原密码相同"),
PWD_NOT_SAME(3602, "新密码与原密码不相同"),
LOGIN_EXPIRED(3700, "登陆过期"),
LOGOUT(3710, "账户已注销"),
PWD_WRONG(3800, "密码不正确"),
JWT_EXPIRED(3810, "Token过期"),
JWT_MALFORMED(3820, "Token格式不对"),
JWT_SIGNATURE(3830, "Token签名错误"),
JWT_NOT_SUPPORT(3840, "不支持的Token"),
//标签
TAG_NOT_EXIST(401, "标签不存在"),
TAG_HAS_EXIST(402, "标签已存在"),
TAG_NOT_EXIST(4010, "标签不存在"),
TAG_HAS_EXIST(4020, "标签已存在"),
//分类
CATEGORY_NOT_EXIST(501, "分类不存在"),
CATEGORY_HAS_EXIST(502, "分类已存在"),
CATEGORY_NOT_EXIST(5010, "分类不存在"),
CATEGORY_HAS_EXIST(5020, "分类已存在"),
//评论/留言
COMMENT_NOT_EXIST(601, "评论/留言不存在"),
COMMENT_HAS_EXIST(602, "评论/留言已存在,请不要重复提交"),
COMMENT_NOT_EXIST(6010, "评论/留言不存在"),
COMMENT_HAS_EXIST(6020, "评论/留言已存在,请不要重复提交"),
//webUdpateInfo amd PartnerSite
DATA_NOT_EXIST(701, "数据不存在"),
DATA_HAS_EXIST(702, "数据已存在"),
DATA_NOT_EXIST(7010, "数据不存在"),
DATA_HAS_EXIST(7020, "数据已存在"),
//其他
//提交更新之前,没有获取数据/,
DID_NOT_GET_THE_DATA(802, "非法访问"),
IMG_CODE_TIMEOUT(810, "验证码已失效"),
IMG_CODE_DIDNOTVERIFY(820, "请先验证验证码"),
VERIFY_ERROR(830, "验证失败"),
PARAMETERS_ERROR(850, "参数错误"),
PARAMETERS_URL_ERROR(851, "链接格式错误"),
PARAMETERS_EMAIL_ERROR(852, "邮箱格式错误"),
PARAMETERS_PHONE_ERROR(853, "手机格式错误"),
PARAMETERS_QQ_ERROR(854, "QQ格式错误"),
PARAMETERS_PWD_ERROR(855, "密码格式错误"),
VERIFY_OUT(840, "已经验证过了");
private int code;
private String msg;
DID_NOT_GET_THE_DATA(8020, "非法访问"),
IMG_CODE_TIMEOUT(8100, "验证码已失效"),
IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"),
VERIFY_ERROR(8300, "验证失败"),
PARAMETERS_ERROR(8500, "参数错误"),
PARAMETERS_URL_ERROR(8510, "链接格式错误"),
PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"),
PARAMETERS_PHONE_ERROR(8530, "手机格式错误"),
PARAMETERS_QQ_ERROR(8540, "QQ格式错误"),
PARAMETERS_PWD_ERROR(8550, "密码格式错误"),
VERIFY_OUT(8400, "已经验证过了");
private final int code;
private final String msg;
ResponseEnum(int code, String msg) {

View File

@@ -0,0 +1,23 @@
package cn.celess.blog.enmu;
import lombok.Getter;
/**
* @Author: 小海
* @Date: 2020-05-24 16:31
* @Desc:
*/
@Getter
public enum RoleEnum {
// admin 权限
ADMIN_ROLE("admin"),
// user 权限
USER_ROLE("user");
private final String roleName;
RoleEnum(String roleName) {
this.roleName = roleName;
}
}

View File

@@ -0,0 +1,39 @@
package cn.celess.blog.enmu;
/**
* @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;
}
}

View File

@@ -3,6 +3,7 @@ package cn.celess.blog.entity;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* @author : xiaohai
@@ -41,16 +42,6 @@ public class Article {
private Date updateDate = null;
private Long categoryId;
private String tagsId;
private Long authorId;
private Long preArticleId;
private Long nextArticleId;
private Long readingNumber;
/**
@@ -58,4 +49,15 @@ public class Article {
*/
private Boolean open;
private Category category;
private List<Tag> tags;
private Integer likeCount;
private Integer dislikeCount;
private User user;
private boolean deleted = false;
}

View File

@@ -0,0 +1,26 @@
package cn.celess.blog.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author: 小海
* @Date: 2020-05-24 14:52
* @Desc:
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ArticleTag {
private Long id;
private Article article;
private TagCategory tag;
public ArticleTag(Article article, TagCategory tag) {
this.article = article;
this.tag = tag;
}
}

View File

@@ -1,20 +1,14 @@
package cn.celess.blog.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author : xiaohai
* @date : 2019/03/28 22:18
*/
@Data
public class Category {
private Long id;
private String name;
private String articles;
@NoArgsConstructor
public class Category extends TagCategory {
public Category(String name) {
super.setName(name);
}
}

View File

@@ -14,27 +14,21 @@ public class Comment {
private Long id;
/**
* 是评论还是留言 0:评论 其他1留言
*/
private Boolean type;
private int status;
private Long authorID;
private String pagePath;
private String content;
private Long articleID;
private Date date;
/**
* 回应着ID 默认为顶级回复
*/
private String responseId = "";
private User fromUser;
private User toUser;
/**
* 评论的父ID
*/
private Long pid;
// private boolean delete;
}

View File

@@ -19,6 +19,12 @@ public class PartnerSite {
private Boolean open;
private String iconPath;
private String desc;
private Boolean delete = false;
public PartnerSite() {
}

View File

@@ -1,5 +1,6 @@
package cn.celess.blog.entity;
import cn.celess.blog.enmu.ResponseEnum;
import lombok.Data;
import net.sf.json.JSONObject;
@@ -10,20 +11,49 @@ import java.io.Serializable;
* @date : 2019/03/28 15:24
*/
@Data
public class Response implements Serializable {
public class Response<T> implements Serializable {
private int code;
private String msg;
private Object result;
private long date;
private T result;
public Response() {
}
public Response(int code, String msg, Object result, long date) {
public Response(int code, String msg, T result) {
this.code = code;
this.msg = msg;
this.result = result;
this.date = date;
}
/**
* 成功相应
*
* @param result 结果
* @return Response
*/
public static Response success(Object result) {
return new Response(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), result);
}
/**
* 失败的响应
*
* @param result 结果
* @return Response
*/
public static Response failure(String result) {
return new Response(ResponseEnum.FAILURE.getCode(), ResponseEnum.FAILURE.getMsg(), result);
}
/**
* 其他的响应
*
* @param r 枚举常量
* @param result 结果
* @return Response
*/
public static Response response(ResponseEnum r, String result) {
return new Response(r.getCode(), r.getMsg(), result);
}
@Override

View File

@@ -1,16 +1,15 @@
package cn.celess.blog.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author : xiaohai
* @date : 2019/03/28 22:19
*/
@Data
public class Tag {
private Long id;
@NoArgsConstructor
public class Tag extends TagCategory {
private String name;
private String articles;
public Tag(String name) {
super.setName(name);
}
}

View File

@@ -0,0 +1,19 @@
package cn.celess.blog.entity;
import lombok.Data;
/**
* @Author: 小海
* @Date: 2020-05-24 14:03
* @Desc:
*/
@Data
public class TagCategory {
private Long id;
private String name;
private Boolean category = true;
private Boolean deleted = false;
}

View File

@@ -2,6 +2,7 @@ package cn.celess.blog.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@@ -10,6 +11,7 @@ import java.util.Date;
* @date : 2019/03/28 14:52
*/
@Data
@NoArgsConstructor
public class User {
private Long id;
@@ -18,12 +20,6 @@ public class User {
*/
private String email;
/**
* 用户唯一标识码
*/
@JsonIgnore
private String uid;
/**
* 密码
*/
@@ -46,15 +42,12 @@ public class User {
private Date recentlyLandedDate;
/**
* 随机码 用户验证邮箱/找回密码
* 暂时废弃这一字段
*/
private String emailVerifyId;
private String role = "user";
public User() {
}
private int status;
public User(String email, String pwd) {
this.email = email;
this.pwd = pwd;
}
}

View File

@@ -15,6 +15,7 @@ public class Visitor {
private String ip;
private Date date;
private String ua;
private boolean delete;
public Visitor(String ip, Date date, String ua) {
this.ip = ip;

View File

@@ -17,11 +17,12 @@ public class WebUpdate {
private Date updateTime;
private boolean delete;
public WebUpdate() {
}
public WebUpdate(String updateInfo, Date updateTime) {
public WebUpdate(String updateInfo) {
this.updateInfo = updateInfo;
this.updateTime = updateTime;
}
}

View File

@@ -1,9 +1,10 @@
package cn.celess.blog.entity.model;
import cn.celess.blog.entity.Tag;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
/**
* @author : xiaohai
@@ -57,40 +58,30 @@ public class ArticleModel {
/**
* 标签
*/
private String[] tags;
private List<Tag> tags;
/**
* 作者
*/
private Long authorId;
private UserModel author;
/**
* 作者名字
*/
private String authorName;
private ArticleModel preArticle;
/**
* 上一篇文章
*/
private Long preArticleId;
/**
* 下一篇文章
*/
private Long nextArticleId;
private String preArticleTitle;
private String nextArticleTitle;
private ArticleModel nextArticle;
/**
* 阅读数
*/
private Long readingNumber;
private Integer likeCount;
private Integer dislikeCount;
/**
* 文章的状态 true公开 false:不公开
*/
private Boolean open;
private boolean deleted;
}

View File

@@ -0,0 +1,24 @@
package cn.celess.blog.entity.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @Author: 小海
* @Date: 2020-03-29 12:18
* @Desc:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CategoryModel {
private Long id;
private String name;
private List<ArticleModel> articles;
private boolean deleted;
}

View File

@@ -3,7 +3,7 @@ package cn.celess.blog.entity.model;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
import java.util.List;
/**
* @author : xiaohai
@@ -14,44 +14,31 @@ import java.util.Date;
public class CommentModel {
private long id;
/**
* 是评论还是留言 0:评论 其他1留言
*/
private boolean isComment;
private UserModel fromUser;
private String authorName;
private String authorAvatarImgUrl;
private UserModel toUser;
/**
* 内容
*/
private String content;
/**
* 文章ID
*/
private long articleID;
/**
* 文章标题
*/
private String articleTitle;
private String pagePath;
/**
* 发布日期
*/
private String date;
/**
* 回应着ID 默认为顶级回复
*/
private String responseId = "";
/**
* 评论的父ID
*/
private long pid = -1;
private Long pid;
private List<CommentModel> respComment;
private int status;
}

View File

@@ -0,0 +1,38 @@
package cn.celess.blog.entity.model;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @Author: 小海
* @Date: 2020-05-25 17:13
* @Desc:
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageData<T> {
private List<T> list;
private long total;
private int pageSize;
private int pageNum;
public PageData(PageInfo pageInfo) {
this.pageNum = pageInfo.getPageNum();
this.pageSize = pageInfo.getPageSize();
this.total = pageInfo.getTotal();
}
public PageData(PageInfo pageInfo, List<T> data) {
this(pageInfo);
this.list = data;
}
}

View File

@@ -0,0 +1,25 @@
package cn.celess.blog.entity.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @Author: 小海
* @Date: 2020-03-29 13:56
* @Desc:
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TagModel {
private Long id;
private String name;
private List<ArticleModel> articles;
private boolean deleted;
}

View File

@@ -37,4 +37,6 @@ public class UserModel {
private String role = "user";
private String token;
private int status;
}

View File

@@ -21,4 +21,6 @@ public class WebUpdateModel {
this.info = info;
this.time = time;
}
private boolean deleted;
}

View File

@@ -11,7 +11,7 @@ public class ArticleReq {
private Long id;
private String title;
private String mdContent;
private String tags;
private String[] tags;
private Boolean type;
private String url;
private String category;

View File

@@ -9,9 +9,8 @@ import lombok.Data;
@Data
public class CommentReq {
private Long id;
private Boolean comment;
private String content;
private Long pid;
private Long articleID;
private String responseId;
private long pid = -1;
private String pagePath;
private long toUserId = -1;
}

View File

@@ -11,5 +11,7 @@ public class LinkReq {
private long id;
private String name;
private String url;
private String iconPath;
private String desc;
private boolean open;
}

View File

@@ -26,12 +26,11 @@ import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class ExceptionHandle {
public static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@Autowired
MailService mailService;
@Autowired
HttpServletRequest request;
public static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@Value("${spring.profiles.active}")
private String activeModel;
@@ -41,27 +40,27 @@ public class ExceptionHandle {
//自定义错误
if (e instanceof MyException) {
logger.debug("返回了自定义的exception,[code={},msg={}]", ((MyException) e).getCode(), e.getMessage());
return new Response(((MyException) e).getCode(), e.getMessage(), null, System.currentTimeMillis());
return new Response(((MyException) e).getCode(), e.getMessage(), null);
}
//请求路径不支持该方法
if (e instanceof HttpRequestMethodNotSupportedException) {
logger.debug("遇到请求路径与请求方法不匹配的请求,[msg={}path:{},method:{}]", e.getMessage(), request.getRequestURL(), request.getMethod());
return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null, System.currentTimeMillis());
return new Response(ResponseEnum.ERROR.getCode(), e.getMessage(), null);
}
//数据输入类型不匹配
if (e instanceof MethodArgumentTypeMismatchException) {
logger.debug("输入类型不匹配,[msg={}]", e.getMessage());
return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null, System.currentTimeMillis());
return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改后再访问", null);
}
//数据验证失败
if (e instanceof BindException) {
logger.debug("数据验证失败,[msg={}]", e.getMessage());
return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null, System.currentTimeMillis());
return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入有问题,请修改", null);
}
//数据输入不完整
if (e instanceof MissingServletRequestParameterException) {
logger.debug("数据输入不完整,[msg={}]", e.getMessage());
return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null, System.currentTimeMillis());
return new Response(ResponseEnum.PARAMETERS_ERROR.getCode(), "数据输入不完整,请检查", null);
}
// 发送错误信息到邮箱
@@ -70,7 +69,7 @@ public class ExceptionHandle {
sendMessage(e);
}
e.printStackTrace();
return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null, System.currentTimeMillis());
return new Response(ResponseEnum.ERROR.getCode(), "服务器出现错误,已记录", null);
}
/**

View File

@@ -1,7 +1,7 @@
package cn.celess.blog.mapper;
import cn.celess.blog.entity.Article;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@@ -21,21 +21,15 @@ public interface ArticleMapper {
int update(Article a);
int updateNextArticleId(long targetArticleID, long nextArticleID);
int updatePreArticleId(long targetArticleID, long preArticleID);
long getLastestArticleId();
Article getLastestArticle();
Article findArticleById(long id);
boolean existsByTitle(String title);
boolean existsById(long id);
boolean isDeletedById(long id);
List<Article> findAllByAuthorId(long authorID);
List<Article> findAllByAuthorId(long authorId);
List<Article> findAllByOpen(boolean isOpen);
@@ -43,15 +37,15 @@ public interface ArticleMapper {
List<Article> findAllByCategoryId(long id);
List<Article> findAllByCategoryIdAndOpen(long id);
List<Article> findAll();
Article getSimpleInfo(long id);
Article getPreArticle(Long id);
List<Article> getSimpleInfoByCategory(long categoryId);
Article getNextArticle(Long id);
List<Article> getSimpleInfoByTag(List<String> idList);
int setReadingNumber(long number, long id);
int updateReadingNumber(long id);
long count();

View File

@@ -0,0 +1,35 @@
package cn.celess.blog.mapper;
import cn.celess.blog.entity.ArticleTag;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @Author: 小海
* @Date: 2020-05-24 14:21
* @Desc:
*/
@Mapper
@Repository
public interface ArticleTagMapper {
int insert(ArticleTag articleTag);
int update(ArticleTag articleTag);
ArticleTag findOneById(Long id);
int deleteById(Long id);
int deleteByArticleId(Long articleId);
List<ArticleTag> findAllByArticleId(Long articleId);
int deleteMultiById(List<ArticleTag> articleTags);
List<ArticleTag> findArticleByTag(Long tagId);
List<ArticleTag> findArticleByTagAndOpen(Long tagId);
}

View File

@@ -34,7 +34,7 @@ public interface CategoryMapper {
String getNameById(long id);
Long getIDByName(String name);
Long getIdByName(String name);
Category getLastestCategory();

View File

@@ -8,8 +8,8 @@ import java.util.List;
/**
* @Author: 小海
* @Date 2019/06/30 16:19
* @Description
* @Date: 2019/06/30 16:19
* @Description:
*/
@Mapper
@Repository
@@ -18,11 +18,9 @@ public interface CommentMapper {
int updateContent(String content, long id);
int updateResponder(String responder, long id);
int delete(long id);
int deleteByArticleId(long articleId);
int deleteByPagePath(String pagePath);
boolean existsById(long id);
@@ -30,19 +28,17 @@ public interface CommentMapper {
Comment getLastestComment();
List<Comment> findAllByAuthorIDAndType(long id, boolean isComment);
List<Comment> findAllByFromUser(long id);
List<Comment> findAllByPId(long pid);
List<Comment> findAllByPid(long pid);
List<Comment> findAllByArticleID(long articleId);
List<Comment> findAllByPagePath(String pagePath);
List<Comment> findAllByArticleIDAndPId(long articleID, long pid);
List<Comment> findAllByPagePathAndFromUser(String pagePath, long userId);
List<Comment> findCommentsByTypeAndPId(boolean isComment, long pid);
List<Comment> findAllByPagePathAndPidAndNormal(String pagePath, long pid);
List<Comment> findAllByPId(int pid);
long countByPagePath(String pagePath);
List<Comment> findAllByType(boolean isComment);
long countByType(boolean isComment);
long count();
}

View File

@@ -26,10 +26,6 @@ public interface TagMapper {
Boolean existsByName(String name);
Long getIDByName(String name);
String getNameById(long id);
Tag getLastestTag();
List<Tag> findAll();

View File

@@ -4,7 +4,6 @@ import cn.celess.blog.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
/**
@@ -16,13 +15,13 @@ import java.util.List;
@Repository
public interface UserMapper {
int addUser(String email, String pwd);
int addUser(User user);
int updateInfo(String desc, String displayName, long id);
int updateAvatarImgUrl(String avatarImgUrl, long id);
int updateLoginTime(String email, Date date);
int updateLoginTime(String email);
int updateEmailStatus(String email, boolean status);
@@ -50,7 +49,9 @@ public interface UserMapper {
int delete(long id);
int setUserRole(Long uid, String role);
int lock(long id);
int setUserRole(Long id, String role);
List<User> findAll();

View File

@@ -20,5 +20,7 @@ public interface VisitorMapper {
List<Visitor> findAll();
List<Visitor> findAllNotDeleted();
long count();
}

View File

@@ -4,7 +4,6 @@ import cn.celess.blog.entity.WebUpdate;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
/**
@@ -27,5 +26,7 @@ public interface WebUpdateInfoMapper {
List<WebUpdate> findAll();
Date getLastestOne();
List<WebUpdate> findAllNotDeleted();
WebUpdate getLastestOne();
}

View File

@@ -1,8 +1,8 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.model.ArticleModel;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.request.ArticleReq;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
@@ -39,11 +39,11 @@ public interface ArticleService {
/**
* 获取一篇文章的数据
*
* @param articleID 文章id
* @param articleId 文章id
* @param is4update 是否是因文章更新而请求数据
* @return 文章数据
*/
ArticleModel retrieveOneByID(long articleID, boolean is4update);
ArticleModel retrieveOneById(long articleId, boolean is4update);
/**
* 管理员 获取分页数据
@@ -52,7 +52,7 @@ public interface ArticleService {
* @param page 数据页
* @return 分页数据
*/
PageInfo adminArticles(int count, int page);
PageData<ArticleModel> adminArticles(int count, int page, boolean deleted);
/**
* 获取文章状态为开放的文章
@@ -61,7 +61,7 @@ public interface ArticleService {
* @param page 数据页
* @return 分页数据
*/
PageInfo retrievePageForOpen(int count, int page);
PageData<ArticleModel> retrievePageForOpen(int count, int page);
/**
* 根据分类名获取文章数据
@@ -71,7 +71,7 @@ public interface ArticleService {
* @param page 数据页
* @return 分页数据
*/
PageInfo findByCategory(String name, int page, int count);
PageData<ArticleModel> findByCategory(String name, int page, int count);
/**
* 根据标签名获取文章数据
@@ -81,5 +81,5 @@ public interface ArticleService {
* @param page 数据页
* @return 分页数据
*/
PageInfo findByTag(String name, int page, int count);
PageData<ArticleModel> findByTag(String name, int page, int count);
}

View File

@@ -1,10 +1,9 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.Category;
import cn.celess.blog.entity.model.CategoryModel;
import cn.celess.blog.entity.model.PageData;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author : xiaohai
* @date : 2019/03/28 22:42
@@ -17,15 +16,7 @@ public interface CategoryService {
* @param name 分类名
* @return 所增加的分类数据
*/
Category create(String name);
/**
* 增加一个分类
*
* @param category 分类对象
* @return 所增加的分类数据
*/
Category create(Category category);
CategoryModel create(String name);
/**
* 通过id删除分类
@@ -42,13 +33,13 @@ public interface CategoryService {
* @param name 分类名字
* @return 更新后的分类的数据
*/
Category update(Long id, String name);
CategoryModel update(Long id, String name);
/**
* 获取全部的分类数据
*
* @return 全部的分类数据
*/
List<Category> retrievePage();
PageData<CategoryModel> retrievePage(int page, int count);
}

View File

@@ -1,10 +1,12 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.model.CommentModel;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.request.CommentReq;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author : xiaohai
* @date : 2019/03/29 16:58
@@ -38,64 +40,52 @@ public interface CommentService {
/**
* 分页获取数据
*
* @param isComment true评论 false留言
* @param pagePath pagePath
* @param count 单页数据量
* @param page 数据页
* @return 分页数据
*/
PageInfo<CommentModel> retrievePage(Boolean isComment, int page, int count);
PageData<CommentModel> retrievePage(String pagePath, int page, int count);
/**
* 通过pid获取数据
*
* @param pid 父id
* @param count 单页数据量
* @param page 数据页
* @return 分页数据
*/
PageInfo<CommentModel> retrievePageByPid(long pid, int page, int count);
List<CommentModel> retrievePageByPid(long pid);
/**
* 根据评论者获取数据
*
* @param isComment true评论 false留言
* @param pagePath pagePath
* @param count 单页数据量
* @param page 数据页
* @return 分页数据
*/
PageInfo<CommentModel> retrievePageByAuthor(Boolean isComment, int page, int count);
PageData<CommentModel> retrievePageByAuthor(String pagePath, int page, int count);
/**
* 根据文章获取数据
*
* @param articleID 文章id
* @param pid 父id
* @param count 单页数据量
* @param page 数据页
* @return 分页数据
*/
PageInfo<CommentModel> retrievePageByArticle(long articleID, long pid, int page, int count);
/**
* 根据数据的type和pid获取数据
*
* @param isComment true评论 false留言
* @param pagePath pagePath
* @param pid 父id
* @param count 单页数据量
* @param page 数据页
* @return 分页数据
*/
PageInfo<CommentModel> retrievePageByTypeAndPid(Boolean isComment, int pid, int page, int count);
PageData<CommentModel> retrievePageByPageAndPid(String pagePath, long pid, int page, int count);
/**
* 根据type获取数据
*
* @param isComment true评论 false留言
* @param pagePath pagePath
* @param count 单页数据量
* @param page 数据页
* @return 分页数据
*/
PageInfo<CommentModel> retrievePageByType(Boolean isComment, int page, int count);
PageData<CommentModel> retrievePageByPage(String pagePath, int page, int count);
}

View File

@@ -36,13 +36,6 @@ public interface CountService {
*/
long getTagsCount();
/**
* 获取留言数量
*
* @return 留言数量
*/
long getLeaveMessageCount();
/**
* 获取用户量
*

View File

@@ -1,8 +1,8 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.PartnerSite;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.request.LinkReq;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -44,7 +44,7 @@ public interface PartnerSiteService {
* @param page 数据页
* @return 分页数据
*/
PageInfo<PartnerSite> PartnerSitePages(int page, int count);
PageData<PartnerSite> partnerSitePages(int page, int count);
/**
* 获取全部数据

View File

@@ -1,7 +1,7 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.Tag;
import com.github.pagehelper.PageInfo;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.TagModel;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -18,16 +18,7 @@ public interface TagService {
* @param name 标签名
* @return 新增后的数据
*/
Tag create(String name);
/**
* 新增数据
*
* @param tag tag对象
* @return 新增后的数据
*/
Tag create(Tag tag);
TagModel create(String name);
/**
* 删除数据
@@ -44,24 +35,7 @@ public interface TagService {
* @param name 改名的name值
* @return 更新后的数据
*/
Tag update(Long id, String name);
/**
* 查询单个标签信息
*
* @param tagId id
* @return 标签的数据
*/
Tag retrieveOneById(long tagId);
/**
* 通过name查询标签的信息
*
* @param name tag的名称
* @return 标签数据
*/
Tag retrieveOneByName(String name);
TagModel update(Long id, String name);
/**
* 分页获取标签数据
@@ -70,13 +44,13 @@ public interface TagService {
* @param page 数据页
* @return 分页数据
*/
PageInfo<Tag> retrievePage(int page, int count);
PageData<TagModel> retrievePage(int page, int count);
/**
* 获取全部标签数据
*
* @return 标签数据列表
*/
List<Tag> findAll();
List<TagModel> findAll();
}

View File

@@ -1,16 +1,12 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.User;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.UserModel;
import cn.celess.blog.entity.request.LoginReq;
import cn.celess.blog.entity.request.UserReq;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;
/**
* @author : xiaohai
@@ -42,14 +38,6 @@ public interface UserService {
*/
Object logout();
/**
* 获取用户头像的链接
*
* @param id 用户id
* @return 头像链接
*/
String getAvatarImg(long id);
/**
* 更新用户数据
*
@@ -83,14 +71,6 @@ public interface UserService {
*/
String getUserRoleByEmail(String email);
/**
* 通过邮箱获取用户的信息
*
* @param email 用户邮箱
* @return 用户信息
*/
User getUserInfoByEmail(String email);
/**
* 获取邮箱是否注册过
*
@@ -99,14 +79,6 @@ public interface UserService {
*/
boolean isExistOfEmail(String email);
/**
* 获取用户的name 优先返回displayName 否则返回email
*
* @param id 用户id
* @return name
*/
String getNameById(long id);
/**
* 发送重置密码邮件
*
@@ -157,7 +129,7 @@ public interface UserService {
* @param page 数据页
* @return 分页数据
*/
PageInfo<UserModel> getUserList(Integer page, Integer count);
PageData<UserModel> getUserList(Integer page, Integer count);
/**
* 更改用户信息
@@ -174,4 +146,14 @@ public interface UserService {
* @return true:存在 false不存在
*/
boolean getStatusOfEmail(String email);
/**
* 设置密码
*
* @param pwd pwd
* @param newPwd newPwd
* @param confirmPwd confirmPwd
* @return UserModel
*/
UserModel setPwd(String pwd, String newPwd, String confirmPwd);
}

View File

@@ -1,7 +1,7 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.VisitorModel;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
@@ -20,7 +20,7 @@ public interface VisitorService {
* @param showLocation 是否显示位置信息 开启改选项数据响应超慢
* @return 分页数据
*/
PageInfo<VisitorModel> visitorPage(int page, int count, boolean showLocation);
PageData<VisitorModel> visitorPage(int page, int count, boolean showLocation);
/**
* 新增访客

View File

@@ -1,7 +1,8 @@
package cn.celess.blog.service;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.WebUpdateModel;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import java.util.List;
@@ -44,7 +45,7 @@ public interface WebUpdateInfoService {
* @param page 数据页
* @return 分页数据
*/
PageInfo<WebUpdateModel> pages(int count, int page);
PageData<WebUpdateModel> pages(int count, int page);
/**
* 获取全部的更新记录
@@ -58,5 +59,5 @@ public interface WebUpdateInfoService {
*
* @return
*/
String getLastestUpdateTime();
JSONObject getLastestUpdateTime();
}

View File

@@ -1,35 +1,33 @@
package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.LevelEnum;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.enmu.RoleEnum;
import cn.celess.blog.entity.*;
import cn.celess.blog.entity.model.ArticleModel;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.request.ArticleReq;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.CategoryMapper;
import cn.celess.blog.mapper.CommentMapper;
import cn.celess.blog.mapper.TagMapper;
import cn.celess.blog.mapper.*;
import cn.celess.blog.service.ArticleService;
import cn.celess.blog.service.UserService;
import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.ModalTrans;
import cn.celess.blog.util.RedisUserUtil;
import cn.celess.blog.util.RegexUtil;
import cn.celess.blog.util.StringFromHtmlUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youbenzi.mdtool.tool.MDTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.krb5.internal.PAData;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
@@ -37,8 +35,8 @@ import java.util.List;
* @date : 2019/03/28 15:21
*/
@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {
public static final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);
@Autowired
ArticleMapper articleMapper;
@@ -50,6 +48,8 @@ public class ArticleServiceImpl implements ArticleService {
@Autowired
CommentMapper commentMapper;
@Autowired
ArticleTagMapper articleTagMapper;
@Autowired
UserService userService;
@Autowired
HttpServletRequest request;
@@ -79,466 +79,286 @@ public class ArticleServiceImpl implements ArticleService {
if (reqBody.getCategory() == null || reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
if (reqBody.getTags() == null || reqBody.getTags().length == 0) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
if (articleMapper.existsByTitle(reqBody.getTitle())) {
throw new MyException(ResponseEnum.ARTICLE_HAS_EXIST);
}
// 查看是否存在已有的分类
Category category = categoryMapper.findCategoryByName(reqBody.getCategory());
if (category == null) {
throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST);
}
//写入数据库的数据
// 构建 需要写入数据库的对象数据
Article article = new Article();
article.setTitle(reqBody.getTitle());
article.setOpen(reqBody.getOpen());
article.setMdContent(reqBody.getMdContent());
article.setUrl(reqBody.getUrl());
article.setType(reqBody.getType());
BeanUtils.copyProperties(reqBody, article);
article.setAuthorId(redisUserUtil.get(request).getId());
article.setPublishDate(new Date());
//防止出现 “null,xxx”这种情况
article.setTagsId("");
//是否需要更新上一篇文章
boolean isUpdatePreArticle = true;
Article preArticle = null;
if (articleMapper.count() == 0) {
isUpdatePreArticle = false;
} else {
//获取最新的一条数据
preArticle = articleMapper.getLastestArticle();
}
if (isUpdatePreArticle) {
logger.info("上一篇文章的id为" + preArticle.getId());
//设置上一篇文章的id
article.setPreArticleId(preArticle.getId());
}
article.setUser(redisUserUtil.get());
//markdown->html->summary
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
//获取摘要 摘要长度为255个字符
String summary = str.length() > 240 ? str.substring(0, 240) + "......" : str;
//去除转换后存在的空格
String tagStr = reqBody.getTags().replaceAll(" ", "");
article.setSummary(summary);
if (articleMapper.existsByTitle(article.getTitle())) {
throw new MyException(ResponseEnum.ARTICLE_HAS_EXIST);
}
//将分类写入数据库
Category category1 = categoryMapper.findCategoryByName(reqBody.getCategory());
if (category1 == null) {
category1 = new Category();
category1.setArticles("");
category1.setName(reqBody.getCategory());
categoryMapper.insert(category1);
}
article.setCategoryId(category1.getId());
article.setCategory(category);
//文章存数据库
articleMapper.insert(article);
//获取新增的文章
if (isUpdatePreArticle) {
//更新上一篇文章的“下一篇文章ID”
articleMapper.updateNextArticleId(preArticle.getId(), article.getId());
}
//无效
// articleMapper.updatePreArticleId(article.getId(), preArticle == null ? -1 : preArticle.getId());
article.setPreArticleId(preArticle == null ? -1 : preArticle.getId());
category1.setArticles(category1.getArticles() + article.getId() + ",");
categoryMapper.update(category1);
//将标签写入数据库
for (String t : tagStr.split(",")) {
if (t.replaceAll(" ", "").length() == 0) {
for (String tagName : reqBody.getTags()) {
if (tagName.replaceAll(" ", "").length() == 0) {
//单个标签只含空格
continue;
}
Tag tag = tagMapper.findTagByName(t);
Tag tag = tagMapper.findTagByName(tagName);
if (tag == null) {
tag = new Tag();
tag.setName(t);
tag.setArticles("");
tag.setName(tagName);
tagMapper.insert(tag);
}
tag.setArticles(tag.getArticles() + article.getId() + ",");
article.setTagsId(article.getTagsId() + tag.getId() + ",");
tagMapper.update(tag);
}
articleMapper.update(article);
return fullTransform(articleMapper.getLastestArticle());
ArticleTag articleTag = new ArticleTag(article, tag);
articleTagMapper.insert(articleTag);
}
Article articleFromDb = articleMapper.findArticleById(article.getId());
ArticleModel articleModel = ModalTrans.article(articleFromDb);
articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(article.getId()), true));
return articleModel;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delete(long articleID) {
Article articleForDel = articleMapper.findArticleById(articleID);
public boolean delete(long articleId) {
Article articleForDel = articleMapper.findArticleById(articleId);
if (articleForDel == null) {
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);//文章不存在
//文章不存在
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);
}
Article preArticle = articleMapper.findArticleById(articleForDel.getPreArticleId());
Article nextArticle = articleMapper.findArticleById(articleForDel.getNextArticleId());
//对访问情况进行判断 非博主/非自己文章 拒绝访问
User user = redisUserUtil.get(request);
if (!user.getRole().contains("admin") && !articleForDel.getAuthorId().equals(user.getId())) {
//对访问情况进行判断 非admin 权限不可删除文章
User user = redisUserUtil.get();
if (!RoleEnum.ADMIN_ROLE.getRoleName().equals(user.getRole())) {
throw new MyException(ResponseEnum.PERMISSION_ERROR);
}
//删除的文章处于中间位置
if (nextArticle != null && preArticle != null) {
//修改上一篇文章的“下一篇文章”y
articleMapper.updateNextArticleId(articleForDel.getPreArticleId(), articleForDel.getNextArticleId());
//修改下一篇文章的 “上一篇文章”
articleMapper.updatePreArticleId(articleForDel.getNextArticleId(), articleForDel.getPreArticleId());
}
if (preArticle == null && nextArticle != null) {
//删除的是第一篇文章
articleMapper.updatePreArticleId(nextArticle.getId(), -1);
}
if (nextArticle == null && preArticle != null) {
//删除的是最后一篇文章
articleMapper.updateNextArticleId(preArticle.getId(), -1);
}
// delete count 为删除的数据数量
int deleteCount = commentMapper.deleteByArticleId(articleID);
//删除标签中的文章id
String tag = articleForDel.getTagsId();
if (tag.length() > 0) {
String[] tags = tag.split(",");
for (String t : tags) {
if (t != null) {
//查询标签
Tag tag1 = tagMapper.findTagById(Long.parseLong(t));
//去除标签中的articleId中的待删除的文章id
String s = tag1.getArticles().replaceAll(articleForDel.getId() + ",", "");
tag1.setArticles(s);
tagMapper.update(tag1);
}
}
}
//删除分类中的文章id
//获取文章的分类
long categoryId = articleForDel.getCategoryId();
Category category = categoryMapper.findCategoryById(categoryId);
//删除文章id
category.setArticles(category.getArticles().replaceAll(articleForDel.getId() + ",", ""));
//更新
categoryMapper.update(category);
//删除指定文章
articleMapper.delete(articleID);
articleMapper.delete(articleId);
//articleTagMapper.deleteByArticleId(articleId);
return true;
}
@Transactional(rollbackFor = Exception.class)
@Override
public ArticleModel update(ArticleReq reqBody) {
if (reqBody == null) {
if (reqBody == null || reqBody.getId() == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
// 查找数据
Article article = articleMapper.findArticleById(reqBody.getId());
//数据判断
if (reqBody.getTitle() == null || reqBody.getTitle().replaceAll(" ", "").isEmpty()) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
} else if (reqBody.getMdContent() == null || reqBody.getMdContent().replaceAll(" ", "").isEmpty()) {
if (reqBody.getTitle() != null && !reqBody.getTitle().replaceAll(" ", "").isEmpty()) {
if (!article.getTitle().equals(reqBody.getTitle()) && articleMapper.existsByTitle(reqBody.getTitle())) {
throw new MyException(ResponseEnum.ARTICLE_HAS_EXIST);
}
article.setTitle(reqBody.getTitle());
}
if (reqBody.getMdContent() != null && !reqBody.getMdContent().replaceAll(" ", "").isEmpty()) {
article.setMdContent(reqBody.getMdContent());
}
//转载 判断链接
if (reqBody.getType() != null) {
if (!reqBody.getType() && reqBody.getUrl() == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
//转载 判断链接
if (!reqBody.getType()) {
if (reqBody.getUrl() == null || reqBody.getUrl().replaceAll(" ", "").isEmpty()) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
} else if (!RegexUtil.urlMatch(reqBody.getUrl())) {
if (!reqBody.getType() && !RegexUtil.urlMatch(reqBody.getUrl())) {
throw new MyException(ResponseEnum.PARAMETERS_URL_ERROR);
}
article.setType(reqBody.getType());
article.setUrl(reqBody.getUrl());
}
if (reqBody.getCategory() == null || reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
if (reqBody.getCategory() != null && !reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
Category category = categoryMapper.findCategoryByName(reqBody.getCategory());
if (category == null) {
category = new Category();
category.setName(reqBody.getCategory());
categoryMapper.insert(category);
}
article.setCategory(category);
}
// 暂时不更新tags
// if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
// throw new MyException(ResponseEnum.PARAMETERS_ERROR);
// }
//写入数据库的数据
Article article = new Article();
if (reqBody.getId() == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不能为空");
}
article.setId(reqBody.getId());
article.setTitle(reqBody.getTitle());
article.setOpen(reqBody.getOpen());
article.setMdContent(reqBody.getMdContent());
article.setUrl(reqBody.getUrl());
article.setType(reqBody.getType());
Article oldArticle = articleMapper.findArticleById(reqBody.getId());
Category category = categoryMapper.findCategoryById(oldArticle.getCategoryId());
if (!(category.getName()).equals(reqBody.getCategory())) {
//修改更新之前数据 的分类
category.setArticles(category.getArticles().replace(reqBody.getId() + ",", ""));
//更新
categoryMapper.update(category);
//更新 更新之后的分类
Category category1 = categoryMapper.findCategoryByName(reqBody.getCategory());
if (category1 == null) {
category1 = new Category();
category1.setName(reqBody.getCategory());
category1.setArticles(reqBody.getId() + ",");
categoryMapper.insert(category1);
}
article.setCategoryId(category1.getId());
} else {
article.setCategoryId(oldArticle.getCategoryId());
}
// String[] newTags = reqBody.getTags().replaceAll(" ", "").split(",");
// //防止出现 null2这种情况
// article.setTagsId("");
// for (String t : newTags) {
// Tag tag = tagMapper.findTagByName(t);
// if (tag == null) {
// tag = new Tag();
// tag.setName(t);
// tag.setArticles(oldArticle.getId() + ",");
// tag = tagMapper.save(tag);
// article.setTagsId(article.getTagsId() + tag.getId() + ",");
// continue;
// }
// article.setTagsId(article.getTagsId() + tag.getId() + ",");
// }
// TODO:::: tag的更新
article.setTagsId(oldArticle.getTagsId());
article.setUpdateDate(new Date());
// TODO::::换用beansUtil
// 设置不定参数
article.setReadingNumber(oldArticle.getReadingNumber());
article.setPublishDate(oldArticle.getPublishDate());
article.setAuthorId(redisUserUtil.get(request).getId());
article.setPreArticleId(oldArticle.getPreArticleId());
article.setNextArticleId(oldArticle.getNextArticleId());
article.setOpen(reqBody.getOpen() == null ? article.getOpen() : reqBody.getOpen());
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
article.setSummary(str.length() > 240 ? str.substring(0, 240) + "......" : str);
articleMapper.update(article);
List<ArticleTag> allByArticleId = articleTagMapper.findAllByArticleId(article.getId());
List<ArticleTag> updateList = new ArrayList<>();
List<ArticleTag> deleteList = new ArrayList<>();
// 获取要更新 的标签
for (String tag : reqBody.getTags()) {
boolean contain = allByArticleId.stream().anyMatch(articleTag -> articleTag.getTag().getName().equals(tag));
if (!contain) {
ArticleTag articleTag = new ArticleTag();
articleTag.setArticle(article);
Tag tagByName = tagMapper.findTagByName(tag);
if (tagByName == null) {
tagByName = new Tag(tag);
tagMapper.insert(tagByName);
}
articleTag.setTag(tagByName);
updateList.add(articleTag);
}
}
// 获取要删除的标签
allByArticleId.forEach(articleTag -> {
boolean contain = false;
for (String tag : reqBody.getTags()) {
if (articleTag.getTag().getName().equals(tag)) {
contain = true;
break;
}
}
if (!contain) {
deleteList.add(articleTag);
}
});
if (updateList.size() != 0) {
updateList.forEach(articleTag -> articleTagMapper.insert(articleTag));
}
if (deleteList.size() != 0) {
articleTagMapper.deleteMultiById(deleteList);
}
//更新完成移除
request.getSession().removeAttribute("article4update");
return fullTransform(article);
ArticleModel articleModel = ModalTrans.article(articleMapper.findArticleById(article.getId()));
setPreAndNextArticle(articleModel);
return articleModel;
}
@Override
public ArticleModel retrieveOneByID(long articleID, boolean is4update) {
Article article = articleMapper.findArticleById(articleID);
public ArticleModel retrieveOneById(long articleId, boolean is4update) {
Article article = articleMapper.findArticleById(articleId);
if (article == null) {
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);
}
if (!article.getOpen()) {
User user = redisUserUtil.getWithOutExc(request);
User user = redisUserUtil.getWithOutExc();
if (user == null || "user".equals(user.getRole())) {
throw new MyException(ResponseEnum.ARTICLE_NOT_PUBLIC);
}
}
article.setReadingNumber(article.getReadingNumber() + 1);
ArticleModel articleModel = ModalTrans.article(article);
if (is4update) {
//因更新而获取文章 不需要增加阅读量
request.getSession().setAttribute("article4update", article);
return fullTransform(article);
return articleModel;
}
articleMapper.setReadingNumber(article.getReadingNumber() + 1, articleID);
return fullTransform(article);
setPreAndNextArticle(articleModel);
articleMapper.updateReadingNumber(articleId);
return articleModel;
}
/**
* @param count 数目
* @param page 页面 默认减1
* @return
* @param page 页面
* @return PageInfo
*/
@Override
public PageInfo adminArticles(int count, int page) {
PageHelper.startPage(page, count);
public PageData<ArticleModel> adminArticles(int count, int page, boolean deleted) {
List<Article> articleList = articleMapper.findAll();
PageInfo pageInfo = new PageInfo(articleList);
pageInfo.setList(list2list(articleList, LevelEnum.BETWEEN_M_AND_H));
return pageInfo;
PageData<ArticleModel> pageData = new PageData<>(null, 0, count, page);
List<Article> collect = articleList.stream().filter(article -> article.isDeleted() == deleted).collect(Collectors.toList());
pageData.setTotal(collect.size());
List<ArticleModel> articleModels = collect.stream()
.peek(article -> article.setMdContent(null))
.map(ModalTrans::article)
.skip((page - 1) * count)
.limit(count)
.collect(Collectors.toList());
pageData.setList(articleModels);
return pageData;
}
@Override
public PageInfo retrievePageForOpen(int count, int page) {
public PageData<ArticleModel> retrievePageForOpen(int count, int page) {
PageHelper.startPage(page, count);
List<Article> articleList = articleMapper.findAllByOpen(true);
PageInfo pageInfo = new PageInfo(articleList);
pageInfo.setList(list2list(articleList, LevelEnum.MIDDLE));
return pageInfo;
PageData<ArticleModel> pageData = new PageData<>(new PageInfo<Article>(articleList));
List<ArticleModel> articleModelList = new ArrayList<>();
articleList.forEach(article -> {
ArticleModel model = ModalTrans.article(article, true);
setPreAndNextArticle(model);
articleModelList.add(model);
});
pageData.setList(articleModelList);
return pageData;
}
@Override
public PageInfo findByCategory(String name, int page, int count) {
Long idByName = categoryMapper.getIDByName(name);
if (idByName == null) {
public PageData<ArticleModel> findByCategory(String name, int page, int count) {
Category category = categoryMapper.findCategoryByName(name);
if (category == null) {
throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST);
}
PageHelper.startPage(page, count);
PageInfo pageInfo = new PageInfo(articleMapper.getSimpleInfoByCategory(idByName));
return pageInfo;
List<Article> open = articleMapper.findAllByCategoryIdAndOpen(category.getId());
List<ArticleModel> modelList = new ArrayList<>();
open.forEach(article -> {
ArticleModel model = ModalTrans.article(article, true);
model.setTags(null);
// setPreAndNextArticle(model);
model.setNextArticle(null);
model.setPreArticle(null);
modelList.add(model);
});
return new PageData<ArticleModel>(new PageInfo<Article>(open), modelList);
}
@Override
public PageInfo findByTag(String name, int page, int count) {
public PageData<ArticleModel> findByTag(String name, int page, int count) {
Tag tag = tagMapper.findTagByName(name);
if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
}
PageHelper.startPage(page, count);
String[] split = tag.getArticles().split(",");
List<String> list = Arrays.asList(split);
List<Article> articleList = articleMapper.getSimpleInfoByTag(list);
PageInfo pageInfo = new PageInfo(articleList);
return pageInfo;
List<ArticleTag> articleByTag = articleTagMapper.findArticleByTagAndOpen(tag.getId());
List<ArticleModel> modelList = new ArrayList<>();
articleByTag.forEach(articleTag -> {
ArticleModel model = ModalTrans.article(articleTag.getArticle(), true);
model.setNextArticle(null);
model.setPreArticle(null);
modelList.add(model);
});
return new PageData<ArticleModel>(new PageInfo<ArticleTag>(articleByTag), modelList);
}
/**
* page转换
*
* @param articleList 数据源
* @param level 转换级别
* @return list
*/
private List<ArticleModel> list2list(List<Article> articleList, LevelEnum level) {
List<ArticleModel> content = new ArrayList<>();
for (Article a : articleList) {
ArticleModel model;
switch (level.getLevelCode()) {
case 0:
model = simpleTransform(a);
break;
case 1:
model = suitableTransform(a);
break;
case 2:
model = suitableTransformForAdmin(a);
break;
case 3:
default:
model = fullTransform(a);
private void setPreAndNextArticle(ArticleModel articleModel) {
if (articleModel == null) {
return;
}
content.add(model);
articleModel.setPreArticle(ModalTrans.article(articleMapper.getPreArticle(articleModel.getId()), true));
articleModel.setNextArticle(ModalTrans.article(articleMapper.getNextArticle(articleModel.getId()), true));
}
return content;
}
/**
* 简单的模型转换
* [id,title,summary]
*
* @param a 源数据
* @return 模型
*/
private ArticleModel simpleTransform(Article a) {
ArticleModel model = new ArticleModel();
model.setId(a.getId());
model.setTitle(a.getTitle());
model.setSummary(a.getSummary());
return model;
}
/**
* 中等转换
* [id,title,summary]
* +
* [original,tags,category]
*
* @param a
* @return
*/
private ArticleModel suitableTransform(Article a) {
ArticleModel model = simpleTransform(a);
model.setAuthorName(userService.getNameById(a.getAuthorId()));
model.setPublishDateFormat(DateFormatUtil.get(a.getPublishDate()));
model.setOriginal(a.getType());
model.setCategory(categoryMapper.getNameById(a.getCategoryId()));
String[] split = a.getTagsId().split(",");
String[] tags = new String[split.length];
for (int i = 0; i < split.length; i++) {
if (split[i] == null || "".equals(split[i])) {
continue;
}
tags[i] = tagMapper.getNameById(Long.parseLong(split[i]));
}
model.setTags(tags);
return model;
}
/**
* 中等转换 for admin页面
* [id,title]
* +
* [original,UpdateDate,open,readingNumber]
*
* @param a
* @return
*/
private ArticleModel suitableTransformForAdmin(Article a) {
ArticleModel model = simpleTransform(a);
model.setPublishDateFormat(DateFormatUtil.get(a.getPublishDate()));
model.setUpdateDateFormat(DateFormatUtil.get(a.getUpdateDate()));
model.setReadingNumber(a.getReadingNumber());
model.setOpen(a.getOpen());
model.setOriginal(a.getType());
model.setSummary(null);
return model;
}
/**
* 全转换
* [id,title,summary,original,tags,category]
* +
* [UpdateDate,MdContent,NextArticleId,NextArticleTitle,preArticleId,preArticleTitle,open,url,readingNumber]
*
* @param a
* @return
*/
private ArticleModel fullTransform(Article a) {
ArticleModel model = suitableTransform(a);
model.setUpdateDateFormat(DateFormatUtil.get(a.getUpdateDate()));
model.setMdContent(a.getMdContent());
model.setNextArticleId(a.getNextArticleId());
model.setNextArticleTitle(a.getNextArticleId() == -1 ? "" : articleMapper.getTitleById(a.getNextArticleId()));
model.setPreArticleId(a.getPreArticleId());
model.setPreArticleTitle(a.getPreArticleId() == -1 ? "" : articleMapper.getTitleById(a.getPreArticleId()));
model.setOpen(a.getOpen());
model.setUrl(a.getUrl());
model.setReadingNumber(a.getReadingNumber());
return model;
}
}

View File

@@ -3,14 +3,21 @@ package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Article;
import cn.celess.blog.entity.Category;
import cn.celess.blog.entity.model.ArticleModel;
import cn.celess.blog.entity.model.CategoryModel;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.CategoryMapper;
import cn.celess.blog.service.CategoryService;
import cn.celess.blog.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.ArrayList;
import java.util.List;
/**
@@ -27,65 +34,56 @@ public class CategoryServiceImpl implements CategoryService {
ArticleMapper articleMapper;
@Override
public Category create(String name) {
public CategoryModel create(String name) {
if (categoryMapper.existsByName(name)) {
throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST);
}
Category category = new Category();
category.setName(name);
category.setArticles("");
categoryMapper.insert(category);
return category;
}
@Override
public Category create(Category category) {
if (category == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
categoryMapper.insert(category);
return category;
return ModalTrans.category(category);
}
@Override
public boolean delete(long id) {
Category category = categoryMapper.findCategoryById(id);
if (category == null) {
throw new MyException(ResponseEnum.CATEGORY_NOT_EXIST);
}
String[] articleArray = category.getArticles().split(",");
for (int i = 0; i < articleArray.length; i++) {
if (articleArray[i] == null || "".equals(articleArray[i])) {
continue;
}
long articleId = Long.parseLong(articleArray[i]);
Article article = articleMapper.findArticleById(articleId);
if (article == null) {
continue;
}
article.setCategoryId(-1L);
//一个 文章只对应一个分类,分类不存在则文章默认不可见
article.setOpen(false);
articleMapper.update(article);
}
return categoryMapper.delete(id) == 1;
}
@Override
public Category update(Long id, String name) {
public CategoryModel update(Long id, String name) {
if (id == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空");
}
Category category = categoryMapper.findCategoryById(id);
category.setName(name);
categoryMapper.update(category);
return category;
return ModalTrans.category(category);
}
@Override
public List<Category> retrievePage() {
return categoryMapper.findAll();
public PageData<CategoryModel> retrievePage(int page, int count) {
PageHelper.startPage(page, count);
List<Category> all = categoryMapper.findAll();
List<CategoryModel> modelList = new ArrayList<>();
all.forEach(e -> {
CategoryModel model = ModalTrans.category(e);
List<Article> allByCategoryId = articleMapper.findAllByCategoryId(e.getId());
List<ArticleModel> articleModelList = new ArrayList<>();
allByCategoryId.forEach(article -> {
ArticleModel articleModel = ModalTrans.article(article, true);
articleModel.setPreArticle(null);
articleModel.setNextArticle(null);
articleModel.setTags(null);
articleModelList.add(articleModel);
});
model.setArticles(articleModelList);
modelList.add(model);
});
return new PageData<CategoryModel>(new PageInfo<Category>(all), modelList);
}
}

View File

@@ -1,24 +1,27 @@
package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.CommentStatusEnum;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Comment;
import cn.celess.blog.entity.User;
import cn.celess.blog.entity.model.CommentModel;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.request.CommentReq;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.CommentMapper;
import cn.celess.blog.mapper.UserMapper;
import cn.celess.blog.service.CommentService;
import cn.celess.blog.service.UserService;
import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.ModalTrans;
import cn.celess.blog.util.RedisUserUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
@@ -30,7 +33,7 @@ public class CommentServiceImpl implements CommentService {
@Autowired
CommentMapper commentMapper;
@Autowired
UserService userService;
UserMapper userMapper;
@Autowired
ArticleMapper articleMapper;
@Autowired
@@ -40,52 +43,43 @@ public class CommentServiceImpl implements CommentService {
@Override
public CommentModel create(CommentReq reqBody) {
if (reqBody == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
long authorID = redisUserUtil.get(request).getId();
User user = redisUserUtil.get();
Comment pComment = null;
if (reqBody.getPid() != null && reqBody.getPid() != -1) {
if (reqBody.getPid() != -1) {
pComment = commentMapper.findCommentById(reqBody.getPid());
}
if (reqBody.getPid() == null) {
reqBody.setPid(-1L);
}
//不是一级评论
if (reqBody.getPid() != -1 && pComment == null) {
//父评论不存在
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
Comment comment = new Comment();
comment.setAuthorID(authorID);
comment.setType(reqBody.getComment());
if (reqBody.getComment()) {
//若为评论
if (reqBody.getArticleID() <= 0) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
comment.setFromUser(user);
User userTo = new User();
userTo.setId(-1L);
if (reqBody.getToUserId() != -1) {
userTo = userMapper.findById(reqBody.getToUserId());
comment.setToUser(userTo);
}
comment.setArticleID(reqBody.getArticleID());
} else {
comment.setArticleID(-1L);
}
comment.setContent(reqBody.getContent());
comment.setPid(reqBody.getPid());
comment.setDate(new Date());
comment.setResponseId("");
comment.setToUser(userTo);
userMapper.findById(reqBody.getToUserId());
BeanUtils.copyProperties(reqBody, comment);
commentMapper.insert(comment);
if (reqBody.getPid() != -1) {
commentMapper.updateResponder(pComment.getResponseId() + comment.getId() + ",", reqBody.getPid());
}
return trans(comment);
return ModalTrans.comment(commentMapper.findCommentById(comment.getId()));
}
@Override
public boolean delete(long id) {
boolean b = commentMapper.existsById(id);
if (!b) {
Comment b = commentMapper.findCommentById(id);
if (b == null) {
throw new MyException(ResponseEnum.COMMENT_NOT_EXIST);
}
if (b.getStatus() == CommentStatusEnum.DELETED.getCode()) {
throw new MyException(ResponseEnum.DATA_IS_DELETED);
}
commentMapper.delete(id);
return true;
}
@@ -100,93 +94,65 @@ public class CommentServiceImpl implements CommentService {
commentMapper.updateContent(reqBody.getContent(), reqBody.getId());
comment.setContent(reqBody.getContent());
}
if (!comment.getResponseId().equals(reqBody.getResponseId())) {
commentMapper.updateResponder(reqBody.getResponseId(), reqBody.getId());
comment.setResponseId(reqBody.getResponseId());
}
return trans(comment);
}
@Override
public PageInfo<CommentModel> retrievePage(Boolean isComment, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByType(isComment);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
return ModalTrans.comment(comment);
}
@Override
public PageInfo<CommentModel> retrievePageByPid(long pid, int page, int count) {
public PageData<CommentModel> retrievePage(String pagePath, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByPId(pid);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
List<Comment> list = commentMapper.findAllByPagePathAndPidAndNormal(pagePath, -1);
return pageTrans(list);
}
@Override
public PageInfo<CommentModel> retrievePageByArticle(long articleID, long pid, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByArticleIDAndPId(articleID, pid);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
public List<CommentModel> retrievePageByPid(long pid) {
List<Comment> allByPagePath = commentMapper.findAllByPid(pid);
List<CommentModel> commentModels = new ArrayList<>();
allByPagePath.forEach(comment -> {
if (comment.getStatus() != CommentStatusEnum.DELETED.getCode()) {
commentModels.add(ModalTrans.comment(comment));
}
});
return commentModels;
}
@Override
public PageInfo<CommentModel> retrievePageByTypeAndPid(Boolean isComment, int pid, int page, int count) {
public PageData<CommentModel> retrievePageByAuthor(String pagePath, int page, int count) {
User user = redisUserUtil.get();
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findCommentsByTypeAndPId(isComment, pid);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
List<Comment> list = commentMapper.findAllByPagePathAndFromUser(pagePath, user.getId());
return pageTrans(list);
}
@Override
public PageInfo<CommentModel> retrievePageByAuthor(Boolean isComment, int page, int count) {
public PageData<CommentModel> retrievePageByPageAndPid(String pagePath, long pid, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByAuthorIDAndType(redisUserUtil.get(request).getId(), isComment);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
List<Comment> list = commentMapper.findAllByPagePath(pagePath);
return pageTrans(list, true);
}
@Override
public PageInfo<CommentModel> retrievePageByType(Boolean isComment, int page, int count) {
public PageData<CommentModel> retrievePageByPage(String pagePath, int page, int count) {
PageHelper.startPage(page, count);
List<Comment> commentList = commentMapper.findAllByType(isComment);
PageInfo pageInfo = new PageInfo(commentList);
pageInfo.setList(list2List(commentList));
return pageInfo;
List<Comment> list = commentMapper.findAllByPagePath(pagePath);
return pageTrans(list, true);
}
private List<CommentModel> list2List(List<Comment> commentList) {
List<CommentModel> content = new ArrayList<>();
for (Comment c : commentList) {
content.add(trans(c));
}
return content;
private PageData<CommentModel> pageTrans(List<Comment> commentList) {
return pageTrans(commentList, false);
}
private CommentModel trans(Comment comment) {
CommentModel commentModel = new CommentModel();
commentModel.setId(comment.getId());
commentModel.setComment(comment.getType());
commentModel.setContent(comment.getContent());
commentModel.setArticleID(comment.getArticleID());
commentModel.setDate(DateFormatUtil.get(comment.getDate()));
commentModel.setResponseId(comment.getResponseId());
commentModel.setPid(comment.getPid());
commentModel.setAuthorName(userService.getNameById(comment.getAuthorID()));
commentModel.setAuthorAvatarImgUrl("http://cdn.celess.cn/" + userService.getAvatarImg(comment.getAuthorID()));
if (comment.getType() && commentModel.getArticleID() > 0) {
commentModel.setArticleTitle(articleMapper.getTitleById(comment.getArticleID()));
private PageData<CommentModel> pageTrans(List<Comment> commentList, boolean noResponseList) {
PageInfo<Comment> p = PageInfo.of(commentList);
List<CommentModel> modelList = new ArrayList<>();
commentList.forEach(l -> {
CommentModel model = ModalTrans.comment(l);
if (!noResponseList) {
model.setRespComment(this.retrievePageByPid(model.getId()));
}
return commentModel;
modelList.add(model);
});
return new PageData<CommentModel>(p, modelList);
}
}

View File

@@ -29,7 +29,7 @@ public class CountServiceImpl implements CountService {
@Override
public long getCommentCount() {
return commentMapper.countByType(true);
return commentMapper.count();
}
@Override
@@ -47,11 +47,6 @@ public class CountServiceImpl implements CountService {
return tagMapper.count();
}
@Override
public long getLeaveMessageCount() {
return commentMapper.countByType(false);
}
@Override
public long getUserCount() {
return userMapper.count();

View File

@@ -2,6 +2,7 @@ package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.PartnerSite;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.request.LinkReq;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.PartnerMapper;
@@ -51,6 +52,12 @@ public class PartnerSiteServiceImpl implements PartnerSiteService {
reqBody.setUrl("http://" + reqBody.getUrl());
}
BeanUtils.copyProperties(reqBody, partnerSite);
if (reqBody.getIconPath() == null) {
partnerSite.setIconPath("");
}
if (reqBody.getDesc() == null) {
partnerSite.setDesc("");
}
partnerMapper.insert(partnerSite);
return partnerSite;
}
@@ -87,16 +94,17 @@ public class PartnerSiteServiceImpl implements PartnerSiteService {
}
@Override
public PageInfo<PartnerSite> PartnerSitePages(int page, int count) {
public PageData<PartnerSite> partnerSitePages(int page, int count) {
PageHelper.startPage(page, count);
List<PartnerSite> sitePage = partnerMapper.findAll();
PageInfo pageInfo = new PageInfo(sitePage);
return pageInfo;
PageInfo<PartnerSite> pageInfo = new PageInfo<PartnerSite>(sitePage);
return new PageData<>(pageInfo, sitePage);
}
@Override
public List<PartnerSite> findAll() {
List<PartnerSite> all = partnerMapper.findAll();
all.forEach(partnerSite -> partnerSite.setDelete(null));
return all;
}

View File

@@ -10,9 +10,7 @@ import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.io.InputStream;
@@ -23,31 +21,29 @@ import java.io.InputStream;
*/
@Service
public class QiniuServiceImpl implements QiniuService {
private Configuration cfg = new Configuration(Zone.zone2());
private UploadManager uploadManager;
private BucketManager bucketManager;
private Auth auth;
private static final Configuration cfg = new Configuration(Zone.zone2());
private static UploadManager uploadManager;
private static BucketManager bucketManager;
private static Auth auth;
private static String bucket;
{
/* ***** 必填 ******
* 七牛的配置 *
* ***** 必填 ******
*/
// accessKeyString,secretKeyString,bucketString请替换为自己的值
String accessKey = "accessKeyString";
String secretKey = "secretKeyString";
bucket = "bucketString";
@Value("${qiniu.accessKey}")
private String accessKey;
@Value("${qiniu.secretKey}")
private String secretKey;
@Value("${qiniu.bucket}")
private String bucket;
private void init() {
if (auth == null || uploadManager == null || bucketManager == null) {
auth = Auth.create(accessKey, secretKey);
uploadManager = new UploadManager(cfg);
bucketManager = new BucketManager(auth, cfg);
}
}
@Override
public QiniuResponse uploadFile(InputStream is, String fileName) {
init();
//文件存在则删除文件
if (continueFile(fileName)) {
try {
@@ -69,6 +65,7 @@ public class QiniuServiceImpl implements QiniuService {
@Override
public FileInfo[] getFileList() {
init();
BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, "");
FileInfo[] items = null;
while (fileListIterator.hasNext()) {

View File

@@ -1,18 +1,25 @@
package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Article;
import cn.celess.blog.entity.ArticleTag;
import cn.celess.blog.entity.Tag;
import cn.celess.blog.entity.model.ArticleModel;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.TagModel;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.ArticleMapper;
import cn.celess.blog.mapper.ArticleTagMapper;
import cn.celess.blog.mapper.TagMapper;
import cn.celess.blog.service.TagService;
import cn.celess.blog.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 org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
@@ -27,9 +34,11 @@ public class TagServiceImpl implements TagService {
HttpServletRequest request;
@Autowired
ArticleMapper articleMapper;
@Autowired
ArticleTagMapper articleTagMapper;
@Override
public Tag create(String name) {
public TagModel create(String name) {
boolean b = tagMapper.existsByName(name);
if (b) {
throw new MyException(ResponseEnum.TAG_HAS_EXIST);
@@ -37,84 +46,55 @@ public class TagServiceImpl implements TagService {
Tag tag = new Tag();
tag.setName(name);
tagMapper.insert(tag);
return tag;
}
@Override
public Tag create(Tag tag) {
if (tag == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
tagMapper.insert(tag);
return tag;
return ModalTrans.tag(tag);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delete(long tagId) {
Tag tag = tagMapper.findTagById(tagId);
if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
}
if (tag.getArticles()==null){
return tagMapper.delete(tagId) == 1;
}
String[] articleArray = tag.getArticles().split(",");
for (int i = 0; i < articleArray.length; i++) {
if (articleArray[i] == null || "".equals(articleArray)) {
continue;
}
long articleID = Long.parseLong(articleArray[i]);
Article article = articleMapper.findArticleById(articleID);
if (article == null) {
continue;
}
article.setTagsId(article.getTagsId().replace(tagId + ",", ""));
articleMapper.update(article);
}
List<ArticleTag> articleByTag = articleTagMapper.findArticleByTag(tagId);
// 删除文章
articleByTag.forEach(articleTag -> articleMapper.delete(articleTag.getArticle().getId()));
return tagMapper.delete(tagId) == 1;
}
@Override
public Tag update(Long id,String name) {
public TagModel update(Long id, String name) {
if (id == null) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID");
}
Tag tagFromDB = tagMapper.findTagById(id);
tagFromDB.setName(name);
tagMapper.update(tagFromDB);
return tagFromDB;
Tag tag = tagMapper.findTagById(id);
tag.setName(name);
tagMapper.update(tag);
return ModalTrans.tag(tag);
}
@Override
public Tag retrieveOneById(long tagId) {
Tag tag = tagMapper.findTagById(tagId);
if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
}
return tag;
}
@Override
public Tag retrieveOneByName(String name) {
Tag tag = tagMapper.findTagByName(name);
if (tag == null) {
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
}
return tag;
}
@Override
public PageInfo<Tag> retrievePage(int page, int count) {
public PageData<TagModel> retrievePage(int page, int count) {
PageHelper.startPage(page, count);
PageInfo pageInfo = new PageInfo(tagMapper.findAll());
return pageInfo;
List<Tag> tagList = tagMapper.findAll();
List<TagModel> modelList = new ArrayList<>();
tagList.forEach(tag -> modelList.add(ModalTrans.tag(tag)));
return new PageData<TagModel>(new PageInfo<Tag>(tagList), modelList);
}
@Override
public List<Tag> findAll() {
return tagMapper.findAll();
public List<TagModel> findAll() {
List<TagModel> list = new ArrayList<>();
tagMapper.findAll().forEach(e -> {
TagModel model = ModalTrans.tag(e);
List<ArticleTag> articleByTagAndOpen = articleTagMapper.findArticleByTagAndOpen(e.getId());
List<ArticleModel> articleModelList = new ArrayList<>();
articleByTagAndOpen.forEach(articleTag -> articleModelList.add(ModalTrans.article(articleTag.getArticle(), true)));
model.setArticles(articleModelList);
list.add(model);
});
return list;
}
}

View File

@@ -1,7 +1,10 @@
package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.enmu.RoleEnum;
import cn.celess.blog.entity.Response;
import cn.celess.blog.entity.User;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.QiniuResponse;
import cn.celess.blog.entity.model.UserModel;
import cn.celess.blog.entity.request.LoginReq;
@@ -26,7 +29,6 @@ import javax.servlet.http.HttpServletRequest;
import java.beans.Transient;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@@ -74,7 +76,8 @@ public class UserServiceImpl implements UserService {
if (userMapper.existsByEmail(email)) {
throw new MyException(ResponseEnum.USERNAME_HAS_EXIST);
}
boolean b = userMapper.addUser(email, MD5Util.getMD5(password)) == 1;
User user = new User(email, MD5Util.getMD5(password));
boolean b = userMapper.addUser(user) == 1;
if (b) {
String verifyId = UUID.randomUUID().toString().replaceAll("-", "");
redisUtil.setEx(email + "-verify", verifyId, 2, TimeUnit.DAYS);
@@ -116,11 +119,10 @@ public class UserServiceImpl implements UserService {
}
if (user.getPwd().equals(MD5Util.getMD5(loginReq.getPassword()))) {
logger.info("====> {} 进行权限认证 状态:登录成功 <====", loginReq.getEmail());
userMapper.updateLoginTime(loginReq.getEmail(), new Date());
userMapper.updateLoginTime(loginReq.getEmail());
redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime");
// redis 标记
redisUtil.setEx(loginReq.getEmail() + "-login", JSONObject.fromObject(user).toString(),
(loginReq.getIsRememberMe() ? JwtUtil.EXPIRATION_LONG_TIME : JwtUtil.EXPIRATION_SHORT_TIME), TimeUnit.MILLISECONDS);
redisUserUtil.set(user, loginReq.getIsRememberMe());
token = jwtUtil.generateToken(user, loginReq.getIsRememberMe());
} else {
logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail());
@@ -138,7 +140,7 @@ public class UserServiceImpl implements UserService {
redisUtil.setEx(loginReq.getEmail() + "-passwordWrongTime", count + "", 2, TimeUnit.HOURS);
throw new MyException(ResponseEnum.LOGIN_FAILURE);
}
UserModel trans = trans(user);
UserModel trans = ModalTrans.userFullInfo(user);
trans.setToken(token);
return trans;
@@ -159,13 +161,13 @@ public class UserServiceImpl implements UserService {
@Override
public UserModel update(String desc, String displayName) {
User user = redisUserUtil.get(request);
User user = redisUserUtil.get();
user.setDesc(desc);
user.setDisplayName(displayName);
userMapper.updateInfo(desc, displayName, user.getId());
redisUserUtil.set(user);
return trans(user);
return ModalTrans.userFullInfo(user);
}
@Override
@@ -177,34 +179,20 @@ public class UserServiceImpl implements UserService {
return role;
}
@Override
public User getUserInfoByEmail(String email) {
User user = userMapper.findByEmail(email);
if (user == null) {
throw new MyException(ResponseEnum.USER_NOT_EXIST);
}
return user;
}
@Override
public String getAvatarImg(long id) {
return userMapper.getAvatarImgUrlById(id);
}
@Override
public Object updateUserAavatarImg(InputStream is, String mime) {
User user = redisUserUtil.get(request);
User user = redisUserUtil.get();
QiniuResponse upload = qiniuService.uploadFile(is, user.getEmail() + "_" + user.getId() + mime.toLowerCase());
user.setAvatarImgUrl(upload.key);
userMapper.updateAvatarImgUrl(upload.key, user.getId());
redisUserUtil.set(user);
return ResponseUtil.success(user.getAvatarImgUrl());
return Response.success(user.getAvatarImgUrl());
}
@Override
public UserModel getUserInfoBySession() {
User user = redisUserUtil.get(request);
return trans(user);
User user = redisUserUtil.get();
return ModalTrans.userFullInfo(user);
}
@Override
@@ -212,18 +200,6 @@ public class UserServiceImpl implements UserService {
return userMapper.existsByEmail(email);
}
@Override
public String getNameById(long id) {
String name = userMapper.getDisPlayName(id);
if (name == null) {
name = userMapper.getEmail(id);
if (name == null) {
throw new MyException(ResponseEnum.USER_NOT_EXIST);
}
}
return name;
}
/**
* 找回密码
*/
@@ -255,7 +231,6 @@ public class UserServiceImpl implements UserService {
return "发送成功!";
}
//TODO
@Override
public Object sendVerifyEmail(String email) {
if (!RegexUtil.emailMatch(email)) {
@@ -367,14 +342,12 @@ public class UserServiceImpl implements UserService {
}
@Override
public PageInfo<UserModel> getUserList(Integer page, Integer count) {
public PageData<UserModel> getUserList(Integer page, Integer count) {
PageHelper.startPage(page, count);
List<User> all = userMapper.findAll();
PageInfo pageInfo = PageInfo.of(all);
List<UserModel> modelList = new ArrayList<>();
all.forEach(user -> modelList.add(trans(user)));
pageInfo.setList(modelList);
return pageInfo;
all.forEach(user -> modelList.add(ModalTrans.userFullInfo(user)));
return new PageData<UserModel>(PageInfo.of(all), modelList);
}
@Override
@@ -403,8 +376,7 @@ public class UserServiceImpl implements UserService {
user.setPwd(MD5Util.getMD5(userReq.getPwd()));
}
if (userReq.getRole() != null) {
// TODO:用enum存放角色分类
if ("user".equals(userReq.getRole()) || "admin".equals(userReq.getRole())) {
if (RoleEnum.USER_ROLE.getRoleName().equals(userReq.getRole()) || RoleEnum.ADMIN_ROLE.getRoleName().equals(userReq.getRole())) {
user.setRole(userReq.getRole());
} else {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
@@ -414,7 +386,6 @@ public class UserServiceImpl implements UserService {
if (!RegexUtil.emailMatch(userReq.getEmail())) {
throw new MyException(ResponseEnum.PARAMETERS_EMAIL_ERROR);
}
// TODO :: 邮件提醒
user.setEmail(userReq.getEmail());
}
// 数据写入
@@ -422,11 +393,11 @@ public class UserServiceImpl implements UserService {
if (updateResult == 0) {
throw new MyException(ResponseEnum.FAILURE);
}
if (redisUserUtil.get(request).getId().equals(userReq.getId())) {
if (redisUserUtil.get().getId().equals(userReq.getId())) {
redisUserUtil.set(user);
}
logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId());
return trans(user);
return ModalTrans.userFullInfo(user);
}
@Override
@@ -434,16 +405,17 @@ public class UserServiceImpl implements UserService {
return userMapper.existsByEmail(email);
}
private UserModel trans(User u) {
UserModel user = new UserModel();
user.setId(u.getId());
user.setAvatarImgUrl(u.getAvatarImgUrl() == null ? null : "http://cdn.celess.cn/" + u.getAvatarImgUrl());
user.setEmail(u.getEmail());
user.setDesc(u.getDesc());
user.setDisplayName(u.getDisplayName() == null ? u.getEmail() : u.getDisplayName());
user.setEmailStatus(u.getEmailStatus());
user.setRecentlyLandedDate(DateFormatUtil.get(u.getRecentlyLandedDate()));
user.setRole(u.getRole());
return user;
@Override
public UserModel setPwd(String pwd, String newPwd, String confirmPwd) {
User user = redisUserUtil.get();
String pwd1 = userMapper.getPwd(user.getEmail());
if (!MD5Util.getMD5(pwd).equals(pwd1)) {
throw new MyException(ResponseEnum.PWD_WRONG);
}
if (!newPwd.equals(confirmPwd)) {
throw new MyException(ResponseEnum.PWD_NOT_SAME);
}
userMapper.updatePwd(user.getEmail(), MD5Util.getMD5(newPwd));
return ModalTrans.userFullInfo(userMapper.findByEmail(user.getEmail()));
}
}

View File

@@ -2,6 +2,7 @@ package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Visitor;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.VisitorModel;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.VisitorMapper;
@@ -45,12 +46,10 @@ public class VisitorServiceImpl implements VisitorService {
}
@Override
public PageInfo<VisitorModel> visitorPage(int page, int count, boolean showLocation) {
public PageData<VisitorModel> visitorPage(int page, int count, boolean showLocation) {
PageHelper.startPage(page, count);
List<Visitor> visitorList = visitorMapper.findAll();
PageInfo pageInfo = new PageInfo(visitorList);
pageInfo.setList(list2List(visitorList, showLocation));
return pageInfo;
return new PageData<VisitorModel>(new PageInfo<Visitor>(visitorList), list2List(visitorList, showLocation));
}
@Override

View File

@@ -2,16 +2,25 @@ package cn.celess.blog.service.serviceimpl;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.WebUpdate;
import cn.celess.blog.entity.model.PageData;
import cn.celess.blog.entity.model.WebUpdateModel;
import cn.celess.blog.exception.MyException;
import cn.celess.blog.mapper.WebUpdateInfoMapper;
import cn.celess.blog.service.WebUpdateInfoService;
import cn.celess.blog.util.DateFormatUtil;
import cn.celess.blog.util.HttpUtil;
import cn.celess.blog.util.ModalTrans;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -21,6 +30,7 @@ import java.util.List;
* @date : 2019/05/12 11:43
*/
@Service
@Slf4j
public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
@Autowired
WebUpdateInfoMapper webUpdateInfoMapper;
@@ -31,11 +41,11 @@ public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
if (info == null || info.replaceAll(" ", "").isEmpty()) {
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
}
WebUpdate webUpdate = new WebUpdate(info, new Date());
WebUpdate webUpdate = new WebUpdate(info);
if (webUpdateInfoMapper.insert(webUpdate) == 0) {
throw new MyException(ResponseEnum.FAILURE);
}
return trans(webUpdate);
return ModalTrans.webUpdate(webUpdateInfoMapper.findById(webUpdate.getId()));
}
@Override
@@ -57,43 +67,46 @@ public class WebUpdateInfoServiceImpl implements WebUpdateInfoService {
}
webUpdate.setUpdateInfo(info);
webUpdateInfoMapper.update(id, info);
return trans(webUpdate);
return ModalTrans.webUpdate(webUpdate);
}
@Override
public PageInfo<WebUpdateModel> pages(int count, int page) {
public PageData<WebUpdateModel> pages(int count, int page) {
PageHelper.startPage(page, count);
List<WebUpdate> updateList = webUpdateInfoMapper.findAll();
PageInfo pageInfo = new PageInfo(updateList);
pageInfo.setList(list2List(updateList));
return pageInfo;
return new PageData<WebUpdateModel>(new PageInfo<WebUpdate>(updateList), list2List(updateList));
}
@Override
public List<WebUpdateModel> findAll() {
List<WebUpdate> all = webUpdateInfoMapper.findAll();
List<WebUpdateModel> webUpdateModels = new ArrayList<>();
for (WebUpdate w : all) {
webUpdateModels.add(trans(w));
}
return webUpdateModels;
return list2List(all);
}
@Override
public String getLastestUpdateTime() {
return DateFormatUtil.get(webUpdateInfoMapper.getLastestOne());
public JSONObject getLastestUpdateTime() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("lastUpdateTime", DateFormatUtil.get(webUpdateInfoMapper.getLastestOne().getUpdateTime()));
jsonObject.put("lastUpdateInfo", webUpdateInfoMapper.getLastestOne().getUpdateInfo());
try {
JSONArray array = JSONArray.fromObject(HttpUtil.get("https://api.github.com/repos/xiaohai2271/blog-frontEnd/commits?page=1&per_page=1"));
JSONObject object = array.getJSONObject(0);
JSONObject commit = object.getJSONObject("commit");
jsonObject.put("lastCommit", commit.getString("message"));
jsonObject.put("committerAuthor", commit.getJSONObject("committer").getString("name"));
SimpleDateFormat sdf = new SimpleDateFormat();
Instant parse = Instant.parse(commit.getJSONObject("committer").getString("date"));
jsonObject.put("committerDate", DateFormatUtil.get(Date.from(parse)));
jsonObject.put("commitUrl", "https://github.com/xiaohai2271/blog-frontEnd/tree/" + object.getString("sha"));
} catch (IOException e) {
log.info("网络请求失败{}", e.getMessage());
}
return jsonObject;
}
private List<WebUpdateModel> list2List(List<WebUpdate> webUpdates) {
List<WebUpdateModel> webUpdateModels = new ArrayList<>();
for (WebUpdate w : webUpdates) {
webUpdateModels.add(trans(w));
}
webUpdates.forEach(update -> webUpdateModels.add(ModalTrans.webUpdate(update)));
return webUpdateModels;
}
private WebUpdateModel trans(WebUpdate webUpdate) {
return new WebUpdateModel(webUpdate.getId(), webUpdate.getUpdateInfo(), DateFormatUtil.get(webUpdate.getUpdateTime()));
}
}

View File

@@ -0,0 +1,51 @@
package cn.celess.blog.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* @Author: 小海
* @Date: 2020-04-23 15:51
* @Desc:
*/
public class HttpUtil {
public static String get(String urlStr) throws IOException {
StringBuffer sb = new StringBuffer();
HttpURLConnection urlConnection = null;
try {
URL url = new URL(urlStr);
//打开http
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
try (
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
) {
//将bufferReader的值给放到buffer里
String str = null;
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
}
} finally {
//断开连接
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return sb.toString();
}
}

View File

@@ -1,10 +1,11 @@
package cn.celess.blog.util;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import cn.celess.blog.exception.MyException;
import io.jsonwebtoken.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Instant;
@@ -18,23 +19,22 @@ import java.util.Map;
* @Description: JWT工具类
*/
@Component
@Log4j2
public class JwtUtil {
private static final String CLAIM_KEY_USERNAME = "sub";
/**
* 5天(毫秒)
*/
public static final long EXPIRATION_LONG_TIME = 432000000;
/**
* 两小时(毫秒)
*/
public static final long EXPIRATION_SHORT_TIME = 7200000;
private static final String CLAIM_KEY_USERNAME = "sub";
/**
* JWT 秘钥需自行设置不可泄露
*/
private static final String SECRET = "xxx";
@Value("${jwt.secret}")
private String SECRET;
public String generateToken(User user, boolean isRemember) {
Map<String, Object> claims = new HashMap<>(16);
@@ -47,46 +47,63 @@ public class JwtUtil {
.compact();
}
public Boolean validateToken(String token, User user) {
String username = getUsernameFromToken(token);
return (username.equals(user.getEmail()) && !isTokenExpired(token));
public String updateTokenDate(String token) {
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
return Jwts.builder()
.setClaims(claims)
.setExpiration(new Date(claims.getExpiration().getTime() + EXPIRATION_SHORT_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
}
/**
* 获取token是否过期
*/
public Boolean isTokenExpired(String token) {
try {
Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
} catch (ExpiredJwtException e) {
return true;
}
return expiration == null || expiration.before(new Date());
}
/**
* 根据token获取username
*/
public String getUsernameFromToken(String token) {
return getClaimsFromToken(token).getSubject();
Claims claims = getClaimsFromToken(token);
return claims == null ? null : claims.getSubject();
}
/**
* 获取token的过期时间
*/
public Date getExpirationDateFromToken(String token) {
return getClaimsFromToken(token).getExpiration();
Claims claims = getClaimsFromToken(token);
return claims == null ? null : claims.getExpiration();
}
/**
* 解析JWT
*/
private Claims getClaimsFromToken(String token) {
Claims claims = Jwts.parser()
Claims claims = null;
try {
claims = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException e) {
log.info("JWT令牌过期");
} catch (UnsupportedJwtException e) {
log.info("不支持的JWT令牌");
throw new MyException(ResponseEnum.JWT_NOT_SUPPORT);
} catch (MalformedJwtException e) {
log.info("JWT令牌格式错误");
throw new MyException(ResponseEnum.JWT_MALFORMED);
} catch (SignatureException e) {
log.info("JWT签名错误");
throw new MyException(ResponseEnum.JWT_SIGNATURE);
} catch (IllegalArgumentException e) {
log.debug("JWT非法参数");
}
return claims;
}

View File

@@ -0,0 +1,109 @@
package cn.celess.blog.util;
import cn.celess.blog.entity.*;
import cn.celess.blog.entity.model.*;
import org.springframework.beans.BeanUtils;
/**
* @Author: 小海
* @Date: 2020-05-24 18:04
* @Desc:
*/
public class ModalTrans {
public static ArticleModel article(Article article) {
if (article == null) {
return null;
}
ArticleModel articleModel = new ArticleModel();
BeanUtils.copyProperties(article, articleModel);
articleModel.setPublishDateFormat(DateFormatUtil.get(article.getPublishDate()));
articleModel.setUpdateDateFormat(DateFormatUtil.get(article.getUpdateDate()));
articleModel.setOriginal(article.getType());
articleModel.setCategory(article.getCategory().getName());
articleModel.setAuthor(user(article.getUser()));
articleModel.getTags().forEach(tag -> {
tag.setCategory(null);
tag.setDeleted(null);
});
return articleModel;
}
public static ArticleModel article(Article article, boolean noMdContent) {
ArticleModel article1 = article(article);
if (!noMdContent || article1 == null) {
return article1;
}
article1.setMdContent(null);
article1.setOpen(null);
return article1;
}
public static UserModel userFullInfo(User user) {
if (user == null || user.getId() == -1) {
return null;
}
UserModel userModel = new UserModel();
BeanUtils.copyProperties(user, userModel);
userModel.setAvatarImgUrl(user.getAvatarImgUrl() == null || user.getAvatarImgUrl().length() == 0 ?
null :
"http://cdn.celess.cn/" + user.getAvatarImgUrl());
userModel.setDisplayName(user.getDisplayName() == null ? user.getEmail() : user.getDisplayName());
userModel.setRecentlyLandedDate(DateFormatUtil.get(user.getRecentlyLandedDate()));
return userModel;
}
public static UserModel user(User user) {
UserModel model = userFullInfo(user);
if (model == null) {
return null;
}
model.setRole(null);
model.setEmailStatus(null);
return model;
}
public static CategoryModel category(Category category) {
if (category == null) {
return null;
}
CategoryModel model = new CategoryModel();
BeanUtils.copyProperties(category, model);
return model;
}
public static TagModel tag(Tag tag) {
if (tag == null) {
return null;
}
TagModel model = new TagModel();
BeanUtils.copyProperties(tag, model);
return model;
}
public static WebUpdateModel webUpdate(WebUpdate update) {
if (update == null) {
return null;
}
WebUpdateModel model = new WebUpdateModel();
model.setId(update.getId());
model.setInfo(update.getUpdateInfo());
model.setTime(DateFormatUtil.get(update.getUpdateTime()));
return model;
}
public static CommentModel comment(Comment comment) {
if (comment == null) {
return null;
}
CommentModel model = new CommentModel();
BeanUtils.copyProperties(comment, model);
model.setFromUser(user(comment.getFromUser()));
model.setToUser(user(comment.getToUser()));
model.setDate(DateFormatUtil.get(comment.getDate()));
return model;
}
}

View File

@@ -20,16 +20,18 @@ public class RedisUserUtil {
RedisUtil redisUtil;
@Autowired
JwtUtil jwtUtil;
@Autowired
HttpServletRequest request;
public User get(HttpServletRequest request) {
User user = getWithOutExc(request);
public User get() {
User user = getWithOutExc();
if (user == null) {
throw new MyException(ResponseEnum.HAVE_NOT_LOG_IN);
}
return user;
}
public User getWithOutExc(HttpServletRequest request) {
public User getWithOutExc() {
String token = request.getHeader("Authorization");
if (token == null || token.isEmpty()) {
return null;
@@ -39,8 +41,16 @@ public class RedisUserUtil {
}
public User set(User user) {
Long expire = redisUtil.getExpire(user.getEmail() + "-login");
redisUtil.setEx(user.getEmail() + "-login", JSONObject.fromObject(user).toString(),
redisUtil.getExpire(user.getEmail() + "-login"), TimeUnit.MILLISECONDS);
expire > 0 ? expire : JwtUtil.EXPIRATION_SHORT_TIME, TimeUnit.MILLISECONDS);
return user;
}
public User set(User user, boolean isRemember) {
redisUtil.setEx(user.getEmail() + "-login", JSONObject.fromObject(user).toString(),
isRemember ? JwtUtil.EXPIRATION_LONG_TIME : JwtUtil.EXPIRATION_SHORT_TIME, TimeUnit.MILLISECONDS);
request.getSession().setAttribute("email", user.getEmail());
return user;
}
}

View File

@@ -20,8 +20,8 @@ import java.util.concurrent.TimeUnit;
* Redis工具类
*
* @author WangFan
* @date 2018-02-24 下午03:09:50
* @version 1.1 (GitHub文档: https://github.com/whvcse/RedisUtil )
* @date 2018-02-24 下午03:09:50
*/
@Component
@@ -29,14 +29,14 @@ public class RedisUtil {
@Autowired
private StringRedisTemplate redisTemplate;
public void setRedisTemplate(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public StringRedisTemplate getRedisTemplate() {
return this.redisTemplate;
}
public void setRedisTemplate(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
/** -------------------key相关操作--------------------- */
/**
@@ -196,6 +196,7 @@ public class RedisUtil {
/**
* 设置指定 key 的值
*
* @param key
* @param value
*/
@@ -205,6 +206,7 @@ public class RedisUtil {
/**
* 获取指定 key 的值
*
* @param key
* @return
*/
@@ -214,6 +216,7 @@ public class RedisUtil {
/**
* 返回 key 中字符串值的子字符
*
* @param key
* @param start
* @param end
@@ -259,10 +262,8 @@ public class RedisUtil {
* 设置ASCII码, 字符串'a'的ASCII码是97, 转为二进制是'01100001', 此方法是将二进制第offset位值变为value
*
* @param key
* @param postion
* 位置
* @param value
* 值,true为1, false为0
* @param offset 位置
* @param value 值,true为1, false为0
* @return
*/
public boolean setBit(String key, long offset, boolean value) {
@@ -274,10 +275,8 @@ public class RedisUtil {
*
* @param key
* @param value
* @param timeout
* 过期时间
* @param unit
* 时间单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES
* @param timeout 过期时间
* @param unit 时间单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES
* 秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS
*/
public void setEx(String key, String value, long timeout, TimeUnit unit) {
@@ -300,8 +299,7 @@ public class RedisUtil {
*
* @param key
* @param value
* @param offset
* 从指定位置开始覆写
* @param offset 从指定位置开始覆写
*/
public void setRange(String key, String value, long offset) {
redisTemplate.opsForValue().set(key, value, offset);
@@ -340,7 +338,7 @@ public class RedisUtil {
* 增加(自增长), 负数则为自减
*
* @param key
* @param value
* @param increment
* @return
*/
public Long incrBy(String key, long increment) {
@@ -348,9 +346,8 @@ public class RedisUtil {
}
/**
*
* @param key
* @param value
* @param increment
* @return
*/
public Double incrByFloat(String key, double increment) {
@@ -526,10 +523,8 @@ public class RedisUtil {
* 获取列表指定范围内的元素
*
* @param key
* @param start
* 开始位置, 0是开始位置
* @param end
* 结束位置, -1返回所有
* @param start 开始位置, 0是开始位置
* @param end 结束位置, -1返回所有
* @return
*/
public List<String> lRange(String key, long start, long end) {
@@ -548,7 +543,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param value
* @return
@@ -558,7 +552,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param value
* @return
@@ -591,7 +584,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param value
* @return
@@ -601,7 +593,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param value
* @return
@@ -611,7 +602,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param value
* @return
@@ -647,8 +637,7 @@ public class RedisUtil {
* 通过索引设置列表元素的值
*
* @param key
* @param index
* 位置
* @param index 位置
* @param value
*/
public void lSet(String key, long index, String value) {
@@ -669,10 +658,8 @@ public class RedisUtil {
* 移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
*
* @param key
* @param timeout
* 等待时间
* @param unit
* 时间单位
* @param timeout 等待时间
* @param unit 时间单位
* @return
*/
public String lBLeftPop(String key, long timeout, TimeUnit unit) {
@@ -693,10 +680,8 @@ public class RedisUtil {
* 移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
*
* @param key
* @param timeout
* 等待时间
* @param unit
* 时间单位
* @param timeout 等待时间
* @param unit 时间单位
* @return
*/
public String lBRightPop(String key, long timeout, TimeUnit unit) {
@@ -734,8 +719,7 @@ public class RedisUtil {
* 删除集合中值等于value得元素
*
* @param key
* @param index
* index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素;
* @param index index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素;
* index<0, 从尾部开始删除第一个值等于value的元素;
* @param value
* @return
@@ -981,8 +965,6 @@ public class RedisUtil {
* 获取集合所有元素
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
public Set<String> setMembers(String key) {
@@ -1022,7 +1004,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param options
* @return
@@ -1046,7 +1027,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param values
* @return
@@ -1056,7 +1036,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param values
* @return
@@ -1103,10 +1082,8 @@ public class RedisUtil {
* 获取集合的元素, 从小到大排序
*
* @param key
* @param start
* 开始位置
* @param end
* 结束位置, -1查询所有
* @param start 开始位置
* @param end 结束位置, -1查询所有
* @return
*/
public Set<String> zRange(String key, long start, long end) {
@@ -1130,10 +1107,8 @@ public class RedisUtil {
* 根据Score值查询集合元素
*
* @param key
* @param min
*
* @param max
* 最大值
* @param min 最小值
* @param max
* @return
*/
public Set<String> zRangeByScore(String key, double min, double max) {
@@ -1144,10 +1119,8 @@ public class RedisUtil {
* 根据Score值查询集合元素, 从小到大排序
*
* @param key
* @param min
*
* @param max
* 最大值
* @param min 最小值
* @param max
* @return
*/
public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
@@ -1156,7 +1129,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param min
* @param max
@@ -1224,7 +1196,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param min
* @param max
@@ -1318,7 +1289,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param otherKeys
* @param destKey
@@ -1359,7 +1329,6 @@ public class RedisUtil {
}
/**
*
* @param key
* @param options
* @return
@@ -1370,6 +1339,7 @@ public class RedisUtil {
/**
* 获取Redis List 序列化
*
* @param key
* @param targetClass
* @param <T>

View File

@@ -1,59 +0,0 @@
package cn.celess.blog.util;
import cn.celess.blog.enmu.ResponseEnum;
import cn.celess.blog.entity.Response;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author : xiaohai
* @date : 2019/03/28 15:32
*/
@ResponseBody
public class ResponseUtil {
/**
* 成功相应
*
* @param result 结果
* @return
*/
public static Response success(Object result) {
Response response = new Response();
response.setCode(ResponseEnum.SUCCESS.getCode());
response.setMsg(ResponseEnum.SUCCESS.getMsg());
response.setDate(System.currentTimeMillis());
response.setResult(result);
return response;
}
/**
* 失败的响应
*
* @param result 结果
* @return
*/
public static Response failure(String result) {
Response response = new Response();
response.setCode(ResponseEnum.FAILURE.getCode());
response.setMsg(ResponseEnum.FAILURE.getMsg());
response.setDate(System.currentTimeMillis());
response.setResult(result);
return response;
}
/**
* 其他的响应
*
* @param r 枚举常量
* @param result 结果
* @return
*/
public static Response response(ResponseEnum r, String result) {
Response response = new Response();
response.setCode(r.getCode());
response.setMsg(r.getMsg());
response.setDate(System.currentTimeMillis());
response.setResult(result);
return response;
}
}

View File

@@ -24,6 +24,7 @@ import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Author: 小海
@@ -33,16 +34,29 @@ import java.util.Map;
@Component
public class SitemapGenerateUtil {
@Autowired
ArticleMapper articleMapper;
@Value("${sitemap.path}")
private String path;
private Map<String, String> urlList;
@Autowired
ArticleMapper articleMapper;
private static DocumentBuilder getDocumentBuilder() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return db;
}
@Async
public void createSitemap() {
initList();
if ("".equals(path) || "classpath".equals(path)) {
path = System.getProperty("user.dir") + "/sitemap.xml";
}
File file = new File(path);
try {
if (file.exists()) {
@@ -86,24 +100,12 @@ public class SitemapGenerateUtil {
urlList.put("https://www.celess.cn", DateFormatUtil.getForXmlDate(new Date()));
urlList.put("https://www.celess.cn/links", DateFormatUtil.getForXmlDate(new Date()));
urlList.put("https://www.celess.cn/leaveMsg", DateFormatUtil.getForXmlDate(new Date()));
List<Article> articles = articleMapper.findAll();
List<Article> articles = articleMapper.findAll().stream().filter(article -> article.getOpen()&&!article.isDeleted()).collect(Collectors.toList());
articles.forEach(article -> {
urlList.put("https://www.celess.cn/article/" + article.getId(), DateFormatUtil.getForXmlDate(
article.getUpdateDate() == null ? article.getPublishDate() : article.getUpdateDate()));
});
}
private static DocumentBuilder getDocumentBuilder() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return db;
}
}

View File

@@ -1,5 +1,14 @@
server.port=8081
# 七牛的密钥配置
qiniu.accessKey=
qiniu.secretKey=
qiniu.bucket=
# sitemap 存放地址
sitemap.path=
# 生成JWT时候的密钥
jwt.secret=
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=update
# 上传单个文件的大小

View File

@@ -1,80 +0,0 @@
server.port=8081
sitemap.path=C:\\Users\\zh564\\Desktop\\sitemap.xml
##spring.jpa.show-sql=false
##spring.jpa.hibernate.ddl-auto=update
mybatis.type-handlers-package=cn.celess.blog.mapper.typehandler
# 上传单个文件的大小
spring.servlet.multipart.max-file-size=10MB
# 上传文件的总大小
spring.servlet.multipart.max-request-size=10MB
spring.jackson.default-property-inclusion=non_null
################# 数据库 ##################
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test_blog?serverTimezone=UCT&allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=zhenghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
################## mybatis ##################
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=cn.celess.blog.entity
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql
#### 用于nginx的代理 获取真实ip
server.use-forward-headers = true
server.tomcat.remote-ip-header = X-Real-IP
server.tomcat.protocol-header = X-Forwarded-Proto
############### email ##############
spring.mail.host=smtp.163.com
spring.mail.username=
spring.mail.password=
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.default-encoding=UTF-8
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback=false
############### redis ##############
# REDIS (RedisProperties)
# Redis数据库索引默认为0
spring.redis.database=1
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码默认为空
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=-1
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000

View File

@@ -3,3 +3,5 @@ spring.profiles.active=prod
####cn.celess.blog.service.serviceimpl.QiniuServiceImpl
logging.level.cn.celess.blog=debug
logging.level.cn.celess.blog.mapper=info
## 修改openSource 添加-test 文件用于测试 -prod文件用于线上发布

View File

@@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.celess.blog.mapper.ArticleTagMapper">
<resultMap id="articleTagResultMap" type="cn.celess.blog.entity.ArticleTag">
<id column="at_id" property="id"/>
<result column="a_id" property="article.id"/>
<result column="t_id" property="tag.id"/>
<association property="article" column="a_id" resultMap="cn.celess.blog.mapper.ArticleMapper.articleResultMap"
javaType="cn.celess.blog.entity.Article">
</association>
<association property="tag" column="t_id" resultMap="cn.celess.blog.mapper.CategoryMapper.categoryResultMap"
javaType="cn.celess.blog.entity.TagCategory">
</association>
</resultMap>
<!--新增-->
<insert id="insert" keyProperty="id" useGeneratedKeys="true">
insert into article_tag(a_id, t_id)
values (#{article.id}, #{tag.id})
</insert>
<!--通过主键修改数据-->
<update id="update">
update article_tag
<set>
<if test="article!=null and article.id != null">
a_id = #{article.id},
</if>
<if test="tag!=null and tag.id != null">
t_id = #{tag.id},
</if>
</set>
where at_id = #{id}
</update>
<!--通过主键删除-->
<delete id="deleteById">
delete
from article_tag
where at_id = #{id};
</delete>
<delete id="deleteMultiById">
delete from article_tag where at_id in
<foreach item="item" collection="list" open="(" close=")" separator=",">
#{item.id}
</foreach>
</delete>
<!--通过主键删除-->
<update id="deleteByArticleId">
delete
from article_tag
where a_id = #{id}
</update>
<select id="findAllByArticleId" resultMap="articleTagResultMap">
select *
from article_tag,
tag_category
where a_id = #{articleId}
and article_tag.t_id = tag_category.t_id
</select>
<select id="findOneById" resultMap="articleTagResultMap">
select *
from article_tag,
article,
tag_category
where article_tag.at_id = #{id}
and article_tag.a_id = article.a_id
and tag_category.t_id = article_tag.t_id
</select>
<select id="findArticleByTag" resultMap="articleTagResultMap">
select *
from tag_category,
article,
article_tag
where tag_category.t_id = #{tagId}
and is_category = false
and tag_category.t_id = article_tag.t_id
and article_tag.a_id = article.a_id
</select>
<select id="findArticleByTagAndOpen" resultMap="articleTagResultMap">
select *
from tag_category,
article,
article_tag
where tag_category.t_id = #{tagId}
and is_category = false
and tag_category.t_id = article_tag.t_id
and article.a_is_open = true
and article_tag.a_id = article.a_id
</select>
</mapper>

View File

@@ -2,83 +2,92 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.celess.blog.mapper.CategoryMapper">
<resultMap id="categoryResultMap" type="cn.celess.blog.entity.Category">
<id column="c_id" property="id"/>
<result column="c_name" property="name"/>
<id column="t_id" property="id"/>
<result column="t_name" property="name"/>
<result column="is_category" property="category"/>
<result column="is_delete" property="deleted"/>
</resultMap>
<insert id="insert">
insert into category (c_name, articles)
values (#{name}, #{articles});
<selectKey resultType="java.lang.Long" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into tag_category (t_name, is_category)
values (#{name}, true);
</insert>
<update id="update">
update category
set c_name=#{name},
articles=#{articles}
where c_id = #{id}
update tag_category
set t_name=#{name}
where t_id = #{id}
and is_category = true
</update>
<delete id="delete">
delete
from category
where c_id = #{id}
</delete>
<update id="delete">
update tag_category
set is_delete= true
where t_id = #{id}
and is_category = true
</update>
<select id="findCategoryByName" resultMap="categoryResultMap">
select *
from category
where c_name = #{name}
from tag_category
where t_name = #{name}
and is_category = true
</select>
<select id="findCategoryById" resultMap="categoryResultMap">
select *
from category
where c_id = #{id}
from tag_category
where t_id = #{id}
and is_category = true
</select>
<select id="findAll" resultMap="categoryResultMap">
select *
from category
from tag_category
where is_category = true
</select>
<select id="getAllName" resultType="java.lang.String">
select c_name
from category
select t_name
from tag_category
where is_category = true
</select>
<select id="getNameById" resultType="java.lang.String">
select c_name
from category
where c_id = #{id}
select t_name
from tag_category
where is_category = true
and t_id = #{id}
</select>
<select id="getIDByName" resultType="java.lang.Long">
select c_id
from category
where c_name = #{name}
<select id="getIdByName" resultType="java.lang.Long">
select t_id
from tag_category
where is_category = true
and t_name = #{name}
</select>
<select id="existsByName" resultType="java.lang.Boolean">
SELECT EXISTS(SELECT * FROM category WHERE c_name = #{name})
SELECT EXISTS(SELECT * FROM tag_category WHERE t_name = #{name} and is_category = true)
</select>
<select id="existsById" resultType="java.lang.Boolean">
SELECT EXISTS(SELECT * FROM category WHERE c_id = #{id})
SELECT EXISTS(SELECT * FROM tag_category WHERE t_id = #{id})
</select>
<select id="getLastestCategory" resultMap="categoryResultMap">
select *
from category
order by c_id desc
from tag_category
where is_category = true
order by t_id desc
limit 1;
</select>
<select id="count" resultType="java.lang.Long">
select count(*)
from category;
from tag_category
where is_category = true
and is_delete = false;
</select>
</mapper>

View File

@@ -3,21 +3,42 @@
<mapper namespace="cn.celess.blog.mapper.CommentMapper">
<resultMap id="commentResultMap" type="cn.celess.blog.entity.Comment">
<id column="co_id" property="id"/>
<result column="co_article_id" property="articleID"/>
<result column="is_comment" property="type"/>
<result column="author_id" property="authorID"/>
<result column="co_page_path" property="pagePath"/>
<result column="co_status" property="status"/>
<result column="co_content" property="content"/>
<result column="co_date" property="date"/>
<result column="co_pid" property="pid"/>
<result column="co_response_id" property="responseId"/>
<result column="co_from_author_id" property="fromUser.id"/>
<result column="co_to_author_id" property="toUser.id"/>
</resultMap>
<insert id="insert">
insert into comment (co_article_id, is_comment, author_id, co_content, co_date, co_pid)
VALUES (#{articleID}, #{type}, #{authorID}, #{content}, #{date}, #{pid})
<selectKey resultType="java.lang.Long" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
<resultMap id="commentViewResultMap" type="cn.celess.blog.entity.Comment">
<id column="commentId" property="id"/>
<result column="pagePath" property="pagePath"/>
<result column="status" property="status"/>
<result column="content" property="content"/>
<result column="date" property="date"/>
<result column="pid" property="pid"/>
<result column="fromAuthorId" property="fromUser.id"/>
<result column="toAuthorId" property="toUser.id"/>
<association property="fromUser" column="fromAuthorId" javaType="cn.celess.blog.entity.User">
<id column="fromAuthorId" property="id"/>
<result column="fromAuthorEmail" property="email"/>
<result column="fromAuthorDisplayName" property="displayName"/>
<result column="fromAuthorAvatar" property="avatarImgUrl"/>
</association>
<association property="toUser" column="toAuthorId" javaType="cn.celess.blog.entity.User">
<id column="toAuthorId" property="id"/>
<result column="toAuthorEmail" property="email"/>
<result column="toAuthorDisplayName" property="displayName"/>
<result column="toAuthorAvatar" property="avatarImgUrl"/>
</association>
</resultMap>
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into comment (co_page_path, co_content, co_date, co_pid, co_from_author_id, co_to_author_id, co_status)
VALUES (#{pagePath}, #{content}, now(), #{pid}, #{fromUser.id}, #{toUser.id}, 0)
</insert>
<update id="updateContent">
@@ -26,73 +47,85 @@
where co_id = #{id}
</update>
<update id="updateResponder">
<update id="delete">
update comment
set co_response_id =#{responder}
set co_status = 3
where co_id = #{id}
</update>
<delete id="delete">
delete
from comment
where co_id = #{id}
</delete>
<delete id="deleteByArticleId">
delete
from comment
where co_article_id = #{articleId}
</delete>
<update id="deleteByPagePath">
update comment
set co_status = 3
where co_page_path = #{path}
</update>
<select id="existsById" resultType="java.lang.Boolean">
SELECT EXISTS(SELECT * FROM comment WHERE co_id = #{id})
</select>
<select id="findCommentById" resultMap="commentResultMap">
<select id="findCommentById" resultMap="commentViewResultMap">
select *
from comment
where co_id = #{id}
from commentView
where commentId = #{sqid}
</select>
<select id="findAllByAuthorIDAndType" resultMap="commentResultMap">
<select id="findAllByFromUser" resultMap="commentViewResultMap">
select *
from comment
where author_id = #{id}
and is_comment = #{isComment}
from commentView
where fromAuthorId = #{id}
</select>
<select id="findAllByPId" resultMap="commentResultMap">
<select id="findAllByPid" resultMap="commentViewResultMap">
select *
from comment
where co_pid = #{pid}
from commentView
where pid = #{pid}
</select>
<select id="findAllByArticleID" resultMap="commentResultMap">
<select id="findAllByPagePath" resultMap="commentViewResultMap" parameterType="string">
select *
from comment
where co_article_id = #{articleId}
from commentView
<if test="toString() != null ">
where pagePath = #{pagePath}
</if>
</select>
<select id="findAllByArticleIDAndPId" resultMap="commentResultMap">
<select id="findAllByPagePathAndFromUser" resultMap="commentViewResultMap">
select *
from comment
where co_article_id = #{articleID}
and co_pid = #{pid}
from commentView
where
<if test="pagePath != null ">
pagePath = #{pagePath} and
</if>
fromAuthorId = #{userId}
</select>
<select id="findCommentsByTypeAndPId" resultMap="commentResultMap">
<select id="findAllByPagePathAndPidAndNormal" resultMap="commentViewResultMap">
select *
from comment
where is_comment = #{isComment}
and co_pid = #{pid}
from commentView
where
<if test="pagePath != null ">
pagePath = #{pagePath} and
</if>
pid = #{pid} and status = 0
</select>
<select id="findAllByType" resultMap="commentResultMap">
select *
from comment
where is_comment = #{isComment}
</select>
<select id="countByType" resultType="java.lang.Long">
<select id="countByPagePath" resultType="java.lang.Long">
select count(*)
from comment
where is_comment = #{isComment}
from commentView
where pagePath = #{pagePath}
</select>
<select id="getLastestComment" resultMap="commentResultMap">
<select id="getLastestComment" resultMap="commentViewResultMap">
select *
from comment
order by co_id desc
from commentView
order by commentId desc
limit 1
</select>
<select id="count" resultType="long">
select count(*)
from comment
where co_status = 0;
</select>
</mapper>

View File

@@ -2,69 +2,71 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.celess.blog.mapper.PartnerMapper">
<resultMap id="partnerSiteResultMap" type="cn.celess.blog.entity.PartnerSite">
<id column="site_id" property="id"/>
<result column="site_name" property="name"/>
<result column="site_url" property="url"/>
<result column="is_open" property="open"/>
<id column="l_id" property="id"/>
<result column="l_name" property="name"/>
<result column="l_url" property="url"/>
<result column="l_is_open" property="open"/>
<result column="l_icon_path" property="iconPath"/>
<result column="l_desc" property="desc"/>
<result column="is_delete" property="delete"/>
</resultMap>
<insert id="insert" parameterType="cn.celess.blog.entity.PartnerSite">
insert into links (site_name, is_open, site_url)
values (#{name}, #{open}, #{url})
<selectKey resultType="java.lang.Long" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
<insert id="insert" parameterType="cn.celess.blog.entity.PartnerSite" useGeneratedKeys="true" keyProperty="id">
insert into links (l_name, l_is_open, l_url, l_icon_path, l_desc, is_delete)
values (#{name}, #{open}, #{url}, #{iconPath}, #{desc}, false)
</insert>
<update id="update" parameterType="cn.celess.blog.entity.PartnerSite">
update links set
<if test="name!=null">site_name=#{name},</if>
<if test="url!=null">site_url=#{url},</if>
<if test="open!=null">is_open=#{open}</if>
where site_id=#{id}
<if test="open!=null">l_is_open=#{open},</if>
<if test="iconPath!=null">l_icon_path=#{iconPath},</if>
<if test="desc!=null">l_desc=#{desc},</if>
<if test="url!=null">l_url=#{url},</if>
<if test="name!=null">l_name=#{name}</if>
where l_id=#{id}
</update>
<delete id="delete">
delete
from links
where site_id = #{id}
</delete>
<update id="delete">
update links
set is_delete = true
where l_id = #{id}
</update>
<select id="existsById" resultType="boolean">
SELECT EXISTS(SELECT * FROM links WHERE site_id = #{id})
SELECT EXISTS(SELECT * FROM links WHERE l_id = #{id})
</select>
<select id="existsByName" resultType="boolean">
SELECT EXISTS(SELECT * FROM links WHERE site_name = #{name})
SELECT EXISTS(SELECT * FROM links WHERE l_name = #{name})
</select>
<select id="existsByUrl" resultType="boolean">
SELECT EXISTS(SELECT * FROM links WHERE site_url = #{url})
SELECT EXISTS(SELECT * FROM links WHERE l_url = #{url})
</select>
<select id="findById" resultMap="partnerSiteResultMap">
select *
from links
where site_id = #{id}
where l_id = #{id}
</select>
<select id="findByName" resultMap="partnerSiteResultMap">
select *
from links
where site_name = #{name}
where l_name = #{name}
</select>
<select id="findByUrl" resultMap="partnerSiteResultMap">
select *
from links
where site_url = #{url}
where l_url = #{url}
</select>
<select id="getLastest" resultMap="partnerSiteResultMap">
select *
from links
order by site_id desc
order by l_id desc
limit 1
</select>
<select id="findAll" resultMap="partnerSiteResultMap">

View File

@@ -4,68 +4,74 @@
<resultMap id="userResultMap" type="cn.celess.blog.entity.User">
<id column="u_id" property="id"/>
<result column="u_email" property="email"/>
<result column="u_uid" property="uid"/>
<result column="u_pwd" property="pwd"/>
<result column="email_status" property="emailStatus"/>
<result column="u_email_status" property="emailStatus"/>
<result column="u_avatar" property="avatarImgUrl"/>
<result column="u_desc" property="desc"/>
<result column="recently_landed_time" property="recentlyLandedDate"/>
<result column="email_verify_id" property="emailVerifyId"/>
<result column="display_name" property="displayName"/>
<result column="role" property="role"/>
<result column="u_recently_landed_time" property="recentlyLandedDate"/>
<result column="u_display_name" property="displayName"/>
<result column="u_role" property="role"/>
<result column="status" property="status"/>
</resultMap>
<insert id="addUser">
<insert id="addUser" useGeneratedKeys="true" keyProperty="id">
insert into user(u_email, u_pwd)
values (#{email}, #{pwd})
</insert>
<update id="updateInfo">
update user set
<if test="desc!=null">`u_desc`=#{desc},</if>
<if test="displayName!=null">`display_name`=#{displayName}</if>
<if test="desc!=null">u_desc=#{desc},</if>
<if test="displayName!=null">u_display_name=#{displayName}</if>
where u_id=#{id}
</update>
<update id="updateLoginTime">
update user
set `recently_landed_time`=#{date}
where `u_email` = #{email}
set u_recently_landed_time=now()
where u_email = #{email}
</update>
<update id="updateAvatarImgUrl">
update user
set `u_avatar`=#{avatarImgUrl}
where `u_id` = #{id}
set u_avatar=#{avatarImgUrl}
where u_id = #{id}
</update>
<update id="updateEmailStatus">
update user
set `email_status`=#{status}
where `u_email` = #{email}
set u_email_status=#{status}
where u_email = #{email}
</update>
<update id="updatePwd">
update user
set `u_pwd`=#{pwd}
where `u_email` = #{email}
set u_pwd=#{pwd}
where u_email = #{email}
</update>
<update id="setUserRole">
update user
set role=#{role}
where u_id = #{uid}
set u_role=#{role}
where u_id = #{id}
</update>
<update id="update">
update user
set `u_email` = #{email},
`u_pwd` = #{pwd},
`email_status` = #{emailStatus},
`u_desc` = #{desc},
`display_name` = #{displayName},
`role` = #{role}
where `u_id` = #{id}
</update>
<delete id="delete">
delete
from user
set u_email = #{email},
u_pwd = #{pwd},
u_email_status = #{emailStatus},
u_desc = #{desc},
u_display_name = #{displayName},
u_avatar = #{avatarImgUrl},
u_role = #{role}
where u_id = #{id}
</delete>
</update>
<update id="delete">
update user
set status= 2
where u_id = #{id}
</update>
<update id="lock">
update user
set status= 1
where u_id = #{id}
</update>
<select id="existsByEmail" resultType="java.lang.Boolean">
select exists(select * from user where u_email = #{email})
@@ -96,7 +102,7 @@
</select>
<select id="getDisPlayName" resultType="java.lang.String">
select display_name
select u_display_name
from user
where u_id = #{id}
</select>
@@ -107,16 +113,17 @@
where u_email = #{email}
</select>
<select id="getRoleByEmail" resultType="java.lang.String">
select role
select u_role
from user
where u_email = #{emai}
</select>
<select id="count" resultType="java.lang.Long">
select count(*)
from user
where status =0;
</select>
<select id="getRoleById" resultType="java.lang.String">
select role
select u_role
from user
where u_id = #{id}
</select>

View File

@@ -6,23 +6,29 @@
<result column="v_date" property="date"/>
<result column="v_user_agent" property="ua"/>
<result column="v_ip" property="ip"/>
<result column="is_delete" property="delete"/>
</resultMap>
<insert id="insert">
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into visitor (v_date, v_ip, v_user_agent)
values (#{date}, #{ip}, #{ua})
<selectKey resultType="java.lang.Long" keyProperty="id">
SELECT LAST_INSERT_ID() AS id
</selectKey>
</insert>
<delete id="delete">
delete
from visitor
<update id="delete">
update visitor
set is_delete = true
where v_id = #{id}
</delete>
</update>
<select id="findAll" resultMap="partnerSiteResultMap">
select *
from visitor order by v_id desc
from visitor
order by v_id desc
</select>
<select id="findAllNotDeleted" resultMap="partnerSiteResultMap">
select *
from visitor
where is_delete = false
order by v_id desc
</select>
<select id="count" resultType="java.lang.Long">
select count(*)

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