Commit ed27bce1 authored by 谢恒's avatar 谢恒

初始提交

parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ]; then
if [ -f /etc/mavenrc ]; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ]; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false
darwin=false
mingw=false
case "$(uname)" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true ;;
Darwin*)
darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="$(/usr/libexec/java_home)"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ]; then
if [ -r /etc/gentoo-release ]; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
if [ -z "$M2_HOME" ]; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ]; do
ls=$(ls -ld "$PRG")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' >/dev/null; then
PRG="$link"
else
PRG="$(dirname "$PRG")/$link"
fi
done
saveddir=$(pwd)
M2_HOME=$(dirname "$PRG")/..
# make it fully qualified
M2_HOME=$(cd "$M2_HOME" && pwd)
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=$(cygpath --unix "$M2_HOME")
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=$(cygpath --unix "$JAVA_HOME")
[ -n "$CLASSPATH" ] &&
CLASSPATH=$(cygpath --path --unix "$CLASSPATH")
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw; then
[ -n "$M2_HOME" ] &&
M2_HOME="$( (
cd "$M2_HOME"
pwd
))"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="$( (
cd "$JAVA_HOME"
pwd
))"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="$(which javac)"
if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=$(which readlink)
if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then
if $darwin; then
javaHome="$(dirname \"$javaExecutable\")"
javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac"
else
javaExecutable="$(readlink -f \"$javaExecutable\")"
fi
javaHome="$(dirname \"$javaExecutable\")"
javaHome=$(expr "$javaHome" : '\(.*\)/bin')
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ]; then
if [ -n "$JAVA_HOME" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="$(which java)"
fi
fi
if [ ! -x "$JAVACMD" ]; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ]; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]; then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ]; do
if [ -d "$wdir"/.mvn ]; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=$(
cd "$wdir/.."
pwd
)
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' <"$1")"
fi
}
BASE_DIR=$(find_maven_basedir "$(pwd)")
if [ -z "$BASE_DIR" ]; then
exit 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.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in wrapperUrl)
jarUrl="$value"
break
;;
esac
done <"$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl >/dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
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 "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@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
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@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_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@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 ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@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.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
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 location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@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
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
: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%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hs</groupId>
<artifactId>admin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>admin</name>
<description>Admin project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.4</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.hs.admin;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.hs.admin.dao")
public class AdminApplication {
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
}
package com.hs.admin.base;
public enum CodeMessageEnum {
REQUEST_SUCCESS("200", "服务成功返回请求数据"),
UPDATE_SUCCESS("201", "新建或修改数据成功"),
ASYNC_TASK("202", "异步任务"),
DELETE_SUCCESS("204", "删除数据成功"),
REQUEST_ERROR("400", "请求错误"),
NOT_AUTHORITY("401", "用户没有权限"),
RELATIONS_EXIST("402", "有用户正在参与活动,无法执行编辑或删除操作"),
ACCESS_BARRED("403", "禁止访问"),
RECORDS_NOT_EXIST("404", "记录不存在"),
QUOTA_OCCUPIED("802", "名额被占用,无法获取"),
FORMAT_NOT_AVAILABLE("406", "格式不可得"),
RESOURCES_HAS_DELETE("410", "资源已被删除"),
VALIDATION_ERROR("422", "创建对象时验证错误"),
SERVICE_ERROR("500", "服务器错误"),
GATEWAY_ERROR("502", "网关错误"),
SERVICE_NOT_AVAILABLE("503", "服务不可用"),
GATEWAY_TIMEOUT("504", "网关超时");
private String code;
private String msg;
CodeMessageEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getcode(String msg) {
for (CodeMessageEnum codeMsg : CodeMessageEnum.values()) {
if (codeMsg.msg.equals(msg)) {
return codeMsg.code;
}
}
return null;
}
/**
* @description: 获取错误信息
* @param: code
* @return: String
* @author: XieHeng
* @date: 2021/5/6 10:08 上午
*/
public String getMsg(String code) {
for (CodeMessageEnum codeMsg : CodeMessageEnum.values()) {
if (codeMsg.code.equals(code)) {
return codeMsg.msg;
}
}
return null;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
\ No newline at end of file
package com.hs.admin.base;
public class HsRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* 错误编码
*/
private String errorCode;
/**
* 消息是否为属性文件中的Key
*/
private boolean propertiesKey = true;
/**
* 构造一个基本异常.
*
* @param message 信息描述
*/
public HsRuntimeException(String message) {
super(message);
}
/**
* 构造一个基本异常.
*
* @param errorCode 错误编码
* @param message 信息描述
*/
public HsRuntimeException(String errorCode, String message) {
this(errorCode, message, true);
}
/**
* 构造一个基本异常.
*
* @param errorCode 错误编码
* @param message 信息描述
*/
public HsRuntimeException(String errorCode, String message, Throwable cause) {
this(errorCode, message, cause, true);
}
/**
* 构造一个基本异常.
*
* @param errorCode 错误编码
* @param message 信息描述
* @param propertiesKey 消息是否为属性文件中的Key
*/
public HsRuntimeException(String errorCode, String message, boolean propertiesKey) {
super(message);
this.setErrorCode(errorCode);
this.setPropertiesKey(propertiesKey);
}
/**
* 构造一个基本异常.
*
* @param errorCode 错误编码
* @param message 信息描述
*/
public HsRuntimeException(String errorCode, String message, Throwable cause, boolean propertiesKey) {
super(message, cause);
this.setErrorCode(errorCode);
this.setPropertiesKey(propertiesKey);
}
/**
* 构造一个基本异常.
*
* @param message 信息描述
* @param cause 根异常类(可以存入任何异常)
*/
public HsRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public boolean isPropertiesKey() {
return propertiesKey;
}
public void setPropertiesKey(boolean propertiesKey) {
this.propertiesKey = propertiesKey;
}
}
package com.hs.admin.base;
public enum JobStateEnum {
NONE(0),
NORMAL(1),
PAUSED(2),
COMPLETE(3),
ERROR(4),
BLOCKED(5);
JobStateEnum(Integer code) {
this.code = code;
}
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public static void main(String[] args) {
System.out.println(JobStateEnum.NORMAL.getCode());
}
}
\ No newline at end of file
package com.hs.admin.base;
import com.hs.admin.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static java.util.stream.Collectors.joining;
/**
* @Description:AOP拦截打印请求地址、参数
* @Author 何志鹏
* @Date 2020/6/1 14:30
* @Version 1.0
*/
@Aspect
@Component
@Slf4j
public class LogAspect {
//设置切面点
@Pointcut(value = "(execution(* com.hs.admin.controller.*.*(..)))")
public void webLog() {}
//指定切点前的处理方法
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Exception {
//获取request对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
StringBuilder sb = new StringBuilder();
//拼接请求内容
sb.append("\n>>>>>>>>>请求路径:" + request.getRequestURL().toString() + " " + request.getMethod() + "\n");
//判断请求是什么请求
if (request.getMethod().equalsIgnoreCase(RequestMethod.GET.name())) {
Map<String, String[]> parameterMap = request.getParameterMap();
Map<String, String> paramMap = new HashMap<>();
parameterMap.forEach((key, value) -> paramMap.put(key, Arrays.stream(value).collect(joining(","))));
sb.append(">>>>>>>>>请求参数:" + JsonUtils.beanToJson(paramMap));
} else if (request.getMethod().equalsIgnoreCase(RequestMethod.POST.name()) || request.getMethod().equalsIgnoreCase(RequestMethod.PUT.name())) {
Object[] args = joinPoint.getArgs();
StringBuilder stringBuilder = new StringBuilder();
Arrays.stream(args).forEach(object -> stringBuilder.append(object.toString().replace("=",":")));
if (stringBuilder.length() == 0){
stringBuilder.append("{}");
}
sb.append(">>>>>>>>>请求参数:").append(stringBuilder.toString());
}
log.info(sb.toString());
}
//指定切点前的处理方法
@AfterReturning(pointcut = "webLog()",returning = "result")
public void doAfterReturning(Object result) {
if (ObjectUtils.isEmpty(result)){
return;
}
log.info("\n>>>>>>>>>返回結果:" + JsonUtils.beanToJson(result));
}
}
\ No newline at end of file
package com.hs.admin.base;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
@AllArgsConstructor
public class PageResult<E> {
/**
* 总记录数
*/
private Long total;
/**
* 列表
*/
private List<E> list;
}
\ No newline at end of file
package com.hs.admin.base;
import java.io.Serializable;
/**
* @author xieheng
*/
public class Result implements Serializable {
private static final long serialVersionUID = -1L;
/**
* 状态码
*/
private Boolean success;
/**
* 结果消息
*/
private String message;
/**
* 错误码
*/
private String code;
/**
* 返回的数据
*/
private Object data;
/**
* 当前系统时间
*/
private Long timeStamp;
public Result() {
}
/**
* 构造函数
*
* @param success
* @param message
* @param code
* @param data
*/
public Result(Boolean success, String message, String code, Object data) {
this.success = success;
this.message = message;
this.code = code;
this.data = data;
this.timeStamp = System.currentTimeMillis();
}
/**
* 构造函数
*
* @param success
* @param code
* @param data
*/
public Result(Boolean success, String code, Object data) {
this.success = success;
this.code = code;
this.data = data;
this.timeStamp = System.currentTimeMillis();
}
public Result(Boolean success, String message, String code, Object data, long timeStamp) {
this.success = success;
this.message = message;
this.code = code;
this.data = data;
this.timeStamp = timeStamp;
}
/**
* 返回失败
*
* @param codeMessageEnum
* @return
*/
public static Result returnError(CodeMessageEnum codeMessageEnum) {
return new Result(Boolean.FALSE, codeMessageEnum.getMsg(), codeMessageEnum.getCode(), null, System.currentTimeMillis());
}
public static Result returnError() {
return new Result(Boolean.FALSE, CodeMessageEnum.SERVICE_ERROR.getMsg(), CodeMessageEnum.SERVICE_ERROR.getCode(), null, System.currentTimeMillis());
}
/**
* 返回成功
*
* @param data
* @return
*/
public static Result returnSuccess(Object data) {
return new Result(Boolean.TRUE, CodeMessageEnum.REQUEST_SUCCESS.getMsg(), CodeMessageEnum.REQUEST_SUCCESS.getCode(), data, System.currentTimeMillis());
}
/**
* 返回自定义异常
*
* @param e
* @return
*/
public static Result returnHsException(HsRuntimeException e) {
return new Result(Boolean.FALSE, e.getMessage(), e.getErrorCode(), null, System.currentTimeMillis());
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Long timeStamp) {
this.timeStamp = timeStamp;
}
}
\ No newline at end of file
package com.hs.admin.base;
public enum StateEnum {
NOT_BUILD(0, "待生成"),
ENABLE(1, "启用"),
CLOSE(2, "关闭"),
DELETE(3, "删除")
;
private Integer code;
private String value;
private StateEnum(Integer code, String value) {
this.code = code;
this.value = value;
}
public Integer getCode() {
return code;
}
public String getValue() {
return value;
}
}
package com.hs.admin.bean;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* jcb
* @author
*/
@Data
public class Jcb implements Serializable {
private Integer id;
private Integer jcbId;
private String dbName;
private String dbPwd;
private String dbUsername;
private String host;
private String name;
private String port;
private String remark;
private Integer state;
private Date gmtCreate;
private Integer type;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package com.hs.admin.bean;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* sys_task
* @author
*/
@Data
public class SysTask implements Serializable {
private Integer id;
/**
* 租户id
*/
private Integer jcbId;
/**
* 任务名
*/
private String jobName;
/**
* 任务描述
*/
private String content;
/**
* cron表达式
*/
private String cronExpression;
/**
* 任务执行时调用哪个类的方法 包名+类名
*/
private String beanClass;
/**
* 任务状态:NONE:0 ,NORMAL:1 ,PAUSED:2 ,COMPLETE:3 ,ERROR:4 ,BLOCKED:5
*/
private Integer jobStatus;
/**
* 任务分组
*/
private String jobGroup;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 任务操作类型:1查询2新增3修改4删除
*/
private Integer type;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package com.hs.admin.bean;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* user
* @author
*/
@Data
public class User implements Serializable {
private Integer id;
private String userName;
private String password;
private Date gmtCreate;
private Date gmtModify;
public User(String userName, String password) {
this.userName = userName;
this.password = password;
}
public User() {
}
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package com.hs.admin.config;
/**
* @author xieheng
*/
public class GlobalConfig {
public static final String PWD_SALT = "PHSA4DR2WS8DF01DGT7";
}
package com.hs.admin.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**");
}}
\ No newline at end of file
package com.hs.admin.controller;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.base.PageResult;
import com.hs.admin.base.Result;
import com.hs.admin.bean.Jcb;
import com.hs.admin.dto.JcbDto;
import com.hs.admin.service.JcbService;
import com.hs.admin.util.JsonUtils;
import com.hs.admin.util.LoginUserUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @author xieheng
*/
@RestController
public class JcbController {
@Resource
LoginUserUtil loginUserUtil;
@Resource
JcbService jcbService;
/**
* @description: 添加租户/修改
* @param: jcbDto
* @return: String
* @author: XieHeng
* @date: 2021/5/10 8:49 上午
*/
@PutMapping(value = "/api/admin/saveJcb")
public String saveJcb(@RequestBody @Validated JcbDto jcbDto) {
Result result;
try {
loginUserUtil.getLoginUser();
boolean b = jcbService.saveJcb(jcbDto);
if (b) {
result = Result.returnSuccess(null);
} else {
result = Result.returnError();
}
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtils.beanToJson(result);
}
/**
* @description: 删除租户
* @param: jcbId
* @return: String
* @author: XieHeng
* @date: 2021/5/10 9:02 上午
*/
@GetMapping(value = "/api/admin/deleteJcb")
public String delJcb(Integer id) {
Result result;
try {
loginUserUtil.getLoginUser();
boolean b = jcbService.delJcb(id);
if (b) {
result = Result.returnSuccess(null);
} else {
result = Result.returnError();
}
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtils.beanToJson(result);
}
/**
* @description: 获取租户列表
* @param: pageNum
* @param: pageSize
* @return: String
* @author: XieHeng
* @date: 2021/5/10 9:04 上午
*/
@GetMapping(value = "/api/admin/getJcbList")
public String getJcbList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "20") Integer pageSize) {
Result result;
try {
loginUserUtil.getLoginUser();
PageResult<Jcb> pageResult = jcbService.getJcbList(pageNum, pageSize);
result = Result.returnSuccess(pageResult);
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtils.beanToJson(result);
}
}
package com.hs.admin.controller;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.base.Result;
import com.hs.admin.dto.UserDto;
import com.hs.admin.service.UserService;
import com.hs.admin.util.JsonUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
/**
* @author xieheng
*/
@RestController
public class LoginController {
@Resource
UserService userService;
// @Resource
// LoginUserUtil loginUserUtil;
/**
* @description: 登录
* @param: userDto
* @return: String
* @author: XieHeng
* @date: 2021/5/8 3:20 下午
*/
@PostMapping(value = "/api/admin/login")
public String login(@RequestBody UserDto userDto) {
Result result;
try {
Map<String, Object> resultMap = userService.login(userDto);
result = Result.returnSuccess(resultMap);
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtils.beanToJson(result);
}
/**
* @description: 用户列表
* @param: pageNum
* @param: pageSize
* @return: String
* @author: XieHeng
* @date: 2021/5/8 5:37 下午
*/
/* @GetMapping(value = "/api/admin/userList")
public String userList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "20") Integer pageSize) {
Result result;
try {
loginUserUtil.getLoginUser();
List<Map> userList = userService.getList(pageNum, pageSize);
result = Result.returnSuccess(userList);
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
e.printStackTrace();
result = Result.returnError();
}
return JsonUtil.beanToJson(result);
}*/
}
package com.hs.admin.controller;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.base.PageResult;
import com.hs.admin.base.Result;
import com.hs.admin.dto.TaskDto;
import com.hs.admin.service.TaskService;
import com.hs.admin.util.JsonUtils;
import com.hs.admin.util.LoginUserUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Map;
/**
* @author xieheng
*/
@RestController
public class TaskController {
@Resource
LoginUserUtil loginUserUtil;
@Resource
TaskService taskService;
/**
* @description: 添加任务
* @param: dto
* @return: String
* @author: XieHeng
* @date: 2021/5/10 3:23 下午
*/
/*
@PutMapping(value = "/api/admin/saveTask")
public String saveTask(@RequestBody @Validated TaskDto dto) {
Result result;
try {
loginUserUtil.getLoginUser();
boolean b = taskService.saveTask(dto);
if (b) {
result = Result.returnSuccess(null);
} else {
result = Result.returnError();
}
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtil.beanToJson(result);
}
@GetMapping(value = "/api/admin/delTask")
public String delTask(Integer taskId) {
Result result;
try {
loginUserUtil.getLoginUser();
boolean b = taskService.delTask(taskId);
if (b) {
result = Result.returnSuccess(null);
} else {
result = Result.returnError();
}
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtil.beanToJson(result);
}
*/
/**
* @description: 获取分页数据
* @param: taskDto
* @return: String
* @author: XieHeng
* @date: 2021/5/10 3:38 下午
*/
@GetMapping(value = "/api/admin/getTaskList")
public String getTaskList(TaskDto taskDto) {
Result result;
try {
loginUserUtil.getLoginUser();
PageResult<Map> pageResult = taskService.getTaskList(taskDto);
result = Result.returnSuccess(pageResult);
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtils.beanToJson(result);
}
}
package com.hs.admin.controller;
import com.hs.admin.dto.UserDto;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.base.Result;
import com.hs.admin.service.UserService;
import com.hs.admin.util.JsonUtils;
import com.hs.admin.util.LoginUserUtil;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author xieheng
*/
@RestController
public class UserContrller {
@Resource
UserService userService;
@Resource
LoginUserUtil loginUserUtil;
/*
@PutMapping(value = "/api/admin/saveUser")
public String saveUser(@RequestBody UserDto userDto) {
Result result;
try {
loginUserUtil.getLoginUser();
boolean b = userService.saveUser(userDto);
if (b) {
result = Result.returnSuccess(null);
} else {
result = Result.returnError();
}
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtil.beanToJson(result);
}
*/
/**
* @description: 修改密码
* @param: userDto
* @return: String
* @author: XieHeng
* @date: 2021/5/8 3:00 下午
*/
@PutMapping(value = "/api/admin/editPassword")
public String editPassword(@RequestBody UserDto userDto) {
Result result;
try {
loginUserUtil.getLoginUser();
boolean b = userService.editPassword(userDto);
if (b) {
result = Result.returnSuccess(null);
} else {
result = Result.returnError();
}
} catch (HsRuntimeException e) {
result = Result.returnHsException(e);
} catch (Exception e) {
result = Result.returnError();
}
return JsonUtils.beanToJson(result);
}
}
package com.hs.admin.dao;
import com.hs.admin.bean.Jcb;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author xieheng
*/
public interface JcbDao {
int deleteByPrimaryKey(Integer jcbId);
int insert(Jcb record);
Jcb selectByPrimaryKey(Integer jcbId);
int updateByPrimaryKey(Jcb record);
int delJcb(Integer id);
List<Jcb> findAllByState();
int updateById(Jcb jcb);
int checkTask(Integer id);
}
\ No newline at end of file
package com.hs.admin.dao;
import com.hs.admin.bean.SysTask;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface SysTaskDao {
int deleteByPrimaryKey(Integer id);
int insert(SysTask record);
int insertSelective(SysTask record);
SysTask selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(SysTask record);
int updateByPrimaryKey(SysTask record);
int delTask(Integer taskId);
List<Map> findAllByCondition(HashMap<String, Object> map);
int delTaskById(Integer id);
}
\ No newline at end of file
package com.hs.admin.dao;
import com.hs.admin.bean.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
public interface UserDao {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
User findByUserNameAndPassword(@Param("username") String username, @Param("password") String password);
List<Map> findUserList();
}
\ No newline at end of file
package com.hs.admin.dto;
import com.sun.istack.internal.NotNull;
import lombok.Data;
import org.springframework.lang.Nullable;
@Data
public class JcbDto {
private Integer id;
@Nullable
private Integer jcbId;
@NotNull
private String jcbName;
@NotNull
private String host;
@NotNull
private String port;
@NotNull
private String dbName;
@NotNull
private String dbUsername;
@NotNull
private String dbPwd;
private String remark;
@NotNull
private Integer type;
}
package com.hs.admin.dto;
import lombok.Data;
@Data
public class TaskDto {
private Integer id;
private Integer pageNum = 1;
private Integer pageSize = 20;
private Integer jcbId;
private String name;
private Integer type;
private String cronExpression;
private String beanClass;
private String jobStatus;
private String jobGroup;
private String content;
}
package com.hs.admin.dto;
import lombok.Data;
@Data
public class UserDto {
private Integer id;
private String username;
private String password;
private String newpassword;
}
package com.hs.admin.service;
import com.hs.admin.base.PageResult;
import com.hs.admin.bean.Jcb;
import com.hs.admin.dto.JcbDto;
import java.util.List;
/**
* @author xieheng
*/
public interface JcbService {
boolean saveJcb(JcbDto jcbDto);
boolean delJcb(Integer jcbId);
PageResult<Jcb> getJcbList(Integer pageNum, Integer pageSize);
}
package com.hs.admin.service;
import com.hs.admin.base.PageResult;
import com.hs.admin.bean.SysTask;
import com.hs.admin.dto.TaskDto;
import java.util.Map;
/**
* @author xieheng
*/
public interface TaskService {
boolean saveTask(TaskDto dto);
boolean delTask(Integer taskId);
PageResult<Map> getTaskList(TaskDto taskDto);
}
package com.hs.admin.service;
import com.hs.admin.dto.UserDto;
import java.util.List;
import java.util.Map;
/**
* @author xieheng
*/
public interface UserService {
boolean saveUser(UserDto userDto);
boolean editPassword(UserDto userDto);
Map login(UserDto userDto);
List<Map> getList(Integer pageNum, Integer pageSize);
}
package com.hs.admin.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.admin.base.CodeMessageEnum;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.base.PageResult;
import com.hs.admin.base.StateEnum;
import com.hs.admin.bean.Jcb;
import com.hs.admin.dao.JcbDao;
import com.hs.admin.dao.SysTaskDao;
import com.hs.admin.dto.JcbDto;
import com.hs.admin.service.JcbService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
* @author xieheng
*/
@Service
public class JcbServiceImpl implements JcbService {
@Resource
JcbDao jcbDao;
@Resource
SysTaskDao sysTaskDao;
@Override
public boolean saveJcb(JcbDto jcbDto) {
Integer id = jcbDto.getId();
Integer jcbId = jcbDto.getJcbId();
String jcbName = jcbDto.getJcbName();
String remark = jcbDto.getRemark();
String dbName = jcbDto.getDbName();
String host = jcbDto.getHost();
String port = jcbDto.getPort();
String username = jcbDto.getDbUsername();
String pwd = jcbDto.getDbPwd();
Integer type = jcbDto.getType();
Jcb jcb = new Jcb();
jcb.setJcbId(jcbId);
jcb.setName(jcbName);
jcb.setRemark(StringUtils.isEmpty(remark) ? "" : remark);
jcb.setHost(host);
jcb.setPort(port);
jcb.setDbName(dbName);
jcb.setDbUsername(username);
jcb.setDbPwd(pwd);
jcb.setType(ObjectUtils.isEmpty(type) ? 1 : type);
if (id == null) {
jcb.setState(StateEnum.ENABLE.getCode());
jcb.setGmtCreate(new Date());
return jcbDao.insert(jcb) == 1;
} else {
jcb.setId(id);
return jcbDao.updateById(jcb) == 1;
}
}
/**
* @description: 删除租户
* @param: jcbId
* @return: boolean
* @author: XieHeng
* @date: 2021/5/10 9:01 上午
*/
@Override
@Transactional(rollbackFor = Exception.class)
public boolean delJcb(Integer id) {
if (id == null || id < 1) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "参数错误");
}
//校验是否有存在正常的任务。否则不能删除租户
int i = jcbDao.checkTask(id);
if (i > 0) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "租户存在任务,不能删除");
}
if (jcbDao.delJcb(id) == 1) {
sysTaskDao.delTaskById(id);
return true;
}
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "删除失败");
}
@Override
public PageResult<Jcb> getJcbList(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Jcb> jcbList = jcbDao.findAllByState();
PageInfo<Jcb> info = new PageInfo<>(jcbList);
return new PageResult<>(info.getTotal(), info.getList());
}
}
package com.hs.admin.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.admin.base.CodeMessageEnum;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.base.PageResult;
import com.hs.admin.base.StateEnum;
import com.hs.admin.bean.Jcb;
import com.hs.admin.bean.SysTask;
import com.hs.admin.dao.SysTaskDao;
import com.hs.admin.dto.TaskDto;
import com.hs.admin.service.JcbService;
import com.hs.admin.service.TaskService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import javax.print.attribute.standard.JobName;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author xieheng
*/
@Service
public class TaskServiceImpl implements TaskService {
@Resource
SysTaskDao taskDao;
@Resource
JcbService jcbService;
@Override
public boolean saveTask(TaskDto dto) {
Integer jcbId = dto.getJcbId();
Integer id = dto.getId();
String beanClass = dto.getBeanClass();
String cronExpression = dto.getCronExpression();
String jobGroup = dto.getJobGroup();
Integer type = dto.getType();
String name = dto.getName();
SysTask sysTask = new SysTask();
if (!StringUtils.isEmpty(name)) {
sysTask.setJobName(name);
}
if (!StringUtils.isEmpty(type)) {
sysTask.setType(type);
}
if (!StringUtils.isEmpty(cronExpression)) {
sysTask.setCronExpression(cronExpression);
}
if (!StringUtils.isEmpty(beanClass)) {
sysTask.setBeanClass(beanClass);
}
if (!StringUtils.isEmpty(name)) {
sysTask.setJobName(name);
}
if (!StringUtils.isEmpty(jobGroup)) {
sysTask.setJobGroup(jobGroup);
}
if (id == null) {
sysTask.setJcbId(jcbId);
sysTask.setContent("");
sysTask.setJobStatus(StateEnum.ENABLE.getCode());
sysTask.setCreateTime(new Date());
sysTask.setUpdateTime(new Date());
return taskDao.insert(sysTask) == 1;
} else {
sysTask.setId(id);
return taskDao.updateByPrimaryKey(sysTask) == 1;
}
}
@Override
public boolean delTask(Integer taskId) {
int i = 0;
try {
i = taskDao.delTask(taskId);
} catch (Exception e) {
e.printStackTrace();
}
return i == 1;
}
@Override
public PageResult<Map> getTaskList(TaskDto taskDto) {
Integer jcbId = taskDto.getJcbId();
if (jcbId == null) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "缺少租户Id");
}
HashMap<String, Object> map = new HashMap<>();
map.put("jcbId", jcbId);
PageHelper.startPage(taskDto.getPageNum(), taskDto.getPageSize());
List<Map> sysTaskList = taskDao.findAllByCondition(map);
PageInfo<Map> info = new PageInfo<>(sysTaskList);
return new PageResult<>(info.getTotal(), info.getList());
}
}
package com.hs.admin.service.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.hs.admin.bean.User;
import com.hs.admin.dao.UserDao;
import com.hs.admin.dto.UserDto;
import com.hs.admin.base.CodeMessageEnum;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.config.GlobalConfig;
import com.hs.admin.service.UserService;
import com.hs.admin.util.PasswordUtil;
import com.hs.admin.util.TokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
/**
* @author xieheng
*/
@Service
public class UserServiceImpl implements UserService {
@Resource
UserDao userDao;
@Override
public boolean saveUser(UserDto dto) {
String username = dto.getUsername();
String password = dto.getPassword().replaceAll(" ", "");
if (StringUtils.isEmpty(username)) {
throw new HsRuntimeException(CodeMessageEnum.RECORDS_NOT_EXIST.getCode(), "用户名不能为空");
}
if (StringUtils.isEmpty(password)) {
throw new HsRuntimeException(CodeMessageEnum.RECORDS_NOT_EXIST.getCode(), "密码不能为空");
}
if (password.length() < 6) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "密码长度不合要求");
}
password = PasswordUtil.passwordEncode(password, GlobalConfig.PWD_SALT);
User user = new User();
user.setUserName(username);
user.setPassword(password);
user.setGmtCreate(new Date());
user.setGmtModify(new Date());
try {
userDao.insert(user);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* @description: 修改密码
* @param: userDto
* @return: boolean
* @author: XieHeng
* @date: 2021/5/8 3:00 下午
*/
@Override
public boolean editPassword(UserDto userDto) {
if (userDto.getId() < 1) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "参数错误");
}
User user = userDao.selectByPrimaryKey(userDto.getId());
if (user == null) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "用户不存在");
}
String password = userDto.getPassword();
String newpassword = userDto.getNewpassword();
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(newpassword)) {
throw new HsRuntimeException(CodeMessageEnum.RECORDS_NOT_EXIST.getCode(), "密码不能为空");
}
if (password.length() < 6) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "密码长度不合要求");
}
String passwordEncode = PasswordUtil.passwordEncode(password, GlobalConfig.PWD_SALT);
if (!user.getPassword().equals(passwordEncode)) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "更改密码失败,原密码错误");
}
password = PasswordUtil.passwordEncode(newpassword, GlobalConfig.PWD_SALT);
user.setPassword(password);
user.setGmtModify(new Date());
try {
userDao.insert(user);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public Map<String, Object> login(UserDto userDto) {
String username = userDto.getUsername();
String password = userDto.getPassword();
if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username)) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "用户名或密码错误");
}
if ("administrator".equals(username) && "administrator".equals(password)) {
String token = TokenUtils.token(username, password);
Map<String, Object> map = new HashMap<>();
map.put("token", token);
return map;
}
password = PasswordUtil.passwordEncode(password, GlobalConfig.PWD_SALT);
User user = userDao.findByUserNameAndPassword(username, password);
if (user != null) {
String token = TokenUtils.token(username, password);
Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("userId", user.getId());
return map;
}
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(), "用户名或密码错误");
}
@Override
public List<Map> getList(Integer pageNum, Integer pageSize) {
return userDao.findUserList();
}
}
package com.hs.admin.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: Lee CE @Description: @Date: 2018/7/13 10:31 @Modified:
*/
public class JsonUtils {
/**
* Bean对象转JSON
*
* @param object
* @param dataFormatString
* @return
*/
public static String beanToJson(Object object, String dataFormatString) {
if (object != null) {
if (StringUtils.isEmpty(dataFormatString)) {
return JSONObject.toJSONString(object);
}
return JSON.toJSONStringWithDateFormat(object, dataFormatString);
} else {
return null;
}
}
/**
* 将json字符串转换成对象
*
* @param json
* @param clazz
* @return
*/
public static <T> T jsonToBean(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json) || clazz == null) {
return null;
}
return JSON.parseObject(json, clazz);
}
/**
* Bean对象转JSON
*
* @param object
* @return
*/
public static String beanToJson(Object object) {
if (object != null) {
return JSON.toJSONString(object, SerializerFeature.DisableCircularReferenceDetect);
} else {
return null;
}
}
/**
* String转JSON字符串
*
* @param key
* @param value
* @return
*/
public static String stringToJsonByFastjson(String key, String value) {
if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
map.put(key, value);
return beanToJson(map, null);
}
/**
* json字符串转map
*
* @param json
* @return
*/
public static Map<String, Object> jsonToMap(String json) {
if (StringUtils.isEmpty(json)) {
return null;
}
return JSON.parseObject(json, Map.class);
}
/**
* json字符串转list
*
* @param jsonStr
* @return
*/
public static <T> List<T> stringToList(String jsonStr, Class<T> model) {
List<T> object = (List<T>) JSONArray.parseArray(jsonStr, model);
return object;
}
public static <T> List<String> stringToList2(String jsonStr, Class<String> model) {
List<java.lang.String> object = (List<String>) JSONArray.parseArray(jsonStr, model);
return object;
}
public static <T> List<T> jsonToList(String json, Class<T> clazz) {
if (StringUtils.isEmpty(json)) {
return null;
}
return JSONArray.parseArray(json, clazz);
}
}
package com.hs.admin.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogUtil {
private static final Logger LOGGER = LoggerFactory.getLogger("error");
/**
* @Description: 记录debug日志
* @params: [messages]
* @Return: void
* @Author: lixin
* @Date: 2018/11/2 14:19
* @Modified:
*/
public static void debug(String... messages) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(mergeStrings(messages));
}
}
/**
* @Description: 记录Info日志
* @params: [messages]
* @Return: void
* @Author: lixin
* @Date: 2018/11/2 14:19
* @Modified:
*/
public static void info(String... messages) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info(mergeObjects(messages));
}
}
/**
* @Description: 记录warn日志
* @params: [messages]
* @Return: void
* @Author: lixin
* @Date: 2018/11/2 14:19
* @Modified:
*/
public static void warn(String... messages) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(mergeObjects(messages));
}
}
/**
* @Description: 记录错误日志
* @params: [messages]
* @Return: void
* @Author: lixin
* @Date: 2018/11/2 14:23
* @Modified:
*/
public static void error(String... messages) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(mergeStrings(messages));
}
}
/**
* @Description: 记录fatal错误日志
* @params: [messages]
* @Return: void
* @Author: weiyuqi
* @Date: 2019/6/17 14:20
* @Modified:
*/
public static void fatal(String... messages) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error(mergeStrings(messages));
}
}
/**
* @Description: 记录错误日志
* @params: [e, messages]
* @Return: void
* @Author: lixin
* @Date: 2018/11/2 14:23
* @Modified:
*/
public static void error(Throwable e, String... messages) {
if (LOGGER.isErrorEnabled()) {
if (e == null) {
LOGGER.error(mergeStrings(messages));
} else {
LOGGER.error(mergeStrings(messages), e);
}
}
}
/**
* @Description: 记录fatal日志
* @params: [e, messages]
* @Return: void
* @Author: weiyuqi
* @Date: 2019/6/17 14:22
* @Modified:
*/
public static void fatal(Throwable e, String... messages) {
if (LOGGER.isErrorEnabled()) {
if (e == null) {
LOGGER.error(mergeStrings(messages));
} else {
LOGGER.error(mergeStrings(messages), e);
}
}
}
/**
* @Description: 将string数组合并为一个字符串返回
* @params: [strings]
* @Return: java.lang.String
* @Author: lixin
* @Date: 2018/11/2 14:21
* @Modified:
*/
private static String mergeStrings(String[] strings) {
if (strings == null) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
for (String string : strings) {
stringBuilder.append(string);
}
return stringBuilder.toString();
}
/**
* @Description: 将string数组合并为一个字符串返回
* @params: [objects]
* @Return: java.lang.String
* @Author: lixin
* @Date: 2018/11/2 14:21
* @Modified:
*/
private static String mergeObjects(Object[] objects) {
if (objects == null) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
for (Object obj : objects) {
if (obj == null) {
continue;
}
if (obj instanceof String) {
stringBuilder.append(obj);
} else {
stringBuilder.append(obj.toString());
}
}
return stringBuilder.toString();
}
}
package com.hs.admin.util;
import com.hs.admin.bean.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Component
public class LoginUserUtil {
public User getLoginUser() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
String token = request.getHeader("token");
return TokenUtils.verify(token);
}
}
package com.hs.admin.util;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* 使用:
* 直接使用即可,至于具体参数,看下面方法的说明即可;
* 1. PasswordUtil.MD5Encode(); MD5不可逆简单加密:散列函数-基于HASH算法的编码
* 2. PasswordUtil.AESEncrypt(); AES加密
* 3. PasswordUtil.AESDecrypt(); AES解密
* 4. PasswordUtil.parseByte2HexStr(); 二进制到16进制
* 5. PasswordUtil.parseHexStr2Byte(); 16进制到2进制
*/
public class PasswordUtil {
/**
* 16进制的字符数组
*/
private final static String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
public static String passwordEncode(String source, String salt) {
return MD5(MD5(MD5(source, salt), salt));
}
public static String MD5(String source) {
return MD5Encode(source, "UTF-8", true);
}
public static String MD5(String source, String salt) {
return MD5Encode(source + salt, "UTF-8", true);
}
/**
* @param source 原字符串
* @param encoding 指定编码类型
* @param uppercase 是否转为大写字符串
*/
public static String MD5Encode(String source, String encoding, boolean uppercase) {
String result = null;
try {
result = source;
// 获得MD5摘要对象
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// 使用指定的字节数组更新摘要信息
messageDigest.update(result.getBytes(encoding));
// messageDigest.digest()获得16位长度
// result = parseByte2HexStr(messageDigest.digest());
result = byteArrayToHexString(messageDigest.digest());
} catch (Exception e) {
e.printStackTrace();
}
return uppercase ? result.toUpperCase() : result;
}
/**
* AES 加密
*
* @param content 需要加密的内容
* @param aesKey 加密密钥
* @return
*/
public static byte[] AESEncrypt(String content, String aesKey) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(aesKey.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
*
* @param content 待解密内容
* @param aesKey 解密密钥 秘miyao
* @return
*/
public static byte[] AESDecrypt(byte[] content, String aesKey) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(aesKey.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 将二进制转换成16进制
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
//byte转16进制
private static String byteArrayToHexString(byte[] bytes) {
StringBuilder stringBuilder = new StringBuilder();
for (byte tem : bytes) {
stringBuilder.append(byteToHexString(tem));
}
return stringBuilder.toString();
}
//16进制转byte[]
private static String byteToHexString(byte b) {
int n = b;
if (n < 0) {
n = 256 + n;
}
int d1 = n / 16;
int d2 = n % 16;
return HEX_DIGITS[d1] + HEX_DIGITS[d2];
}
}
package com.hs.admin.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hs.admin.base.CodeMessageEnum;
import com.hs.admin.base.HsRuntimeException;
import com.hs.admin.bean.User;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author xieheng
* @desc 使用token验证用户是否登录
**/
public class TokenUtils {
//设置过期时间
private static final long EXPIRE_DATE = 30 * 60 * 100000;
//token秘钥
private static final String TOKEN_SECRET = "HSfasfhuaUUHufguGuwu2020BQWE";
public static String token(String username, String password) {
String token;
try {
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
//秘钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//设置头部信息
Map<String, Object> header = new HashMap<>();
header.put("typ", "JWT");
header.put("alg", "HS256");
//携带username,password信息,生成签名
token = JWT.create()
.withHeader(header)
.withClaim("username", username)
.withClaim("password", password).withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return token;
}
public static User verify(String token) {
/**
* @desc 验证token,通过返回true
* @params [token]需要校验的串
**/
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
String username = jwt.getClaim("username").asString();
String password = jwt.getClaim("password").asString();
return new User(username, password);
} catch (Exception e) {
throw new HsRuntimeException(CodeMessageEnum.REQUEST_ERROR.getCode(),"token错误");
}
}
public static void main(String[] args) {
String username = "zhangsan";
String password = "123";
String token = token(username, password);
User user = verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTYyMDY0MTEzNywidXNlcm5hbWUiOiJ6aGFuZ3NhbiJ9.TIFCrGeFCzFiviwUUIS29hklA3fZDXTwb8EZwwb8JiQ1");
System.out.println(token);
}
}
\ No newline at end of file
spring.application.name=admin
server.port=8090
#mybatis
mybatis.mapperLocations=classpath:mapper/*.xml
logging.level.com.hs.admin.dao=debug
#db
spring.datasource.url=jdbc:mysql://localhost:3306/xh-test?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.read-only=false
spring.datasource.hikari.connection-timeout=60000
spring.datasource.hikari.idle-timeout=60000
spring.datasource.hikari.validation-timeout=3000
spring.datasource.hikari.max-lifetime=60000
spring.datasource.hikari.login-timeout=5
spring.datasource.hikari.maximum-pool-size=300
spring.datasource.hikari.minimum-idle=10
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hs.admin.dao.JcbDao">
<resultMap id="BaseResultMap" type="com.hs.admin.bean.Jcb">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="jcb_id" jdbcType="INTEGER" property="jcbId"/>
<result column="db_name" jdbcType="VARCHAR" property="dbName"/>
<result column="db_pwd" jdbcType="VARCHAR" property="dbPwd"/>
<result column="db_username" jdbcType="VARCHAR" property="dbUsername"/>
<result column="host" jdbcType="VARCHAR" property="host"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="port" jdbcType="VARCHAR" property="port"/>
<result column="remark" jdbcType="VARCHAR" property="remark"/>
<result column="state" jdbcType="INTEGER" property="state"/>
<result column="gmt_create" jdbcType="TIMESTAMP" property="gmtCreate"/>
<result column="type" jdbcType="INTEGER" property="type"/>
</resultMap>
<sql id="Base_Column_List">
id,jcb_id, db_name, db_pwd, db_username, `host`, `name`, port, remark, `state`, gmt_create,type
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from jcb
where jcb_id = #{jcbId,jdbcType=INTEGER}
</select>
<select id="findAllByState" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from jcb where state=1 order by gmt_create desc
</select>
<select id="checkTask" resultType="java.lang.Integer">
select count(*)
from jcb j
left join sys_task st on j.jcb_id = st.jcb_id
where j.state = 1
and st.job_status = 1
and j.id = #{id}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete
from jcb
where jcb_id = #{jcbId,jdbcType=INTEGER}
</delete>
<update id="delJcb">
update jcb
set state=3
where state = 1
and id = #{id}
</update>
<insert id="insert" keyColumn="jcb_id" keyProperty="jcbId" parameterType="com.hs.admin.bean.Jcb"
useGeneratedKeys="true">
insert into jcb (jcb_id, db_name, db_pwd, db_username,
`host`, `name`, port, remark,
`state`, gmt_create, type)
values (#{jcbId}, #{dbName,jdbcType=VARCHAR}, #{dbPwd,jdbcType=VARCHAR}, #{dbUsername,jdbcType=VARCHAR},
#{host,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{port,jdbcType=VARCHAR},
#{remark,jdbcType=VARCHAR},
#{state,jdbcType=INTEGER}, #{gmtCreate,jdbcType=TIMESTAMP}, #{type})
</insert>
<update id="updateById" parameterType="com.hs.admin.bean.Jcb">
update jcb
<set>
<if test="dbName != null">
db_name = #{dbName,jdbcType=VARCHAR},
</if>
<if test="dbPwd != null">
db_pwd = #{dbPwd,jdbcType=VARCHAR},
</if>
<if test="dbUsername != null">
db_username = #{dbUsername,jdbcType=VARCHAR},
</if>
<if test="host != null">
`host` = #{host,jdbcType=VARCHAR},
</if>
<if test="name != null">
`name` = #{name,jdbcType=VARCHAR},
</if>
<if test="port != null">
port = #{port,jdbcType=VARCHAR},
</if>
<if test="remark != null">
remark = #{remark,jdbcType=VARCHAR},
</if>
<if test="state != null">
`state` = #{state,jdbcType=INTEGER},
</if>
<if test="gmtCreate != null">
gmt_create = #{gmtCreate,jdbcType=TIMESTAMP},
</if>
<if test="type != null">
type= #{type}
</if>
</set>
where id = #{id}
</update>
<update id="updateByPrimaryKey" parameterType="com.hs.admin.bean.Jcb">
update jcb
set db_name = #{dbName,jdbcType=VARCHAR},
db_pwd = #{dbPwd,jdbcType=VARCHAR},
db_username = #{dbUsername,jdbcType=VARCHAR},
`host` = #{host,jdbcType=VARCHAR},
`name` = #{name,jdbcType=VARCHAR},
port = #{port,jdbcType=VARCHAR},
remark = #{remark,jdbcType=VARCHAR},
`state` = #{state,jdbcType=INTEGER},
gmt_create = #{gmtCreate,jdbcType=TIMESTAMP},
type = #{type}
where id = #{id}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hs.admin.dao.SysTaskDao">
<resultMap id="BaseResultMap" type="com.hs.admin.bean.SysTask">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="jcb_id" jdbcType="INTEGER" property="jcbId"/>
<result column="job_name" jdbcType="VARCHAR" property="jobName"/>
<result column="content" jdbcType="VARCHAR" property="content"/>
<result column="cron_expression" jdbcType="VARCHAR" property="cronExpression"/>
<result column="bean_class" jdbcType="VARCHAR" property="beanClass"/>
<result column="job_status" jdbcType="INTEGER" property="jobStatus"/>
<result column="job_group" jdbcType="VARCHAR" property="jobGroup"/>
<result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
<result column="type" jdbcType="INTEGER" property="type"/>
</resultMap>
<sql id="Base_Column_List">
id, jcb_id, job_name, content, cron_expression, bean_class, job_status, job_group,
create_time, update_time, `type`
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from sys_task
where id = #{id,jdbcType=INTEGER}
</select>
<select id="findAllByCondition" resultType="java.util.Map">
select st.jcb_id jcbId,
st.job_name jobName,
st.content,
st.cron_expression cronExpression,
st.bean_class beanClass,
st.job_status jobStatus,
st.job_group jobGroup,
UNIX_TIMESTAMP(st.create_time) createTime,
st.type,
j.name
from jcb j
left join sys_task st on j.jcb_id = st.jcb_id
where st.jcb_id = #{jcbId}
and st.job_status != 3
order by st.create_time desc
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete
from sys_task
where id = #{id,jdbcType=INTEGER}
</delete>
<update id="delTaskById">
update sys_task
set job_status=3
where job_status!=3 and jcb_id = (select jcb_id from jcb where id = #{id} limit 1)
</update>
<update id="delTask">
update sys_task
set job_status=3
where id = #{taskId}
</update>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.hs.admin.bean.SysTask"
useGeneratedKeys="true">
insert into sys_task (jcb_id, job_name, content,
cron_expression, bean_class, job_status,
job_group, create_time, update_time,
`type`)
values (#{jcbId,jdbcType=VARCHAR}, #{jobName,jdbcType=VARCHAR}, #{content,jdbcType=VARCHAR},
#{cronExpression,jdbcType=VARCHAR}, #{beanClass,jdbcType=VARCHAR}, #{jobStatus,jdbcType=BOOLEAN},
#{jobGroup,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP},
#{type,jdbcType=BOOLEAN})
</insert>
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.hs.admin.bean.SysTask"
useGeneratedKeys="true">
insert into sys_task
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="jcbId != null">
jcb_id,
</if>
<if test="jobName != null">
job_name,
</if>
<if test="content != null">
content,
</if>
<if test="cronExpression != null">
cron_expression,
</if>
<if test="beanClass != null">
bean_class,
</if>
<if test="jobStatus != null">
job_status,
</if>
<if test="jobGroup != null">
job_group,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
<if test="type != null">
`type`,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="jcbId != null">
#{jcbId,jdbcType=VARCHAR},
</if>
<if test="jobName != null">
#{jobName,jdbcType=VARCHAR},
</if>
<if test="content != null">
#{content,jdbcType=VARCHAR},
</if>
<if test="cronExpression != null">
#{cronExpression,jdbcType=VARCHAR},
</if>
<if test="beanClass != null">
#{beanClass,jdbcType=VARCHAR},
</if>
<if test="jobStatus != null">
#{jobStatus,jdbcType=BOOLEAN},
</if>
<if test="jobGroup != null">
#{jobGroup,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="type != null">
#{type,jdbcType=BOOLEAN},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.hs.admin.bean.SysTask">
update sys_task
<set>
<if test="jcbId != null">
jcb_id = #{jcbId,jdbcType=VARCHAR},
</if>
<if test="jobName != null">
job_name = #{jobName,jdbcType=VARCHAR},
</if>
<if test="content != null">
content = #{content,jdbcType=VARCHAR},
</if>
<if test="cronExpression != null">
cron_expression = #{cronExpression,jdbcType=VARCHAR},
</if>
<if test="beanClass != null">
bean_class = #{beanClass,jdbcType=VARCHAR},
</if>
<if test="jobStatus != null">
job_status = #{jobStatus,jdbcType=BOOLEAN},
</if>
<if test="jobGroup != null">
job_group = #{jobGroup,jdbcType=VARCHAR},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=TIMESTAMP},
</if>
<if test="type != null">
`type` = #{type,jdbcType=BOOLEAN},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.hs.admin.bean.SysTask">
update sys_task
set jcb_id = #{jcbId,jdbcType=VARCHAR},
job_name = #{jobName,jdbcType=VARCHAR},
content = #{content,jdbcType=VARCHAR},
cron_expression = #{cronExpression,jdbcType=VARCHAR},
bean_class = #{beanClass,jdbcType=VARCHAR},
job_status = #{jobStatus,jdbcType=BOOLEAN},
job_group = #{jobGroup,jdbcType=VARCHAR},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP},
`type` = #{type,jdbcType=BOOLEAN}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hs.admin.dao.UserDao">
<resultMap id="BaseResultMap" type="com.hs.admin.bean.User">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="user_name" jdbcType="VARCHAR" property="userName"/>
<result column="password" jdbcType="VARCHAR" property="password"/>
<result column="gmt_create" jdbcType="TIMESTAMP" property="gmtCreate"/>
<result column="gmt_modify" jdbcType="TIMESTAMP" property="gmtModify"/>
</resultMap>
<sql id="Base_Column_List">
id, user_name, `password`, gmt_create, gmt_modify
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from user
where id = #{id,jdbcType=INTEGER}
</select>
<select id="findByUserNameAndPassword" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from user where user_name=#{username} and password=#{password}
</select>
<select id="findUserList" resultType="java.util.Map">
select user_name username ,id from user
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete
from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.hs.admin.bean.User" useGeneratedKeys="true">
insert into user (user_name, `password`, gmt_create,
gmt_modify)
values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{gmtCreate,jdbcType=TIMESTAMP},
#{gmtModify,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.hs.admin.bean.User" useGeneratedKeys="true">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userName != null">
user_name,
</if>
<if test="password != null">
`password`,
</if>
<if test="gmtCreate != null">
gmt_create,
</if>
<if test="gmtModify != null">
gmt_modify,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="gmtCreate != null">
#{gmtCreate,jdbcType=TIMESTAMP},
</if>
<if test="gmtModify != null">
#{gmtModify,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.hs.admin.bean.User">
update user
<set>
<if test="userName != null">
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="password != null">
`password` = #{password,jdbcType=VARCHAR},
</if>
<if test="gmtCreate != null">
gmt_create = #{gmtCreate,jdbcType=TIMESTAMP},
</if>
<if test="gmtModify != null">
gmt_modify = #{gmtModify,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.hs.admin.bean.User">
update user
set user_name = #{userName,jdbcType=VARCHAR},
`password` = #{password,jdbcType=VARCHAR},
gmt_create = #{gmtCreate,jdbcType=TIMESTAMP},
gmt_modify = #{gmtModify,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file
package com.hs.admin;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AdminApplicationTests {
@Test
void contextLoads() {
}
}
package com.hs.admin;
import com.hs.admin.dto.UserDto;
import com.hs.admin.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserTest {
@Autowired
UserService userService;
@Test
public void save() {
UserDto dto = new UserDto();
dto.setUsername("admin");
dto.setPassword("123456");
userService.saveUser(dto);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment