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"
|
||||||
232
.mvn/wrapper/MavenWrapperDownloader.java
vendored
232
.mvn/wrapper/MavenWrapperDownloader.java
vendored
@@ -1,114 +1,118 @@
|
|||||||
/*
|
/*
|
||||||
Licensed to the Apache Software Foundation (ASF) under one
|
* Copyright 2012-2019 the original author or authors.
|
||||||
or more contributor license agreements. See the NOTICE file
|
*
|
||||||
distributed with this work for additional information
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
regarding copyright ownership. The ASF licenses this file
|
* you may not use this file except in compliance with the License.
|
||||||
to you under the Apache License, Version 2.0 (the
|
* You may obtain a copy of the License at
|
||||||
"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
|
||||||
|
*
|
||||||
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,
|
||||||
Unless required by applicable law or agreed to in writing,
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
software distributed under the License is distributed on an
|
* See the License for the specific language governing permissions and
|
||||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
* limitations under the License.
|
||||||
KIND, either express or implied. See the License for the
|
*/
|
||||||
specific language governing permissions and limitations
|
|
||||||
under the License.
|
import java.net.*;
|
||||||
*/
|
import java.io.*;
|
||||||
|
import java.nio.channels.*;
|
||||||
import java.io.File;
|
import java.util.Properties;
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.io.FileOutputStream;
|
public class MavenWrapperDownloader {
|
||||||
import java.io.IOException;
|
|
||||||
import java.net.URL;
|
private static final String WRAPPER_VERSION = "0.5.5";
|
||||||
import java.nio.channels.Channels;
|
/**
|
||||||
import java.nio.channels.ReadableByteChannel;
|
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
||||||
import java.util.Properties;
|
*/
|
||||||
|
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
|
||||||
public class MavenWrapperDownloader {
|
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
|
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
||||||
*/
|
* use instead of the default one.
|
||||||
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 MAVEN_WRAPPER_PROPERTIES_PATH =
|
||||||
|
".mvn/wrapper/maven-wrapper.properties";
|
||||||
/**
|
|
||||||
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
|
/**
|
||||||
* use instead of the default one.
|
* Path where the maven-wrapper.jar will be saved to.
|
||||||
*/
|
*/
|
||||||
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
|
private static final String MAVEN_WRAPPER_JAR_PATH =
|
||||||
".mvn/wrapper/maven-wrapper.properties";
|
".mvn/wrapper/maven-wrapper.jar";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Path where the maven-wrapper.jar will be saved to.
|
* Name of the property which should be used to override the default download url for the wrapper.
|
||||||
*/
|
*/
|
||||||
private static final String MAVEN_WRAPPER_JAR_PATH =
|
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
||||||
".mvn/wrapper/maven-wrapper.jar";
|
|
||||||
|
public static void main(String args[]) {
|
||||||
/**
|
System.out.println("- Downloader started");
|
||||||
* Name of the property which should be used to override the default download url for the wrapper.
|
File baseDirectory = new File(args[0]);
|
||||||
*/
|
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
||||||
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
|
|
||||||
|
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
||||||
public static void main(String args[]) {
|
// wrapperUrl parameter.
|
||||||
System.out.println("- Downloader started");
|
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
||||||
File baseDirectory = new File(args[0]);
|
String url = DEFAULT_DOWNLOAD_URL;
|
||||||
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
|
if (mavenWrapperPropertyFile.exists()) {
|
||||||
|
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
||||||
// If the maven-wrapper.properties exists, read it and check if it contains a custom
|
try {
|
||||||
// wrapperUrl parameter.
|
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
||||||
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
|
Properties mavenWrapperProperties = new Properties();
|
||||||
String url = DEFAULT_DOWNLOAD_URL;
|
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
||||||
if (mavenWrapperPropertyFile.exists()) {
|
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
||||||
FileInputStream mavenWrapperPropertyFileInputStream = null;
|
} catch (IOException e) {
|
||||||
try {
|
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
||||||
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
|
} finally {
|
||||||
Properties mavenWrapperProperties = new Properties();
|
try {
|
||||||
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
|
if (mavenWrapperPropertyFileInputStream != null) {
|
||||||
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
|
mavenWrapperPropertyFileInputStream.close();
|
||||||
} catch (IOException e) {
|
}
|
||||||
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
|
} catch (IOException e) {
|
||||||
} finally {
|
// Ignore ...
|
||||||
try {
|
}
|
||||||
if (mavenWrapperPropertyFileInputStream != null) {
|
}
|
||||||
mavenWrapperPropertyFileInputStream.close();
|
}
|
||||||
}
|
System.out.println("- Downloading from: " + url);
|
||||||
} catch (IOException e) {
|
|
||||||
// Ignore ...
|
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
||||||
}
|
if (!outputFile.getParentFile().exists()) {
|
||||||
}
|
if (!outputFile.getParentFile().mkdirs()) {
|
||||||
}
|
System.out.println(
|
||||||
System.out.println("- Downloading from: : " + url);
|
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
||||||
|
}
|
||||||
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
|
}
|
||||||
if (!outputFile.getParentFile().exists()) {
|
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
||||||
if (!outputFile.getParentFile().mkdirs()) {
|
try {
|
||||||
System.out.println(
|
downloadFileFromURL(url, outputFile);
|
||||||
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
|
System.out.println("Done");
|
||||||
}
|
System.exit(0);
|
||||||
}
|
} catch (Throwable e) {
|
||||||
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
|
System.out.println("- Error downloading");
|
||||||
try {
|
e.printStackTrace();
|
||||||
downloadFileFromURL(url, outputFile);
|
System.exit(1);
|
||||||
System.out.println("Done");
|
}
|
||||||
System.exit(0);
|
}
|
||||||
} catch (Throwable e) {
|
|
||||||
System.out.println("- Error downloading");
|
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
||||||
e.printStackTrace();
|
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
|
||||||
System.exit(1);
|
String username = System.getenv("MVNW_USERNAME");
|
||||||
}
|
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
|
||||||
}
|
Authenticator.setDefault(new Authenticator() {
|
||||||
|
@Override
|
||||||
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
|
protected PasswordAuthentication getPasswordAuthentication() {
|
||||||
URL website = new URL(urlString);
|
return new PasswordAuthentication(username, password);
|
||||||
ReadableByteChannel rbc;
|
}
|
||||||
rbc = Channels.newChannel(website.openStream());
|
});
|
||||||
FileOutputStream fos = new FileOutputStream(destination);
|
}
|
||||||
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
URL website = new URL(urlString);
|
||||||
fos.close();
|
ReadableByteChannel rbc;
|
||||||
rbc.close();
|
rbc = Channels.newChannel(website.openStream());
|
||||||
}
|
FileOutputStream fos = new FileOutputStream(destination);
|
||||||
|
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
|
||||||
}
|
fos.close();
|
||||||
|
rbc.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
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的后端博客管理系统
|
## 基于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 "更新结束"
|
||||||
608
mvnw
vendored
608
mvnw
vendored
@@ -1,286 +1,322 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
# Licensed to the Apache Software Foundation (ASF) under one
|
# Licensed to the Apache Software Foundation (ASF) under one
|
||||||
# or more contributor license agreements. See the NOTICE file
|
# or more contributor license agreements. See the NOTICE file
|
||||||
# distributed with this work for additional information
|
# distributed with this work for additional information
|
||||||
# regarding copyright ownership. The ASF licenses this file
|
# regarding copyright ownership. The ASF licenses this file
|
||||||
# to you under the Apache License, Version 2.0 (the
|
# to you under the Apache License, Version 2.0 (the
|
||||||
# "License"); you may not use this file except in compliance
|
# "License"); you may not use this file except in compliance
|
||||||
# with the License. You may obtain a copy of the License at
|
# with the License. You may obtain a copy of the License at
|
||||||
#
|
#
|
||||||
# https://www.apache.org/licenses/LICENSE-2.0
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
#
|
#
|
||||||
# Unless required by applicable law or agreed to in writing,
|
# Unless required by applicable law or agreed to in writing,
|
||||||
# software distributed under the License is distributed on an
|
# software distributed under the License is distributed on an
|
||||||
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
# KIND, either express or implied. See the License for the
|
# KIND, either express or implied. See the License for the
|
||||||
# specific language governing permissions and limitations
|
# specific language governing permissions and limitations
|
||||||
# under the License.
|
# under the License.
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
|
|
||||||
# ----------------------------------------------------------------------------
|
# ----------------------------------------------------------------------------
|
||||||
# Maven2 Start Up Batch script
|
# Maven2 Start Up Batch script
|
||||||
#
|
#
|
||||||
# Required ENV vars:
|
# Required ENV vars:
|
||||||
# ------------------
|
# ------------------
|
||||||
# JAVA_HOME - location of a JDK home dir
|
# JAVA_HOME - location of a JDK home dir
|
||||||
#
|
#
|
||||||
# Optional ENV vars
|
# Optional ENV vars
|
||||||
# -----------------
|
# -----------------
|
||||||
# M2_HOME - location of maven2's installed home dir
|
# M2_HOME - location of maven2's installed home dir
|
||||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||||
# e.g. to debug Maven itself, use
|
# e.g. to debug Maven itself, use
|
||||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
# 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
|
. /etc/mavenrc
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ -f "$HOME/.mavenrc" ] ; then
|
if [ -f "$HOME/.mavenrc" ]; then
|
||||||
. "$HOME/.mavenrc"
|
. "$HOME/.mavenrc"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# OS specific support. $var _must_ be set to either true or false.
|
# OS specific support. $var _must_ be set to either true or false.
|
||||||
cygwin=false;
|
cygwin=false
|
||||||
darwin=false;
|
darwin=false
|
||||||
mingw=false
|
mingw=false
|
||||||
case "`uname`" in
|
case "$(uname)" in
|
||||||
CYGWIN*) cygwin=true ;;
|
CYGWIN*) cygwin=true ;;
|
||||||
MINGW*) mingw=true;;
|
MINGW*) mingw=true ;;
|
||||||
Darwin*) darwin=true
|
Darwin*)
|
||||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
darwin=true
|
||||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||||
if [ -z "$JAVA_HOME" ]; then
|
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||||
if [ -x "/usr/libexec/java_home" ]; then
|
if [ -z "$JAVA_HOME" ]; then
|
||||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
if [ -x "/usr/libexec/java_home" ]; then
|
||||||
else
|
export JAVA_HOME="$(/usr/libexec/java_home)"
|
||||||
export JAVA_HOME="/Library/Java/Home"
|
else
|
||||||
fi
|
export JAVA_HOME="/Library/Java/Home"
|
||||||
fi
|
fi
|
||||||
;;
|
fi
|
||||||
esac
|
;;
|
||||||
|
esac
|
||||||
if [ -z "$JAVA_HOME" ] ; then
|
|
||||||
if [ -r /etc/gentoo-release ] ; then
|
if [ -z "$JAVA_HOME" ]; then
|
||||||
JAVA_HOME=`java-config --jre-home`
|
if [ -r /etc/gentoo-release ]; then
|
||||||
fi
|
JAVA_HOME=$(java-config --jre-home)
|
||||||
fi
|
fi
|
||||||
|
fi
|
||||||
if [ -z "$M2_HOME" ] ; then
|
|
||||||
## resolve links - $0 may be a link to maven's home
|
if [ -z "$M2_HOME" ]; then
|
||||||
PRG="$0"
|
## resolve links - $0 may be a link to maven's home
|
||||||
|
PRG="$0"
|
||||||
# need this for relative symlinks
|
|
||||||
while [ -h "$PRG" ] ; do
|
# need this for relative symlinks
|
||||||
ls=`ls -ld "$PRG"`
|
while [ -h "$PRG" ]; do
|
||||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
ls=$(ls -ld "$PRG")
|
||||||
if expr "$link" : '/.*' > /dev/null; then
|
link=$(expr "$ls" : '.*-> \(.*\)$')
|
||||||
PRG="$link"
|
if expr "$link" : '/.*' >/dev/null; then
|
||||||
else
|
PRG="$link"
|
||||||
PRG="`dirname "$PRG"`/$link"
|
else
|
||||||
fi
|
PRG="$(dirname "$PRG")/$link"
|
||||||
done
|
fi
|
||||||
|
done
|
||||||
saveddir=`pwd`
|
|
||||||
|
saveddir=$(pwd)
|
||||||
M2_HOME=`dirname "$PRG"`/..
|
|
||||||
|
M2_HOME=$(dirname "$PRG")/..
|
||||||
# make it fully qualified
|
|
||||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
# make it fully qualified
|
||||||
|
M2_HOME=$(cd "$M2_HOME" && pwd)
|
||||||
cd "$saveddir"
|
|
||||||
# echo Using m2 at $M2_HOME
|
cd "$saveddir"
|
||||||
fi
|
# echo Using m2 at $M2_HOME
|
||||||
|
fi
|
||||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
|
||||||
if $cygwin ; then
|
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||||
[ -n "$M2_HOME" ] &&
|
if $cygwin; then
|
||||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
[ -n "$M2_HOME" ] &&
|
||||||
[ -n "$JAVA_HOME" ] &&
|
M2_HOME=$(cygpath --unix "$M2_HOME")
|
||||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
[ -n "$JAVA_HOME" ] &&
|
||||||
[ -n "$CLASSPATH" ] &&
|
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
|
||||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
[ -n "$CLASSPATH" ] &&
|
||||||
fi
|
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
|
||||||
|
fi
|
||||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
|
||||||
if $mingw ; then
|
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||||
[ -n "$M2_HOME" ] &&
|
if $mingw; then
|
||||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
[ -n "$M2_HOME" ] &&
|
||||||
[ -n "$JAVA_HOME" ] &&
|
M2_HOME="$( (
|
||||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
cd "$M2_HOME"
|
||||||
# TODO classpath?
|
pwd
|
||||||
fi
|
))"
|
||||||
|
[ -n "$JAVA_HOME" ] &&
|
||||||
if [ -z "$JAVA_HOME" ]; then
|
JAVA_HOME="$( (
|
||||||
javaExecutable="`which javac`"
|
cd "$JAVA_HOME"
|
||||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
pwd
|
||||||
# readlink(1) is not available as standard on Solaris 10.
|
))"
|
||||||
readLink=`which readlink`
|
fi
|
||||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
|
||||||
if $darwin ; then
|
if [ -z "$JAVA_HOME" ]; then
|
||||||
javaHome="`dirname \"$javaExecutable\"`"
|
javaExecutable="$(which javac)"
|
||||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then
|
||||||
else
|
# readlink(1) is not available as standard on Solaris 10.
|
||||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
readLink=$(which readlink)
|
||||||
fi
|
if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
|
||||||
javaHome="`dirname \"$javaExecutable\"`"
|
if $darwin; then
|
||||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
javaHome="$(dirname \"$javaExecutable\")"
|
||||||
JAVA_HOME="$javaHome"
|
javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
|
||||||
export JAVA_HOME
|
else
|
||||||
fi
|
javaExecutable="$(readlink -f \"$javaExecutable\")"
|
||||||
fi
|
fi
|
||||||
fi
|
javaHome="$(dirname \"$javaExecutable\")"
|
||||||
|
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
|
||||||
if [ -z "$JAVACMD" ] ; then
|
JAVA_HOME="$javaHome"
|
||||||
if [ -n "$JAVA_HOME" ] ; then
|
export JAVA_HOME
|
||||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
fi
|
||||||
# IBM's JDK on AIX uses strange locations for the executables
|
fi
|
||||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
fi
|
||||||
else
|
|
||||||
JAVACMD="$JAVA_HOME/bin/java"
|
if [ -z "$JAVACMD" ]; then
|
||||||
fi
|
if [ -n "$JAVA_HOME" ]; then
|
||||||
else
|
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||||
JAVACMD="`which java`"
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
fi
|
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||||
fi
|
else
|
||||||
|
JAVACMD="$JAVA_HOME/bin/java"
|
||||||
if [ ! -x "$JAVACMD" ] ; then
|
fi
|
||||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
else
|
||||||
echo " We cannot execute $JAVACMD" >&2
|
JAVACMD="$(which java)"
|
||||||
exit 1
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ -z "$JAVA_HOME" ] ; then
|
if [ ! -x "$JAVACMD" ]; then
|
||||||
echo "Warning: JAVA_HOME environment variable is not set."
|
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||||
fi
|
echo " We cannot execute $JAVACMD" >&2
|
||||||
|
exit 1
|
||||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
fi
|
||||||
|
|
||||||
# traverses directory structure from process work directory to filesystem root
|
if [ -z "$JAVA_HOME" ]; then
|
||||||
# first directory with .mvn subdirectory is considered project base directory
|
echo "Warning: JAVA_HOME environment variable is not set."
|
||||||
find_maven_basedir() {
|
fi
|
||||||
|
|
||||||
if [ -z "$1" ]
|
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||||
then
|
|
||||||
echo "Path not specified to find_maven_basedir"
|
# traverses directory structure from process work directory to filesystem root
|
||||||
return 1
|
# first directory with .mvn subdirectory is considered project base directory
|
||||||
fi
|
find_maven_basedir() {
|
||||||
|
|
||||||
basedir="$1"
|
if [ -z "$1" ]; then
|
||||||
wdir="$1"
|
echo "Path not specified to find_maven_basedir"
|
||||||
while [ "$wdir" != '/' ] ; do
|
return 1
|
||||||
if [ -d "$wdir"/.mvn ] ; then
|
fi
|
||||||
basedir=$wdir
|
|
||||||
break
|
basedir="$1"
|
||||||
fi
|
wdir="$1"
|
||||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
while [ "$wdir" != '/' ]; do
|
||||||
if [ -d "${wdir}" ]; then
|
if [ -d "$wdir"/.mvn ]; then
|
||||||
wdir=`cd "$wdir/.."; pwd`
|
basedir=$wdir
|
||||||
fi
|
break
|
||||||
# end of workaround
|
fi
|
||||||
done
|
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||||
echo "${basedir}"
|
if [ -d "${wdir}" ]; then
|
||||||
}
|
wdir=$(
|
||||||
|
cd "$wdir/.."
|
||||||
# concatenates all lines of a file
|
pwd
|
||||||
concat_lines() {
|
)
|
||||||
if [ -f "$1" ]; then
|
fi
|
||||||
echo "$(tr -s '\n' ' ' < "$1")"
|
# end of workaround
|
||||||
fi
|
done
|
||||||
}
|
echo "${basedir}"
|
||||||
|
}
|
||||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
|
||||||
if [ -z "$BASE_DIR" ]; then
|
# concatenates all lines of a file
|
||||||
exit 1;
|
concat_lines() {
|
||||||
fi
|
if [ -f "$1" ]; then
|
||||||
|
echo "$(tr -s '\n' ' ' <"$1")"
|
||||||
##########################################################################################
|
fi
|
||||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
}
|
||||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
|
||||||
##########################################################################################
|
BASE_DIR=$(find_maven_basedir "$(pwd)")
|
||||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
if [ -z "$BASE_DIR" ]; then
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
exit 1
|
||||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
fi
|
||||||
fi
|
|
||||||
else
|
##########################################################################################
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||||
fi
|
##########################################################################################
|
||||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
|
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||||
while IFS="=" read key value; do
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||||
esac
|
fi
|
||||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
else
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
echo "Downloading from: $jarUrl"
|
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||||
fi
|
fi
|
||||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
if [ -n "$MVNW_REPOURL" ]; then
|
||||||
|
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
|
||||||
if command -v wget > /dev/null; then
|
else
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
|
||||||
echo "Found wget ... using wget"
|
fi
|
||||||
fi
|
while IFS="=" read key value; do
|
||||||
wget "$jarUrl" -O "$wrapperJarPath"
|
case "$key" in wrapperUrl)
|
||||||
elif command -v curl > /dev/null; then
|
jarUrl="$value"
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
break
|
||||||
echo "Found curl ... using curl"
|
;;
|
||||||
fi
|
esac
|
||||||
curl -o "$wrapperJarPath" "$jarUrl"
|
done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||||
else
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
echo "Downloading from: $jarUrl"
|
||||||
echo "Falling back to using Java to download"
|
fi
|
||||||
fi
|
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
if $cygwin; then
|
||||||
if [ -e "$javaClass" ]; then
|
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
|
||||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
fi
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
|
||||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
if command -v wget >/dev/null; then
|
||||||
fi
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
# Compiling the Java class
|
echo "Found wget ... using wget"
|
||||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
fi
|
||||||
fi
|
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
wget "$jarUrl" -O "$wrapperJarPath"
|
||||||
# Running the downloader
|
else
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
|
||||||
echo " - Running MavenWrapperDownloader.java ..."
|
fi
|
||||||
fi
|
elif command -v curl >/dev/null; then
|
||||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
fi
|
echo "Found curl ... using curl"
|
||||||
fi
|
fi
|
||||||
fi
|
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||||
fi
|
curl -o "$wrapperJarPath" "$jarUrl" -f
|
||||||
##########################################################################################
|
else
|
||||||
# End of extension
|
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
|
||||||
##########################################################################################
|
fi
|
||||||
|
|
||||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
else
|
||||||
if [ "$MVNW_VERBOSE" = true ]; then
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
echo $MAVEN_PROJECTBASEDIR
|
echo "Falling back to using Java to download"
|
||||||
fi
|
fi
|
||||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||||
|
# For Cygwin, switch paths to Windows format before running javac
|
||||||
# For Cygwin, switch paths to Windows format before running java
|
if $cygwin; then
|
||||||
if $cygwin; then
|
javaClass=$(cygpath --path --windows "$javaClass")
|
||||||
[ -n "$M2_HOME" ] &&
|
fi
|
||||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
if [ -e "$javaClass" ]; then
|
||||||
[ -n "$JAVA_HOME" ] &&
|
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
[ -n "$CLASSPATH" ] &&
|
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
fi
|
||||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
# Compiling the Java class
|
||||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||||
fi
|
fi
|
||||||
|
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
# Running the downloader
|
||||||
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
exec "$JAVACMD" \
|
echo " - Running MavenWrapperDownloader.java ..."
|
||||||
$MAVEN_OPTS \
|
fi
|
||||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
fi
|
||||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
##########################################################################################
|
||||||
|
# End of extension
|
||||||
|
##########################################################################################
|
||||||
|
|
||||||
|
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||||
|
if [ "$MVNW_VERBOSE" = true ]; then
|
||||||
|
echo $MAVEN_PROJECTBASEDIR
|
||||||
|
fi
|
||||||
|
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")
|
||||||
|
[ -n "$JAVA_HOME" ] &&
|
||||||
|
JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME")
|
||||||
|
[ -n "$CLASSPATH" ] &&
|
||||||
|
CLASSPATH=$(cygpath --path --windows "$CLASSPATH")
|
||||||
|
[ -n "$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" \
|
||||||
|
$MAVEN_OPTS \
|
||||||
|
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||||
|
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||||
|
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
||||||
|
|||||||
343
mvnw.cmd
vendored
343
mvnw.cmd
vendored
@@ -1,161 +1,182 @@
|
|||||||
@REM ----------------------------------------------------------------------------
|
@REM ----------------------------------------------------------------------------
|
||||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||||
@REM or more contributor license agreements. See the NOTICE file
|
@REM or more contributor license agreements. See the NOTICE file
|
||||||
@REM distributed with this work for additional information
|
@REM distributed with this work for additional information
|
||||||
@REM regarding copyright ownership. The ASF licenses this file
|
@REM regarding copyright ownership. The ASF licenses this file
|
||||||
@REM to you under the Apache License, Version 2.0 (the
|
@REM to you under the Apache License, Version 2.0 (the
|
||||||
@REM "License"); you may not use this file except in compliance
|
@REM "License"); you may not use this file except in compliance
|
||||||
@REM with the License. You may obtain a copy of the License at
|
@REM with the License. You may obtain a copy of the License at
|
||||||
@REM
|
@REM
|
||||||
@REM https://www.apache.org/licenses/LICENSE-2.0
|
@REM https://www.apache.org/licenses/LICENSE-2.0
|
||||||
@REM
|
@REM
|
||||||
@REM Unless required by applicable law or agreed to in writing,
|
@REM Unless required by applicable law or agreed to in writing,
|
||||||
@REM software distributed under the License is distributed on an
|
@REM software distributed under the License is distributed on an
|
||||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
@REM KIND, either express or implied. See the License for the
|
@REM KIND, either express or implied. See the License for the
|
||||||
@REM specific language governing permissions and limitations
|
@REM specific language governing permissions and limitations
|
||||||
@REM under the License.
|
@REM under the License.
|
||||||
@REM ----------------------------------------------------------------------------
|
@REM ----------------------------------------------------------------------------
|
||||||
|
|
||||||
@REM ----------------------------------------------------------------------------
|
@REM ----------------------------------------------------------------------------
|
||||||
@REM Maven2 Start Up Batch script
|
@REM Maven2 Start Up Batch script
|
||||||
@REM
|
@REM
|
||||||
@REM Required ENV vars:
|
@REM Required ENV vars:
|
||||||
@REM JAVA_HOME - location of a JDK home dir
|
@REM JAVA_HOME - location of a JDK home dir
|
||||||
@REM
|
@REM
|
||||||
@REM Optional ENV vars
|
@REM Optional ENV vars
|
||||||
@REM M2_HOME - location of maven2's installed home dir
|
@REM M2_HOME - location of maven2's installed home dir
|
||||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
|
||||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||||
@REM e.g. to debug Maven itself, use
|
@REM e.g. to debug Maven itself, use
|
||||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||||
@REM ----------------------------------------------------------------------------
|
@REM ----------------------------------------------------------------------------
|
||||||
|
|
||||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||||
@echo off
|
@echo off
|
||||||
@REM set title of command window
|
@REM set title of command window
|
||||||
title %0
|
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%
|
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||||
|
|
||||||
@REM set %HOME% to equivalent of $HOME
|
@REM set %HOME% to equivalent of $HOME
|
||||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||||
|
|
||||||
@REM Execute a user defined script before this one
|
@REM Execute a user defined script before this one
|
||||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||||
:skipRcPre
|
:skipRcPre
|
||||||
|
|
||||||
@setlocal
|
@setlocal
|
||||||
|
|
||||||
set ERROR_CODE=0
|
set ERROR_CODE=0
|
||||||
|
|
||||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||||
@setlocal
|
@setlocal
|
||||||
|
|
||||||
@REM ==== START VALIDATION ====
|
@REM ==== START VALIDATION ====
|
||||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo Error: JAVA_HOME not found in your environment. >&2
|
echo Error: JAVA_HOME not found in your environment. >&2
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||||
echo location of your Java installation. >&2
|
echo location of your Java installation. >&2
|
||||||
echo.
|
echo.
|
||||||
goto error
|
goto error
|
||||||
|
|
||||||
:OkJHome
|
:OkJHome
|
||||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||||
|
|
||||||
echo.
|
echo.
|
||||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||||
echo location of your Java installation. >&2
|
echo location of your Java installation. >&2
|
||||||
echo.
|
echo.
|
||||||
goto error
|
goto error
|
||||||
|
|
||||||
@REM ==== END VALIDATION ====
|
@REM ==== END VALIDATION ====
|
||||||
|
|
||||||
:init
|
:init
|
||||||
|
|
||||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||||
@REM Fallback to current working directory if not found.
|
@REM Fallback to current working directory if not found.
|
||||||
|
|
||||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||||
|
|
||||||
set EXEC_DIR=%CD%
|
set EXEC_DIR=%CD%
|
||||||
set WDIR=%EXEC_DIR%
|
set WDIR=%EXEC_DIR%
|
||||||
:findBaseDir
|
:findBaseDir
|
||||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||||
cd ..
|
cd ..
|
||||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||||
set WDIR=%CD%
|
set WDIR=%CD%
|
||||||
goto findBaseDir
|
goto findBaseDir
|
||||||
|
|
||||||
:baseDirFound
|
:baseDirFound
|
||||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||||
cd "%EXEC_DIR%"
|
cd "%EXEC_DIR%"
|
||||||
goto endDetectBaseDir
|
goto endDetectBaseDir
|
||||||
|
|
||||||
:baseDirNotFound
|
:baseDirNotFound
|
||||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||||
cd "%EXEC_DIR%"
|
cd "%EXEC_DIR%"
|
||||||
|
|
||||||
:endDetectBaseDir
|
:endDetectBaseDir
|
||||||
|
|
||||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||||
|
|
||||||
@setlocal EnableExtensions EnableDelayedExpansion
|
@setlocal EnableExtensions EnableDelayedExpansion
|
||||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||||
|
|
||||||
:endReadAdditionalConfig
|
:endReadAdditionalConfig
|
||||||
|
|
||||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
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"
|
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
|
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.
|
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||||
if exist %WRAPPER_JAR% (
|
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||||
echo Found %WRAPPER_JAR%
|
if exist %WRAPPER_JAR% (
|
||||||
) else (
|
if "%MVNW_VERBOSE%" == "true" (
|
||||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
echo Found %WRAPPER_JAR%
|
||||||
echo Downloading from: %DOWNLOAD_URL%
|
)
|
||||||
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
|
) else (
|
||||||
echo Finished downloading %WRAPPER_JAR%
|
if not "%MVNW_REPOURL%" == "" (
|
||||||
)
|
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar"
|
||||||
@REM End of extension
|
)
|
||||||
|
if "%MVNW_VERBOSE%" == "true" (
|
||||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||||
if ERRORLEVEL 1 goto error
|
echo Downloading from: %DOWNLOAD_URL%
|
||||||
goto end
|
)
|
||||||
|
|
||||||
:error
|
powershell -Command "&{"^
|
||||||
set ERROR_CODE=1
|
"$webclient = new-object System.Net.WebClient;"^
|
||||||
|
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
|
||||||
:end
|
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
|
||||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
"}"^
|
||||||
|
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
|
||||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
"}"
|
||||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
if "%MVNW_VERBOSE%" == "true" (
|
||||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
echo Finished downloading %WRAPPER_JAR%
|
||||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
)
|
||||||
:skipRcPost
|
)
|
||||||
|
@REM End of extension
|
||||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
|
||||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
@REM Provide a "standardized" way to retrieve the CLI args that will
|
||||||
|
@REM work with both Windows and non-Windows executions.
|
||||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
set MAVEN_CMD_LINE_ARGS=%*
|
||||||
|
|
||||||
exit /B %ERROR_CODE%
|
%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
|
||||||
|
|
||||||
|
:error
|
||||||
|
set ERROR_CODE=1
|
||||||
|
|
||||||
|
:end
|
||||||
|
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||||
|
|
||||||
|
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||||
|
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||||
|
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||||
|
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||||
|
:skipRcPost
|
||||||
|
|
||||||
|
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||||
|
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||||
|
|
||||||
|
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||||
|
|
||||||
|
exit /B %ERROR_CODE%
|
||||||
|
|||||||
20
pom.xml
20
pom.xml
@@ -156,6 +156,26 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
</plugin>
|
</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>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
|||||||
@@ -19,11 +19,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
|||||||
public class InterceptorConfig implements WebMvcConfigurer {
|
public class InterceptorConfig implements WebMvcConfigurer {
|
||||||
@Override
|
@Override
|
||||||
public void addInterceptors(InterceptorRegistry registry) {
|
public void addInterceptors(InterceptorRegistry registry) {
|
||||||
registry.addInterceptor(new MultipleSubmitFilter()).addPathPatterns("/*");
|
registry.addInterceptor(new MultipleSubmitFilter()).addPathPatterns("/**");
|
||||||
|
registry.addInterceptor(new VisitorRecord()).addPathPatterns("/**");
|
||||||
registry.addInterceptor(authenticationFilter()).addPathPatterns("/**");
|
registry.addInterceptor(authenticationFilter()).addPathPatterns("/**");
|
||||||
|
|
||||||
// visitor 输出信息杂乱 暂时放弃使用
|
|
||||||
// registry.addInterceptor(new VisitorRecord()).addPathPatterns("/*");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
@@ -31,11 +29,11 @@ public class InterceptorConfig implements WebMvcConfigurer {
|
|||||||
return new AuthenticationFilter();
|
return new AuthenticationFilter();
|
||||||
}
|
}
|
||||||
|
|
||||||
// // session listener register bean
|
@Bean
|
||||||
// @Bean
|
public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
|
||||||
// public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
|
// session listener register bean
|
||||||
// ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
|
ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
|
||||||
// slrBean.setListener(new SessionListener());
|
slrBean.setListener(new SessionListener());
|
||||||
// return slrBean;
|
return slrBean;
|
||||||
// }
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,12 +41,16 @@ public class AuthenticationFilter implements HandlerInterceptor {
|
|||||||
path = path.replaceAll("/+", "/");
|
path = path.replaceAll("/+", "/");
|
||||||
int indexOf = path.indexOf("/", 1);
|
int indexOf = path.indexOf("/", 1);
|
||||||
String rootPath = indexOf == -1 ? path : path.substring(0, indexOf);
|
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())) {
|
if (!USER_PREFIX.equals(rootPath.toLowerCase()) && !ADMIN_PREFIX.equals(rootPath.toLowerCase())) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
String jwtStr = request.getHeader("Authorization");
|
|
||||||
if (jwtStr == null || jwtStr.isEmpty()) {
|
if (jwtStr == null || jwtStr.isEmpty()) {
|
||||||
return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request);
|
return writeResponse(ResponseEnum.HAVE_NOT_LOG_IN, response, request);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,14 +21,18 @@ public class VisitorRecord implements HandlerInterceptor {
|
|||||||
@Override
|
@Override
|
||||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
|
||||||
HttpSession session = request.getSession();
|
HttpSession session = request.getSession();
|
||||||
|
|
||||||
HashMap<String, Integer> visitDetail = (HashMap<String, Integer>) session.getAttribute("visitDetail");
|
HashMap<String, Integer> visitDetail = (HashMap<String, Integer>) session.getAttribute("visitDetail");
|
||||||
|
if (visitDetail == null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
// 获取访问次数
|
// 获取访问次数
|
||||||
Integer count = visitDetail.get(RequestUtil.getCompleteUrlAndMethod(request));
|
Integer count = visitDetail.get(RequestUtil.getCompleteUrlAndMethod(request));
|
||||||
// 自增
|
// 自增
|
||||||
count = count == null ? 1 : ++count;
|
count = count == null ? 1 : ++count;
|
||||||
// 更新
|
// 更新
|
||||||
visitDetail.put(RequestUtil.getCompleteUrlAndMethod(request), count);
|
visitDetail.put(RequestUtil.getCompleteUrlAndMethod(request), count);
|
||||||
session.setAttribute("ip",request.getRemoteAddr());
|
session.setAttribute("ip", request.getRemoteAddr());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
package cn.celess.blog.configuration.listener;
|
package cn.celess.blog.configuration.listener;
|
||||||
|
|
||||||
import cn.celess.blog.entity.User;
|
|
||||||
import cn.celess.blog.util.RedisUserUtil;
|
import cn.celess.blog.util.RedisUserUtil;
|
||||||
import org.slf4j.Logger;
|
import lombok.extern.log4j.Log4j2;
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
|
||||||
import javax.servlet.annotation.WebListener;
|
import javax.servlet.annotation.WebListener;
|
||||||
@@ -17,20 +15,21 @@ import java.util.HashMap;
|
|||||||
* @Date: 2019/10/18 15:33
|
* @Date: 2019/10/18 15:33
|
||||||
* @Description: 监听session的情况
|
* @Description: 监听session的情况
|
||||||
*/
|
*/
|
||||||
|
@Log4j2
|
||||||
@WebListener
|
@WebListener
|
||||||
public class SessionListener implements HttpSessionListener {
|
public class SessionListener implements HttpSessionListener {
|
||||||
@Autowired
|
@Autowired
|
||||||
RedisUserUtil redisUserUtil;
|
RedisUserUtil redisUserUtil;
|
||||||
@Autowired
|
@Autowired
|
||||||
HttpServletRequest request;
|
HttpServletRequest request;
|
||||||
private static final Logger logger = LoggerFactory.getLogger(SessionListener.class);
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void sessionCreated(HttpSessionEvent se) {
|
public void sessionCreated(HttpSessionEvent se) {
|
||||||
// TODO : can move 'visit' api to here
|
// TODO : can move 'visit' api to here
|
||||||
se.getSession().setAttribute("visitDetail", new HashMap<String, Integer>());
|
se.getSession().setAttribute("visitDetail", new HashMap<String, Integer>());
|
||||||
// se.getSession().setMaxInactiveInterval(10);// 10s for debug
|
// 10s for debug
|
||||||
logger.info("新增一个Session[{}]", se.getSession().getId());
|
// se.getSession().setMaxInactiveInterval(10);
|
||||||
|
// log.info("新增一个Session[{}]", se.getSession().getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
@@ -39,12 +38,15 @@ public class SessionListener implements HttpSessionListener {
|
|||||||
HashMap<String, Integer> visitDetail = (HashMap<String, Integer>) se.getSession().getAttribute("visitDetail");
|
HashMap<String, Integer> visitDetail = (HashMap<String, Integer>) se.getSession().getAttribute("visitDetail");
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
sb.append("ip => ").append(se.getSession().getAttribute("ip"));
|
sb.append("ip => ").append(se.getSession().getAttribute("ip"));
|
||||||
User user = redisUserUtil.get(request);
|
if (visitDetail.size() == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
sb.append("\t登录情况 => ");
|
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) -> {
|
visitDetail.forEach((s, integer) -> {
|
||||||
sb.append("\n").append("Method:[").append(s.split(":")[1]).append("]\tTimes:[").append(integer).append("]\tPath:[").append(s.split(":")[0]).append("]");
|
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);
|
ArticleModel article = articleService.retrieveOneByID(articleId, is4update);
|
||||||
if (article.getOpen()) {
|
if (article.getOpen()) {
|
||||||
return ResponseUtil.success(article);
|
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.success(article);
|
||||||
}
|
}
|
||||||
return ResponseUtil.response(ResponseEnum.PERMISSION_ERROR, null);
|
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.RedisUtil;
|
||||||
import cn.celess.blog.util.ResponseUtil;
|
import cn.celess.blog.util.ResponseUtil;
|
||||||
import cn.celess.blog.util.VeriCodeUtil;
|
import cn.celess.blog.util.VeriCodeUtil;
|
||||||
|
import net.sf.json.JSONArray;
|
||||||
import net.sf.json.JSONObject;
|
import net.sf.json.JSONObject;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -21,8 +22,10 @@ import javax.imageio.ImageIO;
|
|||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import java.awt.image.BufferedImage;
|
import java.awt.image.BufferedImage;
|
||||||
import java.io.IOException;
|
import java.io.*;
|
||||||
import java.io.OutputStream;
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.Enumeration;
|
import java.util.Enumeration;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -169,4 +172,45 @@ public class Other {
|
|||||||
jsonObject.put("message", "上传失败,请上传图片文件");
|
jsonObject.put("message", "上传失败,请上传图片文件");
|
||||||
response.getWriter().println(jsonObject.toString());
|
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.Response;
|
||||||
import cn.celess.blog.entity.Tag;
|
import cn.celess.blog.entity.Tag;
|
||||||
|
import cn.celess.blog.entity.model.TagModel;
|
||||||
import cn.celess.blog.service.TagService;
|
import cn.celess.blog.service.TagService;
|
||||||
import cn.celess.blog.util.ResponseUtil;
|
import cn.celess.blog.util.ResponseUtil;
|
||||||
import net.sf.json.JSONObject;
|
import net.sf.json.JSONObject;
|
||||||
@@ -56,12 +57,11 @@ public class TagController {
|
|||||||
@GetMapping("/tags/nac")
|
@GetMapping("/tags/nac")
|
||||||
public Response getTagNameAndCount() {
|
public Response getTagNameAndCount() {
|
||||||
List<JSONObject> nameAndCount = new ArrayList<>();
|
List<JSONObject> nameAndCount = new ArrayList<>();
|
||||||
List<Tag> all = tagService.findAll();
|
List<TagModel> all = tagService.findAll();
|
||||||
for (Tag t : all) {
|
for (TagModel t : all) {
|
||||||
JSONObject jsonObject = new JSONObject();
|
JSONObject jsonObject = new JSONObject();
|
||||||
jsonObject.put("name", t.getName());
|
jsonObject.put("name", t.getName());
|
||||||
String articles = t.getArticles();
|
jsonObject.put("size", t.getArticles() == null ? 0 : t.getArticles().size());
|
||||||
jsonObject.put("size", articles == null ? 0 : articles.split(",").length);
|
|
||||||
nameAndCount.add(jsonObject);
|
nameAndCount.add(jsonObject);
|
||||||
}
|
}
|
||||||
return ResponseUtil.success(nameAndCount);
|
return ResponseUtil.success(nameAndCount);
|
||||||
|
|||||||
@@ -12,55 +12,60 @@ public enum ResponseEnum {
|
|||||||
ERROR(-2, "错误"),
|
ERROR(-2, "错误"),
|
||||||
|
|
||||||
//文章类
|
//文章类
|
||||||
ARTICLE_NOT_EXIST(201, "文章不存在"),
|
ARTICLE_NOT_EXIST(2010, "文章不存在"),
|
||||||
ARTICLE_HAS_EXIST(202, "文章已存在"),
|
ARTICLE_HAS_EXIST(2020, "文章已存在"),
|
||||||
ARTICLE_NOT_PUBLIC(203, "文章暂未公开"),
|
ARTICLE_NOT_PUBLIC(2030, "文章暂未公开"),
|
||||||
ARTICLE_NOT_BELONG_YOU(204, "无权限操作别人的文章"),
|
ARTICLE_NOT_BELONG_YOU(2040, "无权限操作别人的文章"),
|
||||||
|
|
||||||
//用户类
|
//用户类
|
||||||
HAVE_NOT_LOG_IN(301, "还未登录"),
|
HAVE_NOT_LOG_IN(3010, "还未登录"),
|
||||||
PERMISSION_ERROR(302, "没有此权限"),
|
PERMISSION_ERROR(3020, "没有此权限"),
|
||||||
USER_NOT_EXIST(303, "用户不存在"),
|
USER_NOT_EXIST(3030, "用户不存在"),
|
||||||
USERNAME_HAS_EXIST(304, "用户名已存在"),
|
USERNAME_HAS_EXIST(3040, "用户名已存在"),
|
||||||
USERNAME_TOO_SHORT(305, "用户名太短"),
|
USERNAME_TOO_SHORT(3050, "用户名太短"),
|
||||||
PASSWORD_TOO_SHORT_OR_LONG(306, "密码长度过长或者过短"),
|
PASSWORD_TOO_SHORT_OR_LONG(3060, "密码长度过长或者过短"),
|
||||||
LOGIN_FAILURE(310, "登录失败,用户名/密码不正确"),
|
LOGIN_FAILURE(3100, "登录失败,用户名/密码不正确"),
|
||||||
USEREMAIL_NULL(331, "未设置邮箱"),
|
USEREMAIL_NULL(3310, "未设置邮箱"),
|
||||||
USEREMAIL_NOT_VERIFY(332, "邮箱未验证"),
|
USEREMAIL_NOT_VERIFY(3320, "邮箱未验证"),
|
||||||
LOGIN_LATER(350, "错误次数已达5次,请稍后再试"),
|
LOGIN_LATER(3500, "错误次数已达5次,请稍后再试"),
|
||||||
PWD_SAME(360, "新密码与原密码相同"),
|
PWD_SAME(3600, "新密码与原密码相同"),
|
||||||
LOGIN_EXPIRED(370, "登陆过期"),
|
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_NOT_EXIST(4010, "标签不存在"),
|
||||||
TAG_HAS_EXIST(402, "标签已存在"),
|
TAG_HAS_EXIST(4020, "标签已存在"),
|
||||||
|
|
||||||
//分类
|
//分类
|
||||||
CATEGORY_NOT_EXIST(501, "分类不存在"),
|
CATEGORY_NOT_EXIST(5010, "分类不存在"),
|
||||||
CATEGORY_HAS_EXIST(502, "分类已存在"),
|
CATEGORY_HAS_EXIST(5020, "分类已存在"),
|
||||||
|
|
||||||
//评论/留言
|
//评论/留言
|
||||||
COMMENT_NOT_EXIST(601, "评论/留言不存在"),
|
COMMENT_NOT_EXIST(6010, "评论/留言不存在"),
|
||||||
COMMENT_HAS_EXIST(602, "评论/留言已存在,请不要重复提交"),
|
COMMENT_HAS_EXIST(6020, "评论/留言已存在,请不要重复提交"),
|
||||||
|
|
||||||
//webUdpateInfo amd PartnerSite
|
//webUdpateInfo amd PartnerSite
|
||||||
DATA_NOT_EXIST(701, "数据不存在"),
|
DATA_NOT_EXIST(7010, "数据不存在"),
|
||||||
DATA_HAS_EXIST(702, "数据已存在"),
|
DATA_HAS_EXIST(7020, "数据已存在"),
|
||||||
|
|
||||||
//其他
|
//其他
|
||||||
|
|
||||||
//提交更新之前,没有获取数据/,
|
//提交更新之前,没有获取数据/,
|
||||||
DID_NOT_GET_THE_DATA(802, "非法访问"),
|
DID_NOT_GET_THE_DATA(8020, "非法访问"),
|
||||||
IMG_CODE_TIMEOUT(810, "验证码已失效"),
|
IMG_CODE_TIMEOUT(8100, "验证码已失效"),
|
||||||
IMG_CODE_DIDNOTVERIFY(820, "请先验证验证码"),
|
IMG_CODE_DIDNOTVERIFY(8200, "请先验证验证码"),
|
||||||
VERIFY_ERROR(830, "验证失败"),
|
VERIFY_ERROR(8300, "验证失败"),
|
||||||
PARAMETERS_ERROR(850, "参数错误"),
|
PARAMETERS_ERROR(8500, "参数错误"),
|
||||||
PARAMETERS_URL_ERROR(851, "链接格式错误"),
|
PARAMETERS_URL_ERROR(8510, "链接格式错误"),
|
||||||
PARAMETERS_EMAIL_ERROR(852, "邮箱格式错误"),
|
PARAMETERS_EMAIL_ERROR(8520, "邮箱格式错误"),
|
||||||
PARAMETERS_PHONE_ERROR(853, "手机格式错误"),
|
PARAMETERS_PHONE_ERROR(8530, "手机格式错误"),
|
||||||
PARAMETERS_QQ_ERROR(854, "QQ格式错误"),
|
PARAMETERS_QQ_ERROR(8540, "QQ格式错误"),
|
||||||
PARAMETERS_PWD_ERROR(855, "密码格式错误"),
|
PARAMETERS_PWD_ERROR(8550, "密码格式错误"),
|
||||||
VERIFY_OUT(840, "已经验证过了");
|
VERIFY_OUT(8400, "已经验证过了");
|
||||||
|
|
||||||
private int code;
|
private int code;
|
||||||
private String msg;
|
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;
|
package cn.celess.blog.service;
|
||||||
|
|
||||||
import cn.celess.blog.entity.Category;
|
import cn.celess.blog.entity.Category;
|
||||||
|
import cn.celess.blog.entity.model.CategoryModel;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -17,7 +18,7 @@ public interface CategoryService {
|
|||||||
* @param name 分类名
|
* @param name 分类名
|
||||||
* @return 所增加的分类数据
|
* @return 所增加的分类数据
|
||||||
*/
|
*/
|
||||||
Category create(String name);
|
CategoryModel create(String name);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 增加一个分类
|
* 增加一个分类
|
||||||
@@ -25,7 +26,7 @@ public interface CategoryService {
|
|||||||
* @param category 分类对象
|
* @param category 分类对象
|
||||||
* @return 所增加的分类数据
|
* @return 所增加的分类数据
|
||||||
*/
|
*/
|
||||||
Category create(Category category);
|
CategoryModel create(Category category);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 通过id删除分类
|
* 通过id删除分类
|
||||||
@@ -42,13 +43,13 @@ public interface CategoryService {
|
|||||||
* @param name 分类名字
|
* @param name 分类名字
|
||||||
* @return 更新后的分类的数据
|
* @return 更新后的分类的数据
|
||||||
*/
|
*/
|
||||||
Category update(Long id, String name);
|
CategoryModel update(Long id, String name);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取全部的分类数据
|
* 获取全部的分类数据
|
||||||
*
|
*
|
||||||
* @return 全部的分类数据
|
* @return 全部的分类数据
|
||||||
*/
|
*/
|
||||||
List<Category> retrievePage();
|
List<CategoryModel> retrievePage();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package cn.celess.blog.service;
|
package cn.celess.blog.service;
|
||||||
|
|
||||||
import cn.celess.blog.entity.Tag;
|
import cn.celess.blog.entity.Tag;
|
||||||
|
import cn.celess.blog.entity.model.TagModel;
|
||||||
import com.github.pagehelper.PageInfo;
|
import com.github.pagehelper.PageInfo;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -18,7 +19,7 @@ public interface TagService {
|
|||||||
* @param name 标签名
|
* @param name 标签名
|
||||||
* @return 新增后的数据
|
* @return 新增后的数据
|
||||||
*/
|
*/
|
||||||
Tag create(String name);
|
TagModel create(String name);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 新增数据
|
* 新增数据
|
||||||
@@ -27,7 +28,7 @@ public interface TagService {
|
|||||||
* @return 新增后的数据
|
* @return 新增后的数据
|
||||||
*/
|
*/
|
||||||
|
|
||||||
Tag create(Tag tag);
|
TagModel create(Tag tag);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 删除数据
|
* 删除数据
|
||||||
@@ -44,7 +45,7 @@ public interface TagService {
|
|||||||
* @param name 改名的name值
|
* @param name 改名的name值
|
||||||
* @return 更新后的数据
|
* @return 更新后的数据
|
||||||
*/
|
*/
|
||||||
Tag update(Long id, String name);
|
TagModel update(Long id, String name);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询单个标签信息
|
* 查询单个标签信息
|
||||||
@@ -52,7 +53,7 @@ public interface TagService {
|
|||||||
* @param tagId id
|
* @param tagId id
|
||||||
* @return 标签的数据
|
* @return 标签的数据
|
||||||
*/
|
*/
|
||||||
Tag retrieveOneById(long tagId);
|
TagModel retrieveOneById(long tagId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 通过name查询标签的信息
|
* 通过name查询标签的信息
|
||||||
@@ -60,7 +61,7 @@ public interface TagService {
|
|||||||
* @param name tag的名称
|
* @param name tag的名称
|
||||||
* @return 标签数据
|
* @return 标签数据
|
||||||
*/
|
*/
|
||||||
Tag retrieveOneByName(String name);
|
TagModel retrieveOneByName(String name);
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -70,13 +71,13 @@ public interface TagService {
|
|||||||
* @param page 数据页
|
* @param page 数据页
|
||||||
* @return 分页数据
|
* @return 分页数据
|
||||||
*/
|
*/
|
||||||
PageInfo<Tag> retrievePage(int page, int count);
|
PageInfo<TagModel> retrievePage(int page, int count);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取全部标签数据
|
* 获取全部标签数据
|
||||||
*
|
*
|
||||||
* @return 标签数据列表
|
* @return 标签数据列表
|
||||||
*/
|
*/
|
||||||
List<Tag> findAll();
|
List<TagModel> findAll();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ public class ArticleServiceImpl implements ArticleService {
|
|||||||
article.setUrl(reqBody.getUrl());
|
article.setUrl(reqBody.getUrl());
|
||||||
article.setType(reqBody.getType());
|
article.setType(reqBody.getType());
|
||||||
|
|
||||||
article.setAuthorId(redisUserUtil.get(request).getId());
|
article.setAuthorId(redisUserUtil.get().getId());
|
||||||
article.setPublishDate(new Date());
|
article.setPublishDate(new Date());
|
||||||
|
|
||||||
//防止出现 “null,xxx”这种情况
|
//防止出现 “null,xxx”这种情况
|
||||||
@@ -198,7 +198,7 @@ public class ArticleServiceImpl implements ArticleService {
|
|||||||
Article nextArticle = articleMapper.findArticleById(articleForDel.getNextArticleId());
|
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())) {
|
if (!user.getRole().contains("admin") && !articleForDel.getAuthorId().equals(user.getId())) {
|
||||||
throw new MyException(ResponseEnum.PERMISSION_ERROR);
|
throw new MyException(ResponseEnum.PERMISSION_ERROR);
|
||||||
}
|
}
|
||||||
@@ -277,10 +277,10 @@ public class ArticleServiceImpl implements ArticleService {
|
|||||||
if (reqBody.getCategory() == null || reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
|
if (reqBody.getCategory() == null || reqBody.getCategory().replaceAll(" ", "").isEmpty()) {
|
||||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||||
}
|
}
|
||||||
// 暂时不更新tags
|
// 暂时不更新tags
|
||||||
// if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
|
if (reqBody.getTags() == null || reqBody.getTags().replaceAll(" ", "").isEmpty()) {
|
||||||
// throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||||
// }
|
}
|
||||||
|
|
||||||
//写入数据库的数据
|
//写入数据库的数据
|
||||||
Article article = new Article();
|
Article article = new Article();
|
||||||
@@ -317,26 +317,44 @@ public class ArticleServiceImpl implements ArticleService {
|
|||||||
article.setCategoryId(oldArticle.getCategoryId());
|
article.setCategoryId(oldArticle.getCategoryId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String[] newTags = reqBody.getTags().split(",");
|
||||||
// String[] newTags = reqBody.getTags().replaceAll(" ", "").split(",");
|
String[] tagIds = oldArticle.getTagsId().split(",");
|
||||||
|
//防止出现 ‘null2’这种情况
|
||||||
// //防止出现 ‘null2’这种情况
|
article.setTagsId("");
|
||||||
// article.setTagsId("");
|
for (String t : newTags) {
|
||||||
// for (String t : newTags) {
|
Tag tag = tagMapper.findTagByName(t);
|
||||||
// Tag tag = tagMapper.findTagByName(t);
|
if (tag == null) {
|
||||||
// if (tag == null) {
|
tag = new Tag();
|
||||||
// tag = new Tag();
|
tag.setName(t);
|
||||||
// tag.setName(t);
|
tag.setArticles(oldArticle.getId() + ",");
|
||||||
// tag.setArticles(oldArticle.getId() + ",");
|
int status = tagMapper.insert(tag);
|
||||||
// tag = tagMapper.save(tag);
|
if (status == 0) {
|
||||||
// article.setTagsId(article.getTagsId() + tag.getId() + ",");
|
// 插入失败
|
||||||
// continue;
|
throw new MyException(ResponseEnum.FAILURE);
|
||||||
// }
|
}
|
||||||
// article.setTagsId(article.getTagsId() + tag.getId() + ",");
|
article.setTagsId(article.getTagsId() + tag.getId() + ",");
|
||||||
// }
|
continue;
|
||||||
|
}
|
||||||
// TODO:::: tag的更新
|
article.setTagsId(article.getTagsId() + tag.getId() + ",");
|
||||||
article.setTagsId(oldArticle.getTagsId());
|
}
|
||||||
|
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());
|
article.setUpdateDate(new Date());
|
||||||
@@ -344,7 +362,7 @@ public class ArticleServiceImpl implements ArticleService {
|
|||||||
// 设置不定参数
|
// 设置不定参数
|
||||||
article.setReadingNumber(oldArticle.getReadingNumber());
|
article.setReadingNumber(oldArticle.getReadingNumber());
|
||||||
article.setPublishDate(oldArticle.getPublishDate());
|
article.setPublishDate(oldArticle.getPublishDate());
|
||||||
article.setAuthorId(redisUserUtil.get(request).getId());
|
article.setAuthorId(redisUserUtil.get().getId());
|
||||||
article.setPreArticleId(oldArticle.getPreArticleId());
|
article.setPreArticleId(oldArticle.getPreArticleId());
|
||||||
article.setNextArticleId(oldArticle.getNextArticleId());
|
article.setNextArticleId(oldArticle.getNextArticleId());
|
||||||
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
|
String str = StringFromHtmlUtil.getString(MDTool.markdown2Html(article.getMdContent()));
|
||||||
@@ -362,7 +380,7 @@ public class ArticleServiceImpl implements ArticleService {
|
|||||||
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);
|
throw new MyException(ResponseEnum.ARTICLE_NOT_EXIST);
|
||||||
}
|
}
|
||||||
if (!article.getOpen()) {
|
if (!article.getOpen()) {
|
||||||
User user = redisUserUtil.getWithOutExc(request);
|
User user = redisUserUtil.getWithOutExc();
|
||||||
if (user == null || "user".equals(user.getRole())) {
|
if (user == null || "user".equals(user.getRole())) {
|
||||||
throw new MyException(ResponseEnum.ARTICLE_NOT_PUBLIC);
|
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.enmu.ResponseEnum;
|
||||||
import cn.celess.blog.entity.Article;
|
import cn.celess.blog.entity.Article;
|
||||||
import cn.celess.blog.entity.Category;
|
import cn.celess.blog.entity.Category;
|
||||||
|
import cn.celess.blog.entity.model.CategoryModel;
|
||||||
import cn.celess.blog.exception.MyException;
|
import cn.celess.blog.exception.MyException;
|
||||||
import cn.celess.blog.mapper.ArticleMapper;
|
import cn.celess.blog.mapper.ArticleMapper;
|
||||||
import cn.celess.blog.mapper.CategoryMapper;
|
import cn.celess.blog.mapper.CategoryMapper;
|
||||||
@@ -11,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,7 +29,7 @@ public class CategoryServiceImpl implements CategoryService {
|
|||||||
ArticleMapper articleMapper;
|
ArticleMapper articleMapper;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Category create(String name) {
|
public CategoryModel create(String name) {
|
||||||
if (categoryMapper.existsByName(name)) {
|
if (categoryMapper.existsByName(name)) {
|
||||||
throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST);
|
throw new MyException(ResponseEnum.CATEGORY_HAS_EXIST);
|
||||||
}
|
}
|
||||||
@@ -35,16 +37,16 @@ public class CategoryServiceImpl implements CategoryService {
|
|||||||
category.setName(name);
|
category.setName(name);
|
||||||
category.setArticles("");
|
category.setArticles("");
|
||||||
categoryMapper.insert(category);
|
categoryMapper.insert(category);
|
||||||
return category;
|
return new CategoryModel(category);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Category create(Category category) {
|
public CategoryModel create(Category category) {
|
||||||
if (category == null) {
|
if (category == null) {
|
||||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||||
}
|
}
|
||||||
categoryMapper.insert(category);
|
categoryMapper.insert(category);
|
||||||
return category;
|
return new CategoryModel(category);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -74,18 +76,20 @@ public class CategoryServiceImpl implements CategoryService {
|
|||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Category update(Long id, String name) {
|
public CategoryModel update(Long id, String name) {
|
||||||
if (id == null) {
|
if (id == null) {
|
||||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空");
|
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "id不可为空");
|
||||||
}
|
}
|
||||||
Category category = categoryMapper.findCategoryById(id);
|
Category category = categoryMapper.findCategoryById(id);
|
||||||
category.setName(name);
|
category.setName(name);
|
||||||
categoryMapper.update(category);
|
categoryMapper.update(category);
|
||||||
return category;
|
return new CategoryModel(category);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Category> retrievePage() {
|
public List<CategoryModel> retrievePage() {
|
||||||
return categoryMapper.findAll();
|
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) {
|
if (reqBody == null) {
|
||||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||||
}
|
}
|
||||||
long authorID = redisUserUtil.get(request).getId();
|
long authorID = redisUserUtil.get().getId();
|
||||||
Comment pComment = null;
|
Comment pComment = null;
|
||||||
if (reqBody.getPid() != null && reqBody.getPid() != -1) {
|
if (reqBody.getPid() != null && reqBody.getPid() != -1) {
|
||||||
pComment = commentMapper.findCommentById(reqBody.getPid());
|
pComment = commentMapper.findCommentById(reqBody.getPid());
|
||||||
@@ -147,7 +147,7 @@ public class CommentServiceImpl implements CommentService {
|
|||||||
@Override
|
@Override
|
||||||
public PageInfo<CommentModel> retrievePageByAuthor(Boolean isComment, int page, int count) {
|
public PageInfo<CommentModel> retrievePageByAuthor(Boolean isComment, int page, int count) {
|
||||||
PageHelper.startPage(page, 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 pageInfo = new PageInfo(commentList);
|
||||||
pageInfo.setList(list2List(commentList));
|
pageInfo.setList(list2List(commentList));
|
||||||
return pageInfo;
|
return pageInfo;
|
||||||
|
|||||||
@@ -10,9 +10,7 @@ import com.qiniu.storage.Configuration;
|
|||||||
import com.qiniu.storage.UploadManager;
|
import com.qiniu.storage.UploadManager;
|
||||||
import com.qiniu.storage.model.FileInfo;
|
import com.qiniu.storage.model.FileInfo;
|
||||||
import com.qiniu.util.Auth;
|
import com.qiniu.util.Auth;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.core.env.Environment;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -23,31 +21,29 @@ import java.io.InputStream;
|
|||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
public class QiniuServiceImpl implements QiniuService {
|
public class QiniuServiceImpl implements QiniuService {
|
||||||
private Configuration cfg = new Configuration(Zone.zone2());
|
private static Configuration cfg = new Configuration(Zone.zone2());
|
||||||
private UploadManager uploadManager;
|
private static UploadManager uploadManager;
|
||||||
private BucketManager bucketManager;
|
private static BucketManager bucketManager;
|
||||||
private Auth auth;
|
private static Auth auth;
|
||||||
|
|
||||||
private static String bucket;
|
@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);
|
||||||
*/
|
}
|
||||||
// accessKeyString,secretKeyString,bucketString:请替换为自己的值
|
|
||||||
String accessKey = "accessKeyString";
|
|
||||||
String secretKey = "secretKeyString";
|
|
||||||
bucket = "bucketString";
|
|
||||||
|
|
||||||
auth = Auth.create(accessKey, secretKey);
|
|
||||||
uploadManager = new UploadManager(cfg);
|
|
||||||
bucketManager = new BucketManager(auth, cfg);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public QiniuResponse uploadFile(InputStream is, String fileName) {
|
public QiniuResponse uploadFile(InputStream is, String fileName) {
|
||||||
|
init();
|
||||||
//文件存在则删除文件
|
//文件存在则删除文件
|
||||||
if (continueFile(fileName)) {
|
if (continueFile(fileName)) {
|
||||||
try {
|
try {
|
||||||
@@ -69,6 +65,7 @@ public class QiniuServiceImpl implements QiniuService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public FileInfo[] getFileList() {
|
public FileInfo[] getFileList() {
|
||||||
|
init();
|
||||||
BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, "");
|
BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, "", 1000, "");
|
||||||
FileInfo[] items = null;
|
FileInfo[] items = null;
|
||||||
while (fileListIterator.hasNext()) {
|
while (fileListIterator.hasNext()) {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package cn.celess.blog.service.serviceimpl;
|
|||||||
import cn.celess.blog.enmu.ResponseEnum;
|
import cn.celess.blog.enmu.ResponseEnum;
|
||||||
import cn.celess.blog.entity.Article;
|
import cn.celess.blog.entity.Article;
|
||||||
import cn.celess.blog.entity.Tag;
|
import cn.celess.blog.entity.Tag;
|
||||||
|
import cn.celess.blog.entity.model.TagModel;
|
||||||
import cn.celess.blog.exception.MyException;
|
import cn.celess.blog.exception.MyException;
|
||||||
import cn.celess.blog.mapper.ArticleMapper;
|
import cn.celess.blog.mapper.ArticleMapper;
|
||||||
import cn.celess.blog.mapper.TagMapper;
|
import cn.celess.blog.mapper.TagMapper;
|
||||||
@@ -13,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,7 +31,7 @@ public class TagServiceImpl implements TagService {
|
|||||||
ArticleMapper articleMapper;
|
ArticleMapper articleMapper;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Tag create(String name) {
|
public TagModel create(String name) {
|
||||||
boolean b = tagMapper.existsByName(name);
|
boolean b = tagMapper.existsByName(name);
|
||||||
if (b) {
|
if (b) {
|
||||||
throw new MyException(ResponseEnum.TAG_HAS_EXIST);
|
throw new MyException(ResponseEnum.TAG_HAS_EXIST);
|
||||||
@@ -37,16 +39,16 @@ public class TagServiceImpl implements TagService {
|
|||||||
Tag tag = new Tag();
|
Tag tag = new Tag();
|
||||||
tag.setName(name);
|
tag.setName(name);
|
||||||
tagMapper.insert(tag);
|
tagMapper.insert(tag);
|
||||||
return tag;
|
return new TagModel(tag);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Tag create(Tag tag) {
|
public TagModel create(Tag tag) {
|
||||||
if (tag == null) {
|
if (tag == null) {
|
||||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
throw new MyException(ResponseEnum.PARAMETERS_ERROR);
|
||||||
}
|
}
|
||||||
tagMapper.insert(tag);
|
tagMapper.insert(tag);
|
||||||
return tag;
|
return new TagModel(tag);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -55,12 +57,12 @@ public class TagServiceImpl implements TagService {
|
|||||||
if (tag == null) {
|
if (tag == null) {
|
||||||
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
||||||
}
|
}
|
||||||
if (tag.getArticles()==null){
|
if (tag.getArticles() == null) {
|
||||||
return tagMapper.delete(tagId) == 1;
|
return tagMapper.delete(tagId) == 1;
|
||||||
}
|
}
|
||||||
String[] articleArray = tag.getArticles().split(",");
|
String[] articleArray = tag.getArticles().split(",");
|
||||||
for (int i = 0; i < articleArray.length; i++) {
|
for (int i = 0; i < articleArray.length; i++) {
|
||||||
if (articleArray[i] == null || "".equals(articleArray)) {
|
if (articleArray[i] == null || "".equals(articleArray[i])) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
long articleID = Long.parseLong(articleArray[i]);
|
long articleID = Long.parseLong(articleArray[i]);
|
||||||
@@ -76,7 +78,7 @@ public class TagServiceImpl implements TagService {
|
|||||||
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Tag update(Long id,String name) {
|
public TagModel update(Long id, String name) {
|
||||||
if (id == null) {
|
if (id == null) {
|
||||||
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID");
|
throw new MyException(ResponseEnum.PARAMETERS_ERROR.getCode(), "缺少ID");
|
||||||
}
|
}
|
||||||
@@ -84,37 +86,43 @@ public class TagServiceImpl implements TagService {
|
|||||||
tagFromDB.setName(name);
|
tagFromDB.setName(name);
|
||||||
|
|
||||||
tagMapper.update(tagFromDB);
|
tagMapper.update(tagFromDB);
|
||||||
return tagFromDB;
|
return new TagModel(tagFromDB);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Tag retrieveOneById(long tagId) {
|
public TagModel retrieveOneById(long tagId) {
|
||||||
Tag tag = tagMapper.findTagById(tagId);
|
Tag tag = tagMapper.findTagById(tagId);
|
||||||
if (tag == null) {
|
if (tag == null) {
|
||||||
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
||||||
}
|
}
|
||||||
return tag;
|
return new TagModel(tag);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Tag retrieveOneByName(String name) {
|
public TagModel retrieveOneByName(String name) {
|
||||||
Tag tag = tagMapper.findTagByName(name);
|
Tag tag = tagMapper.findTagByName(name);
|
||||||
if (tag == null) {
|
if (tag == null) {
|
||||||
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
throw new MyException(ResponseEnum.TAG_NOT_EXIST);
|
||||||
}
|
}
|
||||||
return tag;
|
return new TagModel(tag);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PageInfo<Tag> retrievePage(int page, int count) {
|
public PageInfo<TagModel> retrievePage(int page, int count) {
|
||||||
PageHelper.startPage(page, 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;
|
return pageInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Tag> findAll() {
|
public List<TagModel> findAll() {
|
||||||
return tagMapper.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());
|
userMapper.updateLoginTime(loginReq.getEmail(), new Date());
|
||||||
redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime");
|
redisUtil.delete(loginReq.getEmail() + "-passwordWrongTime");
|
||||||
// redis 标记
|
// redis 标记
|
||||||
redisUtil.setEx(loginReq.getEmail() + "-login", JSONObject.fromObject(user).toString(),
|
redisUserUtil.set(user, loginReq.getIsRememberMe());
|
||||||
(loginReq.getIsRememberMe() ? JwtUtil.EXPIRATION_LONG_TIME : JwtUtil.EXPIRATION_SHORT_TIME), TimeUnit.MILLISECONDS);
|
|
||||||
token = jwtUtil.generateToken(user, loginReq.getIsRememberMe());
|
token = jwtUtil.generateToken(user, loginReq.getIsRememberMe());
|
||||||
} else {
|
} else {
|
||||||
logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail());
|
logger.info("====> {} 进行权限认证 状态:登录失败 <====", loginReq.getEmail());
|
||||||
@@ -159,7 +158,7 @@ public class UserServiceImpl implements UserService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public UserModel update(String desc, String displayName) {
|
public UserModel update(String desc, String displayName) {
|
||||||
User user = redisUserUtil.get(request);
|
User user = redisUserUtil.get();
|
||||||
user.setDesc(desc);
|
user.setDesc(desc);
|
||||||
user.setDisplayName(displayName);
|
user.setDisplayName(displayName);
|
||||||
|
|
||||||
@@ -193,7 +192,7 @@ public class UserServiceImpl implements UserService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Object updateUserAavatarImg(InputStream is, String mime) {
|
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());
|
QiniuResponse upload = qiniuService.uploadFile(is, user.getEmail() + "_" + user.getId() + mime.toLowerCase());
|
||||||
user.setAvatarImgUrl(upload.key);
|
user.setAvatarImgUrl(upload.key);
|
||||||
userMapper.updateAvatarImgUrl(upload.key, user.getId());
|
userMapper.updateAvatarImgUrl(upload.key, user.getId());
|
||||||
@@ -203,7 +202,7 @@ public class UserServiceImpl implements UserService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public UserModel getUserInfoBySession() {
|
public UserModel getUserInfoBySession() {
|
||||||
User user = redisUserUtil.get(request);
|
User user = redisUserUtil.get();
|
||||||
return trans(user);
|
return trans(user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -422,7 +421,7 @@ public class UserServiceImpl implements UserService {
|
|||||||
if (updateResult == 0) {
|
if (updateResult == 0) {
|
||||||
throw new MyException(ResponseEnum.FAILURE);
|
throw new MyException(ResponseEnum.FAILURE);
|
||||||
}
|
}
|
||||||
if (redisUserUtil.get(request).getId().equals(userReq.getId())) {
|
if (redisUserUtil.get().getId().equals(userReq.getId())) {
|
||||||
redisUserUtil.set(user);
|
redisUserUtil.set(user);
|
||||||
}
|
}
|
||||||
logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId());
|
logger.info("修改了用户 [id={}] 的用户的资料", userReq.getId());
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
package cn.celess.blog.util;
|
package cn.celess.blog.util;
|
||||||
|
|
||||||
|
import cn.celess.blog.enmu.ResponseEnum;
|
||||||
import cn.celess.blog.entity.User;
|
import cn.celess.blog.entity.User;
|
||||||
import io.jsonwebtoken.Claims;
|
import cn.celess.blog.exception.MyException;
|
||||||
import io.jsonwebtoken.ExpiredJwtException;
|
import io.jsonwebtoken.*;
|
||||||
import io.jsonwebtoken.Jwts;
|
import lombok.extern.log4j.Log4j2;
|
||||||
import io.jsonwebtoken.SignatureAlgorithm;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
@@ -18,6 +19,7 @@ import java.util.Map;
|
|||||||
* @Description: JWT工具类
|
* @Description: JWT工具类
|
||||||
*/
|
*/
|
||||||
@Component
|
@Component
|
||||||
|
@Log4j2
|
||||||
public class JwtUtil {
|
public class JwtUtil {
|
||||||
private static final String CLAIM_KEY_USERNAME = "sub";
|
private static final String CLAIM_KEY_USERNAME = "sub";
|
||||||
|
|
||||||
@@ -33,8 +35,8 @@ public class JwtUtil {
|
|||||||
/**
|
/**
|
||||||
* JWT 秘钥需自行设置不可泄露
|
* JWT 秘钥需自行设置不可泄露
|
||||||
*/
|
*/
|
||||||
private static final String SECRET = "xxx";
|
@Value("${jwt.secret}")
|
||||||
|
private String SECRET;
|
||||||
|
|
||||||
public String generateToken(User user, boolean isRemember) {
|
public String generateToken(User user, boolean isRemember) {
|
||||||
Map<String, Object> claims = new HashMap<>(16);
|
Map<String, Object> claims = new HashMap<>(16);
|
||||||
@@ -47,46 +49,63 @@ public class JwtUtil {
|
|||||||
.compact();
|
.compact();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Boolean validateToken(String token, User user) {
|
public String updateTokenDate(String token) {
|
||||||
String username = getUsernameFromToken(token);
|
Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
|
||||||
|
return Jwts.builder()
|
||||||
return (username.equals(user.getEmail()) && !isTokenExpired(token));
|
.setClaims(claims)
|
||||||
|
.setExpiration(new Date(claims.getExpiration().getTime() + EXPIRATION_SHORT_TIME))
|
||||||
|
.signWith(SignatureAlgorithm.HS512, SECRET)
|
||||||
|
.compact();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取token是否过期
|
* 获取token是否过期
|
||||||
*/
|
*/
|
||||||
public Boolean isTokenExpired(String token) {
|
public Boolean isTokenExpired(String token) {
|
||||||
try {
|
Date expiration = getExpirationDateFromToken(token);
|
||||||
Date expiration = getExpirationDateFromToken(token);
|
return expiration == null || expiration.before(new Date());
|
||||||
return expiration.before(new Date());
|
|
||||||
} catch (ExpiredJwtException e) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据token获取username
|
* 根据token获取username
|
||||||
*/
|
*/
|
||||||
public String getUsernameFromToken(String token) {
|
public String getUsernameFromToken(String token) {
|
||||||
return getClaimsFromToken(token).getSubject();
|
Claims claims = getClaimsFromToken(token);
|
||||||
|
return claims == null ? null : claims.getSubject();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取token的过期时间
|
* 获取token的过期时间
|
||||||
*/
|
*/
|
||||||
public Date getExpirationDateFromToken(String token) {
|
public Date getExpirationDateFromToken(String token) {
|
||||||
return getClaimsFromToken(token).getExpiration();
|
Claims claims = getClaimsFromToken(token);
|
||||||
|
return claims == null ? null : claims.getExpiration();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析JWT
|
* 解析JWT
|
||||||
*/
|
*/
|
||||||
private Claims getClaimsFromToken(String token) {
|
private Claims getClaimsFromToken(String token) {
|
||||||
Claims claims = Jwts.parser()
|
Claims claims = null;
|
||||||
.setSigningKey(SECRET)
|
try {
|
||||||
.parseClaimsJws(token)
|
claims = Jwts.parser()
|
||||||
.getBody();
|
.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;
|
return claims;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,16 +20,18 @@ public class RedisUserUtil {
|
|||||||
RedisUtil redisUtil;
|
RedisUtil redisUtil;
|
||||||
@Autowired
|
@Autowired
|
||||||
JwtUtil jwtUtil;
|
JwtUtil jwtUtil;
|
||||||
|
@Autowired
|
||||||
|
HttpServletRequest request;
|
||||||
|
|
||||||
public User get(HttpServletRequest request) {
|
public User get() {
|
||||||
User user = getWithOutExc(request);
|
User user = getWithOutExc();
|
||||||
if (user == null) {
|
if (user == null) {
|
||||||
throw new MyException(ResponseEnum.HAVE_NOT_LOG_IN);
|
throw new MyException(ResponseEnum.HAVE_NOT_LOG_IN);
|
||||||
}
|
}
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
public User getWithOutExc(HttpServletRequest request) {
|
public User getWithOutExc() {
|
||||||
String token = request.getHeader("Authorization");
|
String token = request.getHeader("Authorization");
|
||||||
if (token == null || token.isEmpty()) {
|
if (token == null || token.isEmpty()) {
|
||||||
return null;
|
return null;
|
||||||
@@ -43,4 +45,11 @@ public class RedisUserUtil {
|
|||||||
redisUtil.getExpire(user.getEmail() + "-login"), TimeUnit.MILLISECONDS);
|
redisUtil.getExpire(user.getEmail() + "-login"), TimeUnit.MILLISECONDS);
|
||||||
return user;
|
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
|
@Async
|
||||||
public void createSitemap() {
|
public void createSitemap() {
|
||||||
initList();
|
initList();
|
||||||
|
if ("".equals(path) || "classpath".equals(path)) {
|
||||||
|
path = System.getProperty("user.dir")+"/sitemap.xml";
|
||||||
|
}
|
||||||
File file = new File(path);
|
File file = new File(path);
|
||||||
try {
|
try {
|
||||||
if (file.exists()) {
|
if (file.exists()) {
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
server.port=8081
|
server.port=8081
|
||||||
|
|
||||||
|
# 七牛的密钥配置
|
||||||
|
qiniu.accessKey=
|
||||||
|
qiniu.secretKey=
|
||||||
|
qiniu.bucket=
|
||||||
|
# sitemap 存放地址
|
||||||
|
sitemap.path=
|
||||||
|
# 生成JWT时候的密钥
|
||||||
|
jwt.secret=
|
||||||
|
|
||||||
spring.jpa.show-sql=false
|
spring.jpa.show-sql=false
|
||||||
spring.jpa.hibernate.ddl-auto=update
|
spring.jpa.hibernate.ddl-auto=update
|
||||||
# 上传单个文件的大小
|
# 上传单个文件的大小
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
server.port=8081
|
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.show-sql=false
|
||||||
##spring.jpa.hibernate.ddl-auto=update
|
##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.type=com.alibaba.druid.pool.DruidDataSource
|
||||||
spring.datasource.url=jdbc:mysql://localhost:3306/test_blog?serverTimezone=UCT&allowPublicKeyRetrieval=true&useSSL=false
|
spring.datasource.url=
|
||||||
spring.datasource.username=root
|
spring.datasource.username=
|
||||||
spring.datasource.password=zhenghai
|
spring.datasource.password=
|
||||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
||||||
|
|
||||||
|
|
||||||
@@ -42,7 +49,7 @@ server.tomcat.protocol-header = X-Forwarded-Proto
|
|||||||
|
|
||||||
|
|
||||||
############### email ##############
|
############### email ##############
|
||||||
spring.mail.host=smtp.163.com
|
spring.mail.host=
|
||||||
spring.mail.username=
|
spring.mail.username=
|
||||||
spring.mail.password=
|
spring.mail.password=
|
||||||
spring.mail.properties.mail.smtp.auth=true
|
spring.mail.properties.mail.smtp.auth=true
|
||||||
|
|||||||
@@ -8,10 +8,12 @@ import org.junit.Test;
|
|||||||
import org.junit.runner.RunWith;
|
import org.junit.runner.RunWith;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.mock.web.MockHttpSession;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
import org.springframework.test.context.junit4.SpringRunner;
|
||||||
import org.springframework.test.context.web.WebAppConfiguration;
|
import org.springframework.test.context.web.WebAppConfiguration;
|
||||||
import org.springframework.test.web.servlet.MockMvc;
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
|
import org.springframework.test.web.servlet.MvcResult;
|
||||||
import org.springframework.test.web.servlet.ResultHandler;
|
import org.springframework.test.web.servlet.ResultHandler;
|
||||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||||
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
|
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
|
||||||
@@ -20,6 +22,8 @@ import org.springframework.web.context.WebApplicationContext;
|
|||||||
|
|
||||||
import javax.servlet.http.Cookie;
|
import javax.servlet.http.Cookie;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,10 +43,12 @@ public class BaseTest {
|
|||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private WebApplicationContext wac;
|
private WebApplicationContext wac;
|
||||||
|
protected MockHttpSession session;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void before() {
|
public void before() {
|
||||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
|
||||||
|
session = new MockHttpSession();
|
||||||
System.out.println("==========> 开始测试 <=========");
|
System.out.println("==========> 开始测试 <=========");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,7 +66,7 @@ public class BaseTest {
|
|||||||
req.setIsRememberMe(false);
|
req.setIsRememberMe(false);
|
||||||
JSONObject loginReq = JSONObject.fromObject(req);
|
JSONObject loginReq = JSONObject.fromObject(req);
|
||||||
String str = mockMvc.perform(MockMvcRequestBuilders.post("/login").content(loginReq.toString()).contentType("application/json"))
|
String str = mockMvc.perform(MockMvcRequestBuilders.post("/login").content(loginReq.toString()).contentType("application/json"))
|
||||||
// .andDo(MockMvcResultHandlers.print())
|
// .andDo(MockMvcResultHandlers.print())
|
||||||
.andReturn().getResponse().getContentAsString();
|
.andReturn().getResponse().getContentAsString();
|
||||||
String token = JSONObject.fromObject(str).getJSONObject(Result).getString("token");
|
String token = JSONObject.fromObject(str).getJSONObject(Result).getString("token");
|
||||||
assertNotNull(token);
|
assertNotNull(token);
|
||||||
@@ -79,7 +85,7 @@ public class BaseTest {
|
|||||||
req.setIsRememberMe(false);
|
req.setIsRememberMe(false);
|
||||||
JSONObject loginReq = JSONObject.fromObject(req);
|
JSONObject loginReq = JSONObject.fromObject(req);
|
||||||
String str = mockMvc.perform(MockMvcRequestBuilders.post("/login").content(loginReq.toString()).contentType("application/json"))
|
String str = mockMvc.perform(MockMvcRequestBuilders.post("/login").content(loginReq.toString()).contentType("application/json"))
|
||||||
// .andDo(MockMvcResultHandlers.print())
|
// .andDo(MockMvcResultHandlers.print())
|
||||||
.andReturn().getResponse().getContentAsString();
|
.andReturn().getResponse().getContentAsString();
|
||||||
String token = JSONObject.fromObject(str).getJSONObject(Result).getString("token");
|
String token = JSONObject.fromObject(str).getJSONObject(Result).getString("token");
|
||||||
assertNotNull(token);
|
assertNotNull(token);
|
||||||
@@ -94,4 +100,8 @@ public class BaseTest {
|
|||||||
public void test() {
|
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 org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||||
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.*;
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||||
@@ -139,32 +138,17 @@ public class ArticleControllerTest extends BaseTest {
|
|||||||
articleReq.setCategory("test");
|
articleReq.setCategory("test");
|
||||||
articleReq.setMdContent("test-" + article.getMdContent());
|
articleReq.setMdContent("test-" + article.getMdContent());
|
||||||
articleReq.setOpen(!article.getOpen());
|
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());
|
articleReq.setTitle("test-" + article.getTitle());
|
||||||
try {
|
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 权限
|
// Admin 权限
|
||||||
token = adminLogin();
|
|
||||||
mockMvc.perform(put("/admin/article/update")
|
mockMvc.perform(put("/admin/article/update")
|
||||||
.content(JSONObject.fromObject(articleReq).toString())
|
.content(JSONObject.fromObject(articleReq).toString())
|
||||||
.contentType("application/json")
|
.contentType("application/json")
|
||||||
.header("Authorization", token))
|
.header("Authorization", adminLogin()))
|
||||||
.andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
.andDo(result -> {
|
.andDo(result -> {
|
||||||
JSONObject jsonObject = JSONObject.fromObject(result.getResponse().getContentAsString());
|
JSONObject jsonObject = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||||
@@ -175,8 +159,11 @@ public class ArticleControllerTest extends BaseTest {
|
|||||||
assertEquals(articleReq.getMdContent(), a.getMdContent());
|
assertEquals(articleReq.getMdContent(), a.getMdContent());
|
||||||
assertEquals(articleReq.getTitle(), a.getTitle());
|
assertEquals(articleReq.getTitle(), a.getTitle());
|
||||||
assertEquals(articleReq.getType(), a.getOriginal());
|
assertEquals(articleReq.getType(), a.getOriginal());
|
||||||
// Tag 暂时不支持更新
|
// Tag
|
||||||
// assertEquals(articleReq.getTags(), Arrays.toString(a.getTags()).replaceAll(" ", "".replace("[", "".replace("]", ""))));
|
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.getOpen(), a.getOpen());
|
||||||
assertEquals(articleReq.getId(), a.getId());
|
assertEquals(articleReq.getId(), a.getId());
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cn.celess.blog.controller;
|
|||||||
|
|
||||||
import cn.celess.blog.BaseTest;
|
import cn.celess.blog.BaseTest;
|
||||||
import cn.celess.blog.entity.Category;
|
import cn.celess.blog.entity.Category;
|
||||||
|
import cn.celess.blog.entity.model.CategoryModel;
|
||||||
import cn.celess.blog.mapper.CategoryMapper;
|
import cn.celess.blog.mapper.CategoryMapper;
|
||||||
import net.sf.json.JSONArray;
|
import net.sf.json.JSONArray;
|
||||||
import net.sf.json.JSONObject;
|
import net.sf.json.JSONObject;
|
||||||
@@ -45,10 +46,10 @@ public class CategoryControllerTest extends BaseTest {
|
|||||||
.andDo(result -> {
|
.andDo(result -> {
|
||||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
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());
|
assertEquals(categoryName, category.getName());
|
||||||
assertNotNull(category.getId());
|
assertNotNull(category.getId());
|
||||||
assertNotNull(category.getArticles());
|
assertNotEquals(0, category.getArticles());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,9 +106,9 @@ public class CategoryControllerTest extends BaseTest {
|
|||||||
.andDo(result -> {
|
.andDo(result -> {
|
||||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
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());
|
assertEquals(name, c.getName());
|
||||||
assertNotNull(c.getArticles());
|
assertNotEquals(0, c.getArticles());
|
||||||
assertNotNull(c.getId());
|
assertNotNull(c.getId());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -121,10 +122,10 @@ public class CategoryControllerTest extends BaseTest {
|
|||||||
JSONArray jsonArray = object.getJSONArray(Result);
|
JSONArray jsonArray = object.getJSONArray(Result);
|
||||||
assertNotNull(jsonArray);
|
assertNotNull(jsonArray);
|
||||||
jsonArray.forEach(o -> {
|
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.getName());
|
||||||
assertNotNull(c.getId());
|
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 {
|
public void apply() throws Exception {
|
||||||
long l = System.currentTimeMillis();
|
long l = System.currentTimeMillis();
|
||||||
String url = "https://www.example.com";
|
String url = "https://www.example.com";
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package cn.celess.blog.controller;
|
|||||||
|
|
||||||
import cn.celess.blog.BaseTest;
|
import cn.celess.blog.BaseTest;
|
||||||
import cn.celess.blog.entity.Tag;
|
import cn.celess.blog.entity.Tag;
|
||||||
|
import cn.celess.blog.entity.model.TagModel;
|
||||||
import cn.celess.blog.mapper.TagMapper;
|
import cn.celess.blog.mapper.TagMapper;
|
||||||
import com.github.pagehelper.PageInfo;
|
import com.github.pagehelper.PageInfo;
|
||||||
import net.sf.json.JSONArray;
|
import net.sf.json.JSONArray;
|
||||||
@@ -29,7 +30,7 @@ public class TagControllerTest extends BaseTest {
|
|||||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||||
JSONObject resJson = object.getJSONObject(Result);
|
JSONObject resJson = object.getJSONObject(Result);
|
||||||
Tag tag = (Tag) JSONObject.toBean(resJson, Tag.class);
|
TagModel tag = (TagModel) JSONObject.toBean(resJson, TagModel.class);
|
||||||
assertNotNull(tag.getId());
|
assertNotNull(tag.getId());
|
||||||
assertEquals(name, tag.getName());
|
assertEquals(name, tag.getName());
|
||||||
});
|
});
|
||||||
@@ -63,9 +64,11 @@ public class TagControllerTest extends BaseTest {
|
|||||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||||
assertNotNull(object.getJSONObject(Result));
|
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(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());
|
assertEquals(tag.getId(), t.getId());
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -79,7 +82,7 @@ public class TagControllerTest extends BaseTest {
|
|||||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||||
assertNotNull(object.getJSONObject(Result));
|
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());
|
assertEquals(tag.getId(), t.getId());
|
||||||
assertNotNull(t.getName());
|
assertNotNull(t.getName());
|
||||||
});
|
});
|
||||||
@@ -93,7 +96,7 @@ public class TagControllerTest extends BaseTest {
|
|||||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||||
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
assertEquals(SUCCESS.getCode(), object.getInt(Code));
|
||||||
assertNotNull(object.getJSONObject(Result));
|
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());
|
assertEquals(tag.getName(), t.getName());
|
||||||
assertNotNull(t.getId());
|
assertNotNull(t.getId());
|
||||||
});
|
});
|
||||||
@@ -119,7 +122,7 @@ public class TagControllerTest extends BaseTest {
|
|||||||
assertEquals(5, pageInfo.getPageSize());
|
assertEquals(5, pageInfo.getPageSize());
|
||||||
// 内容完整
|
// 内容完整
|
||||||
for (Object tag : pageInfo.getList()) {
|
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.getId());
|
||||||
assertNotNull(t.getName());
|
assertNotNull(t.getName());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,10 +14,9 @@ import org.junit.Test;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.mock.web.MockMultipartFile;
|
import org.springframework.mock.web.MockMultipartFile;
|
||||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
import java.io.InputStream;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
import java.io.File;
|
import java.net.URL;
|
||||||
import java.io.FileInputStream;
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
@@ -93,8 +92,12 @@ public class UserControllerTest extends BaseTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void upload() throws Exception {
|
public void upload() throws Exception {
|
||||||
File logoFile = new File("C:\\Users\\zh564\\Pictures\\logo.png");
|
URL url = new URL("https://56462271.oss-cn-beijing.aliyuncs.com/web/logo.png");
|
||||||
MockMultipartFile file = new MockMultipartFile("file", "logo.png", MediaType.IMAGE_PNG_VALUE, new FileInputStream(logoFile));
|
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)).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 -> {
|
mockMvc.perform(multipart("/user/imgUpload").file(file).header("Authorization", userLogin())).andDo(result -> {
|
||||||
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
JSONObject object = JSONObject.fromObject(result.getResponse().getContentAsString());
|
||||||
|
|||||||
@@ -63,7 +63,8 @@ public class VisitorControllerTest extends BaseTest {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
// 手动测试
|
||||||
|
// @Test
|
||||||
public void ipLocation() throws Exception {
|
public void ipLocation() throws Exception {
|
||||||
String ip = "127.0.0.1";
|
String ip = "127.0.0.1";
|
||||||
mockMvc.perform(get("/ip/" + ip)).andDo(MockMvcResultHandlers.print()).andDo(result -> {
|
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.BaseTest;
|
||||||
import cn.celess.blog.entity.User;
|
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.Test;
|
||||||
|
import org.junit.runners.MethodSorters;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
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.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
|
||||||
public class JwtUtilTest extends BaseTest {
|
public class JwtUtilTest extends BaseTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
JwtUtil jwtUtil;
|
JwtUtil jwtUtil;
|
||||||
|
@Value("${jwt.secret}")
|
||||||
|
private String secret;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void generateToken() {
|
public void testGenerateToken() {
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setEmail("a@celess.cn");
|
user.setEmail("a@celess.cn");
|
||||||
String s = jwtUtil.generateToken(user, true);
|
String s = jwtUtil.generateToken(user, false);
|
||||||
System.out.println(s);
|
|
||||||
assertNotNull(s);
|
assertNotNull(s);
|
||||||
|
String str = null;
|
||||||
|
try {
|
||||||
|
str = jwtUtil.generateToken(null, false);
|
||||||
|
} catch (Exception e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
assertNull(str);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@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 user = new User();
|
||||||
user.setEmail("a@celess.cn");
|
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
|
@Test
|
||||||
public void isTokenExpired() {
|
public void testGetExpirationDateFromToken() {
|
||||||
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() {
|
|
||||||
User user = new User();
|
User user = new User();
|
||||||
user.setEmail("a@celess.cn");
|
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