Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec0b17151c | ||
|
|
98430a34f6 | ||
|
|
23ee331609 | ||
|
|
ebddbc0ecf | ||
|
|
8181fab48d | ||
|
|
7ba287d261 | ||
|
|
1745a5d821 | ||
|
|
9a4a930426 | ||
|
|
a0eaddafec | ||
|
|
450f308f1e | ||
|
|
86bb5e1b13 | ||
|
|
a4c2ec1272 | ||
|
|
2945d091ee | ||
|
|
900d84b15e | ||
|
|
d9aac0fbd8 | ||
|
|
28aa7cf7e3 | ||
|
|
7972f4d473 | ||
|
|
79ec6fcc91 | ||
|
|
1f736dc9c9 | ||
|
|
55ccff3451 | ||
|
|
a5811364c7 | ||
|
|
a77dc695f6 | ||
|
|
753ea5c9a1 | ||
|
|
19e0697a01 |
30
.gitlab-ci.yml
Normal file
30
.gitlab-ci.yml
Normal file
@@ -0,0 +1,30 @@
|
||||
image: maven:3.3.9-jdk-8
|
||||
|
||||
cache:
|
||||
paths:
|
||||
- .m2/repository
|
||||
|
||||
stages:
|
||||
- test
|
||||
- deploy
|
||||
|
||||
|
||||
test:
|
||||
stage: test
|
||||
script:
|
||||
- cp "$APP_TEST" ./src/main/resources/application-test.properties
|
||||
- mvn clean test && cat target/site/jacoco/index.html
|
||||
|
||||
deploy:
|
||||
stage: deploy
|
||||
script:
|
||||
- cp "$APP_PROD" ./src/main/resources/application-prod.properties
|
||||
- mvn package -DskipTests
|
||||
- eval $(ssh-agent -s)
|
||||
- ssh-add <(echo "$SSH_PRIVATE_KEY" | base64 --decode)
|
||||
- mkdir -p ~/.ssh
|
||||
- chmod 700 ~/.ssh
|
||||
- ssh-keyscan celess.cn >> ~/.ssh/known_hosts
|
||||
- chmod 644 ~/.ssh/known_hosts
|
||||
- scp target/blog-0.0.1-SNAPSHOT.jar root@celess.cn:/www/wwwroot/api.celess.cn
|
||||
- ssh root@celess.cn "cd /www/wwwroot/api.celess.cn && bash build.sh"
|
||||
60
.mvn/wrapper/MavenWrapperDownloader.java
vendored
60
.mvn/wrapper/MavenWrapperDownloader.java
vendored
@@ -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
|
||||
* 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.
|
||||
*/
|
||||
|
||||
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());
|
||||
|
||||
BIN
.mvn/wrapper/maven-wrapper.jar
vendored
BIN
.mvn/wrapper/maven-wrapper.jar
vendored
Binary file not shown.
3
.mvn/wrapper/maven-wrapper.properties
vendored
3
.mvn/wrapper/maven-wrapper.properties
vendored
@@ -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
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# 小海博客后端管理系统
|
||||
|
||||
|
||||
|
||||
   [](https://www.celess.cn)
|
||||
## 基于Springboot的后端博客管理系统
|
||||
|
||||
|
||||
|
||||
8
build.sh
Normal file
8
build.sh
Normal 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 "更新结束"
|
||||
164
mvnw
vendored
164
mvnw
vendored
@@ -34,31 +34,32 @@
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
if [ -z "$MAVEN_SKIP_RC" ]; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
if [ -f /etc/mavenrc ]; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
if [ -f "$HOME/.mavenrc" ]; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
cygwin=false
|
||||
darwin=false
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
case "$(uname)" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true ;;
|
||||
Darwin*)
|
||||
darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
export JAVA_HOME="$(/usr/libexec/java_home)"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
@@ -66,97 +67,102 @@ case "`uname`" in
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -r /etc/gentoo-release ]; then
|
||||
JAVA_HOME=$(java-config --jre-home)
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
if [ -z "$M2_HOME" ]; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
while [ -h "$PRG" ]; do
|
||||
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
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
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
|
||||
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
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
readLink=$(which readlink)
|
||||
if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
|
||||
if $darwin; then
|
||||
javaHome="$(dirname \"$javaExecutable\")"
|
||||
javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
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
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
if [ -z "$JAVACMD" ]; then
|
||||
if [ -n "$JAVA_HOME" ]; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
JAVACMD="$(which java)"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
if [ ! -x "$JAVACMD" ]; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
@@ -166,22 +172,24 @@ 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
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
while [ "$wdir" != '/' ]; do
|
||||
if [ -d "$wdir"/.mvn ]; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
wdir=$(
|
||||
cd "$wdir/.."
|
||||
pwd
|
||||
)
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
@@ -191,13 +199,13 @@ find_maven_basedir() {
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
echo "$(tr -s '\n' ' ' <"$1")"
|
||||
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"
|
||||
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 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"
|
||||
elif command -v curl > /dev/null; then
|
||||
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
29
mvnw.cmd
vendored
@@ -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
|
||||
|
||||
20
pom.xml
20
pom.xml
@@ -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>
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,12 +41,16 @@ public class AuthenticationFilter implements HandlerInterceptor {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -21,14 +21,18 @@ 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));
|
||||
// 自增
|
||||
count = count == null ? 1 : ++count;
|
||||
// 更新
|
||||
visitDetail.put(RequestUtil.getCompleteUrlAndMethod(request), count);
|
||||
session.setAttribute("ip",request.getRemoteAddr());
|
||||
session.setAttribute("ip", request.getRemoteAddr());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +83,7 @@ public class ArticleController {
|
||||
ArticleModel article = articleService.retrieveOneByID(articleId, is4update);
|
||||
if (article.getOpen()) {
|
||||
return ResponseUtil.success(article);
|
||||
} else if (article.getAuthorId().equals(redisUserUtil.get(request).getId())) {
|
||||
} else if (article.getAuthorId().equals(redisUserUtil.get().getId())) {
|
||||
return ResponseUtil.success(article);
|
||||
}
|
||||
return ResponseUtil.response(ResponseEnum.PERMISSION_ERROR, null);
|
||||
|
||||
@@ -9,6 +9,7 @@ import cn.celess.blog.service.QiniuService;
|
||||
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;
|
||||
@@ -21,8 +22,10 @@ import javax.imageio.ImageIO;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
@@ -169,4 +172,45 @@ public class Other {
|
||||
jsonObject.put("message", "上传失败,请上传图片文件");
|
||||
response.getWriter().println(jsonObject.toString());
|
||||
}
|
||||
|
||||
@GetMapping("/bingPic")
|
||||
public Response bingPic() {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
try {
|
||||
//建立URL
|
||||
URL url = new URL("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN");
|
||||
|
||||
//打开http
|
||||
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
|
||||
urlConnection.setDoInput(true);
|
||||
urlConnection.setRequestMethod("GET");
|
||||
urlConnection.connect();
|
||||
|
||||
//获得输入
|
||||
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);
|
||||
}
|
||||
//关闭bufferReader和输入流
|
||||
bufferedReader.close();
|
||||
inputStreamReader.close();
|
||||
inputStream.close();
|
||||
//断开连接
|
||||
urlConnection.disconnect();
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return ResponseUtil.failure(null);
|
||||
}
|
||||
|
||||
JSONObject imageObj = JSONObject.fromObject(sb.toString());
|
||||
JSONArray jsonArray = imageObj.getJSONArray("images");
|
||||
String imageName = jsonArray.getJSONObject(0).getString("url");
|
||||
return ResponseUtil.success("https://cn.bing.com" + imageName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -56,12 +57,11 @@ public class TagController {
|
||||
@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() == null ? 0 : t.getArticles().size());
|
||||
nameAndCount.add(jsonObject);
|
||||
}
|
||||
return ResponseUtil.success(nameAndCount);
|
||||
|
||||
@@ -12,55 +12,60 @@ public enum ResponseEnum {
|
||||
ERROR(-2, "错误"),
|
||||
|
||||
//文章类
|
||||
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(3600, "新密码与原密码相同"),
|
||||
LOGIN_EXPIRED(3700, "登陆过期"),
|
||||
|
||||
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, "已经验证过了");
|
||||
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 int code;
|
||||
private String msg;
|
||||
|
||||
43
src/main/java/cn/celess/blog/entity/model/CategoryModel.java
Normal file
43
src/main/java/cn/celess/blog/entity/model/CategoryModel.java
Normal file
@@ -0,0 +1,43 @@
|
||||
package cn.celess.blog.entity.model;
|
||||
|
||||
import cn.celess.blog.entity.Category;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
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<Integer> articles;
|
||||
|
||||
|
||||
public CategoryModel(Category category) {
|
||||
this.id = category.getId();
|
||||
this.name = category.getName();
|
||||
if (category.getArticles() == null || category.getArticles().length() == 0) {
|
||||
articles = null;
|
||||
} else {
|
||||
articles = new ArrayList<>();
|
||||
for (String s : category.getArticles().split(",")) {
|
||||
if ("".equals(s)) {
|
||||
return;
|
||||
}
|
||||
articles.add(Integer.parseInt(s));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
41
src/main/java/cn/celess/blog/entity/model/TagModel.java
Normal file
41
src/main/java/cn/celess/blog/entity/model/TagModel.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package cn.celess.blog.entity.model;
|
||||
|
||||
import cn.celess.blog.entity.Tag;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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<Integer> articles;
|
||||
|
||||
public TagModel(Tag tag) {
|
||||
this.id = tag.getId();
|
||||
this.name = tag.getName();
|
||||
if (tag.getArticles() == null || tag.getArticles().length() == 0) {
|
||||
articles = null;
|
||||
} else {
|
||||
articles = new ArrayList<>();
|
||||
for (String s : tag.getArticles().split(",")) {
|
||||
if ("".equals(s)) {
|
||||
return;
|
||||
}
|
||||
articles.add(Integer.parseInt(s));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package cn.celess.blog.service;
|
||||
|
||||
import cn.celess.blog.entity.Category;
|
||||
import cn.celess.blog.entity.model.CategoryModel;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
@@ -17,7 +18,7 @@ public interface CategoryService {
|
||||
* @param name 分类名
|
||||
* @return 所增加的分类数据
|
||||
*/
|
||||
Category create(String name);
|
||||
CategoryModel create(String name);
|
||||
|
||||
/**
|
||||
* 增加一个分类
|
||||
@@ -25,7 +26,7 @@ public interface CategoryService {
|
||||
* @param category 分类对象
|
||||
* @return 所增加的分类数据
|
||||
*/
|
||||
Category create(Category category);
|
||||
CategoryModel create(Category category);
|
||||
|
||||
/**
|
||||
* 通过id删除分类
|
||||
@@ -42,13 +43,13 @@ public interface CategoryService {
|
||||
* @param name 分类名字
|
||||
* @return 更新后的分类的数据
|
||||
*/
|
||||
Category update(Long id, String name);
|
||||
CategoryModel update(Long id, String name);
|
||||
|
||||
/**
|
||||
* 获取全部的分类数据
|
||||
*
|
||||
* @return 全部的分类数据
|
||||
*/
|
||||
List<Category> retrievePage();
|
||||
List<CategoryModel> retrievePage();
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package cn.celess.blog.service;
|
||||
|
||||
import cn.celess.blog.entity.Tag;
|
||||
import cn.celess.blog.entity.model.TagModel;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -18,7 +19,7 @@ public interface TagService {
|
||||
* @param name 标签名
|
||||
* @return 新增后的数据
|
||||
*/
|
||||
Tag create(String name);
|
||||
TagModel create(String name);
|
||||
|
||||
/**
|
||||
* 新增数据
|
||||
@@ -27,7 +28,7 @@ public interface TagService {
|
||||
* @return 新增后的数据
|
||||
*/
|
||||
|
||||
Tag create(Tag tag);
|
||||
TagModel create(Tag tag);
|
||||
|
||||
/**
|
||||
* 删除数据
|
||||
@@ -44,7 +45,7 @@ public interface TagService {
|
||||
* @param name 改名的name值
|
||||
* @return 更新后的数据
|
||||
*/
|
||||
Tag update(Long id, String name);
|
||||
TagModel update(Long id, String name);
|
||||
|
||||
/**
|
||||
* 查询单个标签信息
|
||||
@@ -52,7 +53,7 @@ public interface TagService {
|
||||
* @param tagId id
|
||||
* @return 标签的数据
|
||||
*/
|
||||
Tag retrieveOneById(long tagId);
|
||||
TagModel retrieveOneById(long tagId);
|
||||
|
||||
/**
|
||||
* 通过name查询标签的信息
|
||||
@@ -60,7 +61,7 @@ public interface TagService {
|
||||
* @param name tag的名称
|
||||
* @return 标签数据
|
||||
*/
|
||||
Tag retrieveOneByName(String name);
|
||||
TagModel retrieveOneByName(String name);
|
||||
|
||||
|
||||
/**
|
||||
@@ -70,13 +71,13 @@ public interface TagService {
|
||||
* @param page 数据页
|
||||
* @return 分页数据
|
||||
*/
|
||||
PageInfo<Tag> retrievePage(int page, int count);
|
||||
PageInfo<TagModel> retrievePage(int page, int count);
|
||||
|
||||
/**
|
||||
* 获取全部标签数据
|
||||
*
|
||||
* @return 标签数据列表
|
||||
*/
|
||||
List<Tag> findAll();
|
||||
List<TagModel> findAll();
|
||||
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ public class ArticleServiceImpl implements ArticleService {
|
||||
article.setUrl(reqBody.getUrl());
|
||||
article.setType(reqBody.getType());
|
||||
|
||||
article.setAuthorId(redisUserUtil.get(request).getId());
|
||||
article.setAuthorId(redisUserUtil.get().getId());
|
||||
article.setPublishDate(new Date());
|
||||
|
||||
//防止出现 “null,xxx”这种情况
|
||||
@@ -198,7 +198,7 @@ public class ArticleServiceImpl implements ArticleService {
|
||||
Article nextArticle = articleMapper.findArticleById(articleForDel.getNextArticleId());
|
||||
|
||||
//对访问情况进行判断 非博主/非自己文章 拒绝访问
|
||||
User user = redisUserUtil.get(request);
|
||||
User user = redisUserUtil.get();
|
||||
if (!user.getRole().contains("admin") && !articleForDel.getAuthorId().equals(user.getId())) {
|
||||
throw new MyException(ResponseEnum.PERMISSION_ERROR);
|
||||
}
|
||||
@@ -277,10 +277,10 @@ public class ArticleServiceImpl implements ArticleService {
|
||||
if (reqBody.getCategory() == null || reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
// 暂时不更新tags
|
||||
// if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
|
||||
// throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
// }
|
||||
// 暂时不更新tags
|
||||
if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
|
||||
//写入数据库的数据
|
||||
Article article = new Article();
|
||||
@@ -317,26 +317,44 @@ public class ArticleServiceImpl implements ArticleService {
|
||||
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());
|
||||
String[] newTags = reqBody.getTags().split(",");
|
||||
String[] tagIds = oldArticle.getTagsId().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() + ",");
|
||||
int status = tagMapper.insert(tag);
|
||||
if (status == 0) {
|
||||
// 插入失败
|
||||
throw new MyException(ResponseEnum.FAILURE);
|
||||
}
|
||||
article.setTagsId(article.getTagsId() + tag.getId() + ",");
|
||||
continue;
|
||||
}
|
||||
article.setTagsId(article.getTagsId() + tag.getId() + ",");
|
||||
}
|
||||
for (String tagId : tagIds) {
|
||||
Tag tagById = tagMapper.findTagById(Long.parseLong(tagId));
|
||||
// 在新更新的tag中是否有原有的tag
|
||||
boolean isOldTag = false;
|
||||
for (String s : newTags) {
|
||||
if (s.equals(tagById.getName())) {
|
||||
isOldTag = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!isOldTag) {
|
||||
tagById.setArticles(tagById.getArticles().replace(oldArticle.getId() + ",", ""));
|
||||
}
|
||||
tagMapper.update(tagById);
|
||||
}
|
||||
//
|
||||
// // TODO:::: tag的更新
|
||||
// article.setTagsId(oldArticle.getTagsId());
|
||||
|
||||
|
||||
article.setUpdateDate(new Date());
|
||||
@@ -344,7 +362,7 @@ public class ArticleServiceImpl implements ArticleService {
|
||||
// 设置不定参数
|
||||
article.setReadingNumber(oldArticle.getReadingNumber());
|
||||
article.setPublishDate(oldArticle.getPublishDate());
|
||||
article.setAuthorId(redisUserUtil.get(request).getId());
|
||||
article.setAuthorId(redisUserUtil.get().getId());
|
||||
article.setPreArticleId(oldArticle.getPreArticleId());
|
||||
article.setNextArticleId(oldArticle.getNextArticleId());
|
||||
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
|
||||
@@ -362,7 +380,7 @@ public class ArticleServiceImpl implements ArticleService {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ 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.CategoryModel;
|
||||
import cn.celess.blog.exception.MyException;
|
||||
import cn.celess.blog.mapper.ArticleMapper;
|
||||
import cn.celess.blog.mapper.CategoryMapper;
|
||||
@@ -11,6 +12,7 @@ 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,7 +29,7 @@ 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);
|
||||
}
|
||||
@@ -35,16 +37,16 @@ public class CategoryServiceImpl implements CategoryService {
|
||||
category.setName(name);
|
||||
category.setArticles("");
|
||||
categoryMapper.insert(category);
|
||||
return category;
|
||||
return new CategoryModel(category);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Category create(Category category) {
|
||||
public CategoryModel create(Category category) {
|
||||
if (category == null) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
categoryMapper.insert(category);
|
||||
return category;
|
||||
return new CategoryModel(category);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -74,18 +76,20 @@ public class CategoryServiceImpl implements CategoryService {
|
||||
|
||||
|
||||
@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 new CategoryModel(category);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Category> retrievePage() {
|
||||
return categoryMapper.findAll();
|
||||
public List<CategoryModel> retrievePage() {
|
||||
List<CategoryModel> list = new ArrayList<>();
|
||||
categoryMapper.findAll().forEach(e -> list.add(new CategoryModel(e)));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ public class CommentServiceImpl implements CommentService {
|
||||
if (reqBody == null) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
long authorID = redisUserUtil.get(request).getId();
|
||||
long authorID = redisUserUtil.get().getId();
|
||||
Comment pComment = null;
|
||||
if (reqBody.getPid() != null && reqBody.getPid() != -1) {
|
||||
pComment = commentMapper.findCommentById(reqBody.getPid());
|
||||
@@ -147,7 +147,7 @@ public class CommentServiceImpl implements CommentService {
|
||||
@Override
|
||||
public PageInfo<CommentModel> retrievePageByAuthor(Boolean isComment, int page, int count) {
|
||||
PageHelper.startPage(page, count);
|
||||
List<Comment> commentList = commentMapper.findAllByAuthorIDAndType(redisUserUtil.get(request).getId(), isComment);
|
||||
List<Comment> commentList = commentMapper.findAllByAuthorIDAndType(redisUserUtil.get().getId(), isComment);
|
||||
PageInfo pageInfo = new PageInfo(commentList);
|
||||
pageInfo.setList(list2List(commentList));
|
||||
return pageInfo;
|
||||
|
||||
@@ -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 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()) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package cn.celess.blog.service.serviceimpl;
|
||||
import cn.celess.blog.enmu.ResponseEnum;
|
||||
import cn.celess.blog.entity.Article;
|
||||
import cn.celess.blog.entity.Tag;
|
||||
import cn.celess.blog.entity.model.TagModel;
|
||||
import cn.celess.blog.exception.MyException;
|
||||
import cn.celess.blog.mapper.ArticleMapper;
|
||||
import cn.celess.blog.mapper.TagMapper;
|
||||
@@ -13,6 +14,7 @@ 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;
|
||||
|
||||
/**
|
||||
@@ -29,7 +31,7 @@ public class TagServiceImpl implements TagService {
|
||||
ArticleMapper articleMapper;
|
||||
|
||||
@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,16 +39,16 @@ public class TagServiceImpl implements TagService {
|
||||
Tag tag = new Tag();
|
||||
tag.setName(name);
|
||||
tagMapper.insert(tag);
|
||||
return tag;
|
||||
return new TagModel(tag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tag create(Tag tag) {
|
||||
public TagModel create(Tag tag) {
|
||||
if (tag == null) {
|
||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||
}
|
||||
tagMapper.insert(tag);
|
||||
return tag;
|
||||
return new TagModel(tag);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -55,12 +57,12 @@ public class TagServiceImpl implements TagService {
|
||||
if (tag == null) {
|
||||
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
||||
}
|
||||
if (tag.getArticles()==null){
|
||||
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)) {
|
||||
if (articleArray[i] == null || "".equals(articleArray[i])) {
|
||||
continue;
|
||||
}
|
||||
long articleID = Long.parseLong(articleArray[i]);
|
||||
@@ -76,7 +78,7 @@ public class TagServiceImpl implements TagService {
|
||||
|
||||
|
||||
@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");
|
||||
}
|
||||
@@ -84,37 +86,43 @@ public class TagServiceImpl implements TagService {
|
||||
tagFromDB.setName(name);
|
||||
|
||||
tagMapper.update(tagFromDB);
|
||||
return tagFromDB;
|
||||
return new TagModel(tagFromDB);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tag retrieveOneById(long tagId) {
|
||||
public TagModel retrieveOneById(long tagId) {
|
||||
Tag tag = tagMapper.findTagById(tagId);
|
||||
if (tag == null) {
|
||||
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
||||
}
|
||||
return tag;
|
||||
return new TagModel(tag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tag retrieveOneByName(String name) {
|
||||
public TagModel retrieveOneByName(String name) {
|
||||
Tag tag = tagMapper.findTagByName(name);
|
||||
if (tag == null) {
|
||||
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
||||
}
|
||||
return tag;
|
||||
return new TagModel(tag);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<Tag> retrievePage(int page, int count) {
|
||||
public PageInfo<TagModel> retrievePage(int page, int count) {
|
||||
PageHelper.startPage(page, count);
|
||||
PageInfo pageInfo = new PageInfo(tagMapper.findAll());
|
||||
List<Tag> tagList = tagMapper.findAll();
|
||||
PageInfo pageInfo = new PageInfo(tagList);
|
||||
List<TagModel> list = new ArrayList<>();
|
||||
tagList.forEach(e -> list.add(new TagModel(e)));
|
||||
pageInfo.setList(list);
|
||||
return pageInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Tag> findAll() {
|
||||
return tagMapper.findAll();
|
||||
public List<TagModel> findAll() {
|
||||
List<TagModel> list = new ArrayList<>();
|
||||
tagMapper.findAll().forEach(e -> list.add(new TagModel(e)));
|
||||
return list;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,8 +119,7 @@ public class UserServiceImpl implements UserService {
|
||||
userMapper.updateLoginTime(loginReq.getEmail(), new Date());
|
||||
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());
|
||||
@@ -159,7 +158,7 @@ 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);
|
||||
|
||||
@@ -193,7 +192,7 @@ public class UserServiceImpl implements UserService {
|
||||
|
||||
@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());
|
||||
@@ -203,7 +202,7 @@ public class UserServiceImpl implements UserService {
|
||||
|
||||
@Override
|
||||
public UserModel getUserInfoBySession() {
|
||||
User user = redisUserUtil.get(request);
|
||||
User user = redisUserUtil.get();
|
||||
return trans(user);
|
||||
}
|
||||
|
||||
@@ -422,7 +421,7 @@ 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());
|
||||
|
||||
@@ -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,6 +19,7 @@ import java.util.Map;
|
||||
* @Description: JWT工具类
|
||||
*/
|
||||
@Component
|
||||
@Log4j2
|
||||
public class JwtUtil {
|
||||
private static final String CLAIM_KEY_USERNAME = "sub";
|
||||
|
||||
@@ -33,8 +35,8 @@ public class JwtUtil {
|
||||
/**
|
||||
* 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 +49,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -43,4 +45,11 @@ public class RedisUserUtil {
|
||||
redisUtil.getExpire(user.getEmail() + "-login"), 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +43,9 @@ public class SitemapGenerateUtil {
|
||||
@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()) {
|
||||
|
||||
@@ -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
|
||||
# 上传单个文件的大小
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
server.port=8081
|
||||
|
||||
sitemap.path=C:\\Users\\zh564\\Desktop\\sitemap.xml
|
||||
## 七牛的密钥配置
|
||||
qiniu.accessKey=
|
||||
qiniu.secretKey=
|
||||
qiniu.bucket=
|
||||
## sitemap 存放地址
|
||||
sitemap.path=
|
||||
## 生成JWT时候的密钥
|
||||
jwt.secret=
|
||||
|
||||
##spring.jpa.show-sql=false
|
||||
##spring.jpa.hibernate.ddl-auto=update
|
||||
@@ -17,9 +24,9 @@ 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.url=
|
||||
spring.datasource.username=
|
||||
spring.datasource.password=
|
||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||
|
||||
|
||||
@@ -42,7 +49,7 @@ server.tomcat.protocol-header = X-Forwarded-Proto
|
||||
|
||||
|
||||
############### email ##############
|
||||
spring.mail.host=smtp.163.com
|
||||
spring.mail.host=
|
||||
spring.mail.username=
|
||||
spring.mail.password=
|
||||
spring.mail.properties.mail.smtp.auth=true
|
||||
|
||||
@@ -8,10 +8,12 @@ import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.mock.web.MockHttpSession;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.ResultHandler;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
|
||||
@@ -20,6 +22,8 @@ import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
@@ -39,10 +43,12 @@ public class BaseTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
protected MockHttpSession session;
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||
session = new MockHttpSession();
|
||||
System.out.println("==========> 开始测试 <=========");
|
||||
}
|
||||
|
||||
@@ -60,7 +66,7 @@ public class BaseTest {
|
||||
req.setIsRememberMe(false);
|
||||
JSONObject loginReq = JSONObject.fromObject(req);
|
||||
String str = mockMvc.perform(MockMvcRequestBuilders.post("/login").content(loginReq.toString()).contentType("application/json"))
|
||||
// .andDo(MockMvcResultHandlers.print())
|
||||
// .andDo(MockMvcResultHandlers.print())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
String token = JSONObject.fromObject(str).getJSONObject(Result).getString("token");
|
||||
assertNotNull(token);
|
||||
@@ -79,7 +85,7 @@ public class BaseTest {
|
||||
req.setIsRememberMe(false);
|
||||
JSONObject loginReq = JSONObject.fromObject(req);
|
||||
String str = mockMvc.perform(MockMvcRequestBuilders.post("/login").content(loginReq.toString()).contentType("application/json"))
|
||||
// .andDo(MockMvcResultHandlers.print())
|
||||
// .andDo(MockMvcResultHandlers.print())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
String token = JSONObject.fromObject(str).getJSONObject(Result).getString("token");
|
||||
assertNotNull(token);
|
||||
@@ -94,4 +100,8 @@ public class BaseTest {
|
||||
public void test() {
|
||||
|
||||
}
|
||||
|
||||
protected String randomStr(int len) {
|
||||
return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.UUID;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
@@ -139,32 +138,17 @@ public class ArticleControllerTest extends BaseTest {
|
||||
articleReq.setCategory("test");
|
||||
articleReq.setMdContent("test-" + article.getMdContent());
|
||||
articleReq.setOpen(!article.getOpen());
|
||||
articleReq.setTags("tag");
|
||||
String tag1 = randomStr(4);
|
||||
String tag2 = randomStr(4);
|
||||
String tag = "test," + tag1 + "," + tag2;
|
||||
articleReq.setTags(tag);
|
||||
articleReq.setTitle("test-" + article.getTitle());
|
||||
try {
|
||||
mockMvc.perform(put("/admin/article/update")
|
||||
.content(JSONObject.fromObject(articleReq).toString())
|
||||
.contentType("application/json"))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(result -> {
|
||||
assertEquals(HAVE_NOT_LOG_IN.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code));
|
||||
});
|
||||
// User 权限
|
||||
String token = userLogin();
|
||||
mockMvc.perform(put("/admin/article/update")
|
||||
.content(JSONObject.fromObject(articleReq).toString())
|
||||
.contentType("application/json")
|
||||
.header("Authorization", token))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(result -> {
|
||||
assertEquals(PERMISSION_ERROR.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code));
|
||||
});
|
||||
// Admin 权限
|
||||
token = adminLogin();
|
||||
mockMvc.perform(put("/admin/article/update")
|
||||
.content(JSONObject.fromObject(articleReq).toString())
|
||||
.contentType("application/json")
|
||||
.header("Authorization", token))
|
||||
.header("Authorization", adminLogin()))
|
||||
.andExpect(status().isOk())
|
||||
.andDo(result -> {
|
||||
JSONObject jsonObject = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||
@@ -175,8 +159,11 @@ public class ArticleControllerTest extends BaseTest {
|
||||
assertEquals(articleReq.getMdContent(), a.getMdContent());
|
||||
assertEquals(articleReq.getTitle(), a.getTitle());
|
||||
assertEquals(articleReq.getType(), a.getOriginal());
|
||||
// Tag 暂时不支持更新
|
||||
// assertEquals(articleReq.getTags(), Arrays.toString(a.getTags()).replaceAll(" ", "".replace("[", "".replace("]", ""))));
|
||||
// Tag
|
||||
List<String> asList = Arrays.asList(a.getTags());
|
||||
assertTrue(asList.contains("test"));
|
||||
assertTrue(asList.contains(tag1));
|
||||
assertTrue(asList.contains(tag2));
|
||||
assertEquals(articleReq.getOpen(), a.getOpen());
|
||||
assertEquals(articleReq.getId(), a.getId());
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ package cn.celess.blog.controller;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import cn.celess.blog.entity.Category;
|
||||
import cn.celess.blog.entity.model.CategoryModel;
|
||||
import cn.celess.blog.mapper.CategoryMapper;
|
||||
import net.sf.json.JSONArray;
|
||||
import net.sf.json.JSONObject;
|
||||
@@ -45,10 +46,10 @@ public class CategoryControllerTest extends BaseTest {
|
||||
.andDo(result -> {
|
||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||
Category category = (Category) JSONObject.toBean(object.getJSONObject(Result), Category.class);
|
||||
CategoryModel category = (CategoryModel) JSONObject.toBean(object.getJSONObject(Result), CategoryModel.class);
|
||||
assertEquals(categoryName, category.getName());
|
||||
assertNotNull(category.getId());
|
||||
assertNotNull(category.getArticles());
|
||||
assertNotEquals(0, category.getArticles());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -105,9 +106,9 @@ public class CategoryControllerTest extends BaseTest {
|
||||
.andDo(result -> {
|
||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||
Category c = (Category) JSONObject.toBean(object.getJSONObject(Result), Category.class);
|
||||
CategoryModel c = (CategoryModel) JSONObject.toBean(object.getJSONObject(Result), CategoryModel.class);
|
||||
assertEquals(name, c.getName());
|
||||
assertNotNull(c.getArticles());
|
||||
assertNotEquals(0, c.getArticles());
|
||||
assertNotNull(c.getId());
|
||||
});
|
||||
}
|
||||
@@ -121,10 +122,10 @@ public class CategoryControllerTest extends BaseTest {
|
||||
JSONArray jsonArray = object.getJSONArray(Result);
|
||||
assertNotNull(jsonArray);
|
||||
jsonArray.forEach(o -> {
|
||||
Category c = (Category) JSONObject.toBean(JSONObject.fromObject(o), Category.class);
|
||||
CategoryModel c = (CategoryModel) JSONObject.toBean(JSONObject.fromObject(o), CategoryModel.class);
|
||||
assertNotNull(c.getName());
|
||||
assertNotNull(c.getId());
|
||||
assertNotNull(c.getArticles());
|
||||
assertNotEquals(0, c.getArticles());
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -161,7 +161,8 @@ public class LinksControllerTest extends BaseTest {
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
// 手动测试
|
||||
// @Test
|
||||
public void apply() throws Exception {
|
||||
long l = System.currentTimeMillis();
|
||||
String url = "https://www.example.com";
|
||||
|
||||
@@ -2,6 +2,7 @@ package cn.celess.blog.controller;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import cn.celess.blog.entity.Tag;
|
||||
import cn.celess.blog.entity.model.TagModel;
|
||||
import cn.celess.blog.mapper.TagMapper;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import net.sf.json.JSONArray;
|
||||
@@ -29,7 +30,7 @@ public class TagControllerTest extends BaseTest {
|
||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||
JSONObject resJson = object.getJSONObject(Result);
|
||||
Tag tag = (Tag) JSONObject.toBean(resJson, Tag.class);
|
||||
TagModel tag = (TagModel) JSONObject.toBean(resJson, TagModel.class);
|
||||
assertNotNull(tag.getId());
|
||||
assertEquals(name, tag.getName());
|
||||
});
|
||||
@@ -63,9 +64,11 @@ public class TagControllerTest extends BaseTest {
|
||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||
assertNotNull(object.getJSONObject(Result));
|
||||
Tag t = (Tag) JSONObject.toBean(object.getJSONObject(Result), Tag.class);
|
||||
TagModel t = (TagModel) JSONObject.toBean(object.getJSONObject(Result), TagModel.class);
|
||||
assertEquals(name, t.getName());
|
||||
assertEquals(tag.getArticles(), t.getArticles());
|
||||
StringBuilder s = new StringBuilder();
|
||||
t.getArticles().forEach(e -> s.append(e).append(","));
|
||||
assertEquals(tag.getArticles(), s.toString());
|
||||
assertEquals(tag.getId(), t.getId());
|
||||
});
|
||||
|
||||
@@ -79,7 +82,7 @@ public class TagControllerTest extends BaseTest {
|
||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||
assertNotNull(object.getJSONObject(Result));
|
||||
Tag t = (Tag) JSONObject.toBean(object.getJSONObject(Result), Tag.class);
|
||||
TagModel t = (TagModel) JSONObject.toBean(object.getJSONObject(Result), TagModel.class);
|
||||
assertEquals(tag.getId(), t.getId());
|
||||
assertNotNull(t.getName());
|
||||
});
|
||||
@@ -93,7 +96,7 @@ public class TagControllerTest extends BaseTest {
|
||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||
assertNotNull(object.getJSONObject(Result));
|
||||
Tag t = (Tag) JSONObject.toBean(object.getJSONObject(Result), Tag.class);
|
||||
TagModel t = (TagModel) JSONObject.toBean(object.getJSONObject(Result), TagModel.class);
|
||||
assertEquals(tag.getName(), t.getName());
|
||||
assertNotNull(t.getId());
|
||||
});
|
||||
@@ -119,7 +122,7 @@ public class TagControllerTest extends BaseTest {
|
||||
assertEquals(5, pageInfo.getPageSize());
|
||||
// 内容完整
|
||||
for (Object tag : pageInfo.getList()) {
|
||||
Tag t = (Tag) JSONObject.toBean(JSONObject.fromObject(tag), Tag.class);
|
||||
TagModel t = (TagModel) JSONObject.toBean(JSONObject.fromObject(tag), TagModel.class);
|
||||
assertNotNull(t.getId());
|
||||
assertNotNull(t.getName());
|
||||
}
|
||||
|
||||
@@ -14,10 +14,9 @@ import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
@@ -93,8 +92,12 @@ public class UserControllerTest extends BaseTest {
|
||||
|
||||
@Test
|
||||
public void upload() throws Exception {
|
||||
File logoFile = new File("C:\\Users\\zh564\\Pictures\\logo.png");
|
||||
MockMultipartFile file = new MockMultipartFile("file", "logo.png", MediaType.IMAGE_PNG_VALUE, new FileInputStream(logoFile));
|
||||
URL url = new URL("https://56462271.oss-cn-beijing.aliyuncs.com/web/logo.png");
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
InputStream inputStream = connection.getInputStream();
|
||||
assertNotNull(inputStream);
|
||||
MockMultipartFile file = new MockMultipartFile("file", "logo.png", MediaType.IMAGE_PNG_VALUE, inputStream);
|
||||
mockMvc.perform(multipart("/user/imgUpload").file(file)).andDo(result -> assertEquals(HAVE_NOT_LOG_IN.getCode(), JSONObject.fromObject(result.getResponse().getContentAsString()).getInt(Code)));
|
||||
mockMvc.perform(multipart("/user/imgUpload").file(file).header("Authorization", userLogin())).andDo(result -> {
|
||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||
|
||||
@@ -63,7 +63,8 @@ public class VisitorControllerTest extends BaseTest {
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
// 手动测试
|
||||
// @Test
|
||||
public void ipLocation() throws Exception {
|
||||
String ip = "127.0.0.1";
|
||||
mockMvc.perform(get("/ip/" + ip)).andDo(MockMvcResultHandlers.print()).andDo(result -> {
|
||||
|
||||
26
src/test/java/cn/celess/blog/util/DateFormatUtilTest.java
Normal file
26
src/test/java/cn/celess/blog/util/DateFormatUtilTest.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package cn.celess.blog.util;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class DateFormatUtilTest extends BaseTest {
|
||||
|
||||
@Test
|
||||
public void get() {
|
||||
assertNotNull(DateFormatUtil.get(new Date()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getForXmlDate() {
|
||||
assertNotNull(DateFormatUtil.getForXmlDate(new Date()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getNow() {
|
||||
assertNotNull(DateFormatUtil.getNow());
|
||||
}
|
||||
}
|
||||
@@ -2,51 +2,79 @@ package cn.celess.blog.util;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import cn.celess.blog.entity.User;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.junit.runners.MethodSorters;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||
public class JwtUtilTest extends BaseTest {
|
||||
|
||||
@Autowired
|
||||
JwtUtil jwtUtil;
|
||||
|
||||
@Value("${jwt.secret}")
|
||||
private String secret;
|
||||
|
||||
@Test
|
||||
public void generateToken() {
|
||||
public void testGenerateToken() {
|
||||
User user = new User();
|
||||
user.setEmail("a@celess.cn");
|
||||
String s = jwtUtil.generateToken(user, true);
|
||||
System.out.println(s);
|
||||
String s = jwtUtil.generateToken(user, false);
|
||||
assertNotNull(s);
|
||||
String str = null;
|
||||
try {
|
||||
str = jwtUtil.generateToken(null, false);
|
||||
} catch (Exception e) {
|
||||
// ignore
|
||||
}
|
||||
assertNull(str);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validateToken() {
|
||||
public void testIsTokenExpired() throws InterruptedException {
|
||||
String s = Jwts.builder()
|
||||
.setClaims(null)
|
||||
.setExpiration(new Date(Instant.now().toEpochMilli() + 1000))
|
||||
.signWith(SignatureAlgorithm.HS512, secret)
|
||||
.compact();
|
||||
Thread.sleep(1010);
|
||||
assertTrue(jwtUtil.isTokenExpired(s));
|
||||
assertFalse(jwtUtil.isTokenExpired(jwtUtil.generateToken(new User(), false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUsernameFromToken() {
|
||||
User user = new User();
|
||||
user.setEmail("a@celess.cn");
|
||||
assertTrue(jwtUtil.validateToken(createToken(), user));
|
||||
String s = jwtUtil.generateToken(user, false);
|
||||
assertEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s));
|
||||
user.setEmail("example@celess.cn");
|
||||
assertNotEquals(user.getEmail(), jwtUtil.getUsernameFromToken(s));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void isTokenExpired() {
|
||||
assertFalse(jwtUtil.isTokenExpired(createToken()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getUsernameFromToken() {
|
||||
assertEquals("a@celess.cn", jwtUtil.getUsernameFromToken(createToken()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getExpirationDateFromToken() {
|
||||
assertNotNull(jwtUtil.getExpirationDateFromToken(createToken()));
|
||||
}
|
||||
|
||||
private String createToken() {
|
||||
public void testGetExpirationDateFromToken() {
|
||||
User user = new User();
|
||||
user.setEmail("a@celess.cn");
|
||||
return jwtUtil.generateToken(user, true);
|
||||
String s = jwtUtil.generateToken(user, false);
|
||||
assertNotNull(jwtUtil.getExpirationDateFromToken(s));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateTokenDate() {
|
||||
User user = new User();
|
||||
user.setEmail("a@celess.cn");
|
||||
String s = jwtUtil.generateToken(user, false);
|
||||
Date before = jwtUtil.getExpirationDateFromToken(s);
|
||||
String s1 = jwtUtil.updateTokenDate(s);
|
||||
assertTrue(jwtUtil.getExpirationDateFromToken(s1).getTime() - jwtUtil.getExpirationDateFromToken(s).getTime() > 0);
|
||||
}
|
||||
}
|
||||
14
src/test/java/cn/celess/blog/util/MD5UtilTest.java
Normal file
14
src/test/java/cn/celess/blog/util/MD5UtilTest.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package cn.celess.blog.util;
|
||||
|
||||
import cn.celess.blog.BaseTest;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class MD5UtilTest extends BaseTest {
|
||||
|
||||
@Test
|
||||
public void getMD5() {
|
||||
assertEquals("25f9e794323b453885f5181f1b624d0b", MD5Util.getMD5("123456789"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user