搭建项目的框架

This commit is contained in:
DESKTOP-4U0TDEF\20371 2021-07-12 14:51:34 +08:00
commit 07498b55ad
71 changed files with 6296 additions and 0 deletions

33
.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
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/

118
.mvn/wrapper/MavenWrapperDownloader.java vendored Normal file
View File

@ -0,0 +1,118 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

2
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

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

310
mvnw vendored Normal file
View File

@ -0,0 +1,310 @@
#!/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 "$@"

182
mvnw.cmd vendored Normal file
View File

@ -0,0 +1,182 @@
@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%

183
pom.xml Normal file
View File

@ -0,0 +1,183 @@
<?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.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xkrs</groupId>
<artifactId>fire_point</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fire_point</name>
<description>火点项目</description>
<properties>
<yauaa.version>5.19</yauaa.version>
<jjwt.version>0.11.2</jjwt.version>
<httpmime.version>4.5.12</httpmime.version>
<hibernate-validator.version>6.1.5.Final</hibernate-validator.version>
<hibernate-spatial.version>5.4.20.Final</hibernate-spatial.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<fastjson.version>1.2.76</fastjson.version>
<springfox-swagger-ui.version>2.10.5</springfox-swagger-ui.version>
<springfox-swagger2.version>2.10.5</springfox-swagger2.version>
<poi.version>5.0.0</poi.version>
<poi-ooxml.version>5.0.0</poi-ooxml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId> mysql</groupId>
<artifactId> mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jjwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>nl.basjes.parse.useragent</groupId>
<artifactId>yauaa</artifactId>
<version>${yauaa.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpmime.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>${hibernate-spatial.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!--swagger的依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-swagger-ui.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger2.version}</version>
</dependency>
<!--excel依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi-ooxml.version}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.txt</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,13 @@
package com.xkrs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class FirePointApplication {
public static void main(String[] args) {
SpringApplication.run(FirePointApplication.class, args);
}
}

View File

@ -0,0 +1,36 @@
package com.xkrs.common.account;
/**
* 账户实体
* @author tajochen
*/
public class AccountCredentials {
private String userName;
private String password;
private boolean remember;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isRemember() {
return remember;
}
public void setRemember(boolean remember) {
this.remember = remember;
}
}

View File

@ -0,0 +1,113 @@
package com.xkrs.common.account;
import com.xkrs.model.entity.SysAuthorityEntity;
import com.xkrs.model.entity.SysUserEntity;
import com.xkrs.service.SysAuthorityService;
import com.xkrs.service.SysRoleService;
import com.xkrs.service.SysUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import static com.xkrs.utils.EncryptDecryptUtil.encry256;
/**
* 自定义认证Provider
* @author tajochen
*/
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Resource
private SysUserService sysUserService;
@Resource
private SysRoleService sysRoleService;
@Resource
private SysAuthorityService sysAuthorityService;
/**
* 初使化时将已静态化的Service实例化
*/
protected static CustomAuthenticationProvider customAuthenticationProvider;
/**
* 通过@PostConstruct实现初始化bean之前进行的操作
*/
@PostConstruct
public void init() {
customAuthenticationProvider = this;
customAuthenticationProvider.sysUserService = this.sysUserService;
customAuthenticationProvider.sysRoleService = this.sysRoleService;
customAuthenticationProvider.sysAuthorityService = this.sysAuthorityService;
}
/**
* 用户认证授权
* @param authentication
* @return
* @throws AuthenticationException
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// 获取认证的用户名 & 密码
String userName = authentication.getName();
String password = authentication.getCredentials().toString();
SysUserEntity userEntity = customAuthenticationProvider.sysUserService.getSysUserByUserName(userName);
// 检查用户是否存在
if(userEntity == null){
throw new BadCredentialsException("user don't exist");
}
// 检查用户是否激活
if(userEntity.getActiveFlag().intValue() != 0){
throw new DisabledException("user not activated");
}
//检查用户状态是否正常
if(userEntity.getStatusCode() != 0){
throw new DisabledException("user state exception");
}
// 认证逻辑
String encryptPassword = encry256(password + userEntity.getSalt());
if (encryptPassword.equals(userEntity.getPassword())) {
// 设置权限列表
ArrayList<GrantedAuthority> permissions = new ArrayList<>();
List<Integer> integers = customAuthenticationProvider.sysAuthorityService.selectAuthorityByUserId(userEntity.getId());
List<SysAuthorityEntity> permissionList = customAuthenticationProvider.sysAuthorityService.findAllByIdIn(integers);
for(SysAuthorityEntity sysAuthorityEntity : permissionList) {
permissions.add(new GrantedAuthorityImpl(sysAuthorityEntity.getAuthorityName()));
}
// 生成令牌
Authentication authToken = new UsernamePasswordAuthenticationToken(userName, encryptPassword, permissions);
return authToken;
}
else {
throw new BadCredentialsException("user password error");
}
}
/**
* 是否可以提供输入类型的认证服务
* @param authentication
* @return
*/
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

View File

@ -0,0 +1,25 @@
package com.xkrs.common.account;
import org.springframework.security.core.GrantedAuthority;
/**
* 权限认证服务
* @author tajochen
*/
public class GrantedAuthorityImpl implements GrantedAuthority {
private String authority;
public GrantedAuthorityImpl(String authority) {
this.authority = authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
@Override
public String getAuthority() {
return this.authority;
}
}

View File

@ -0,0 +1,28 @@
package com.xkrs.common.account;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 拦截所有需要JWT的请求然后调用TokenAuthenticationService类的静态方法去做JWT验证
* @author tajochen
*/
public class JwtAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest)request);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request,response);
}
}

View File

@ -0,0 +1,132 @@
package com.xkrs.common.account;
import com.xkrs.common.encapsulation.OutputEncapsulation;
import com.xkrs.common.encapsulation.PromptMessageEnum;
import com.xkrs.model.entity.SysUserEntity;
import com.xkrs.service.SysUserService;
import com.xkrs.utils.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
/**
* jwt登录过滤器
* @author tajochen
*/
public class JwtLoginFilter extends AbstractAuthenticationProcessingFilter {
private static final Logger logger = LoggerFactory.getLogger(JwtLoginFilter.class);
@Resource
private SysUserService sysUserService;
public JwtLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
/**
* 登录时验证
* @param req
* @param res
* @return
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws UnsupportedEncodingException {
req.setCharacterEncoding("UTF-8");
res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Credentials", "false");
AccountCredentials creds = new AccountCredentials();
//获取表单数据
String userName = req.getParameter("userName");
String password = req.getParameter("password");
String rememberMe = req.getParameter("remember");
//如果用户名密码为空
if(userName == null||password == null|| userName.trim().isEmpty()||password.trim().isEmpty()){
throw new BadCredentialsException("user or password is null");
}
if(rememberMe == null||rememberMe.isEmpty()){
rememberMe = "false";
}
creds.setUserName(userName.trim());
creds.setPassword(password.trim());
creds.setRemember(Boolean.parseBoolean(rememberMe));
// 返回一个验证令牌
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUserName(),
creds.getPassword()
)
);
}
/**
* 验证成功后调用
* @param req
* @param response
* @param chain
* @param auth
* @throws IOException
* @throws ServletException
*/
@Override
protected void successfulAuthentication(
HttpServletRequest req, HttpServletResponse response, FilterChain chain, Authentication auth) {
if(sysUserService==null){
ServletContext servletContext = req.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
sysUserService = webApplicationContext.getBean(SysUserService.class);
}
//更新用户登录信息
sysUserService.updateSysUserLogin(auth.getName(), IpUtil.getIpAddr(req));
SysUserEntity sysUserByUserName = sysUserService.getSysUserByUserName(auth.getName());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "false");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
TokenAuthenticationService.addAuthentication(response, auth.getName(),auth.getAuthorities(),sysUserByUserName);
}
/**
* 验证失败后调用
* @param request
* @param response
* @param failed
* @throws IOException
*/
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException failed) throws IOException {
Locale locale = LocaleContextHolder.getLocale();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "false");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// JWT 写入 body
PrintWriter out = response.getWriter();
out.append(OutputEncapsulation.outputEncapsulationObject(PromptMessageEnum.DATA_WRONG, failed.getLocalizedMessage(), locale));
response.setStatus(HttpServletResponse.SC_OK);
}
}

View File

@ -0,0 +1,129 @@
package com.xkrs.common.account;
import com.xkrs.common.encapsulation.OutputEncapsulation;
import com.xkrs.common.encapsulation.PromptMessageEnum;
import com.xkrs.model.entity.SysUserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
/**
* token认证服务
* @author tajochen
*/
public class TokenAuthenticationService {
private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationService.class);
/**
* 过期时间6小时
*/
static public final long EXPIRATIONTIME = 21_600_000;
/**
* 加密密钥
*/
static public final String SECRET_KEY = "0Y9H364Q9Y908262F25LMXGIKIN5N858XM3674GWL2DD8X1DS4W6I722IRY8PS4XPNB6U303" +
"45HBVCUL94STG8C3Z53T7A09JJ100I56YE9894CI11PX9J71HIZ8L5Y2O504C4E2K8276425UA8734833F45K36878FXAG799QV9LXU" +
"JOI3XA2046UPG8TB2OT84R5T6ZB127N9ZPJ7AJMC41JVHB2WK2B6H8NL45LZNAZ666KHZH3QUT65UX6F8";
/**
* Token前缀
*/
static public final String TOKEN_PREFIX = "Bearer";
/**
* 存放Token的Header Key
*/
static final String HEADER_STRING = "Authorization";
static SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
/**
* JWT生成方法
* @param response
* @param userName
* @param authorities
*/
static void addAuthentication(HttpServletResponse response, String userName,
Collection<? extends GrantedAuthority> authorities,SysUserEntity sysUserEntity) {
Locale locale = new Locale("zh", "CN");
Map map = new HashMap(3);
StringBuffer auths = new StringBuffer();
String authsList = "";
for(GrantedAuthority r : authorities) {
auths.append("," + r.getAuthority());
}
authsList = auths.toString();
if(authsList.length()>1){
authsList=authsList.substring(1,authsList.length());
}else{
logger.warn(userName +" has no permission!");
}
// 生成JWT
String jwt = Jwts.builder()
.setSubject(userName)
.setIssuer("https://www.microservice.com")
.setAudience(userName)
// 保存权限
.claim("auths", authsList)
// 有效期设置
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
// 签名设置
.signWith(key)
.compact();
map.put("token",jwt);
map.put("role",authsList);
map.put("user",sysUserEntity);
// JWT 写入 body
PrintWriter out = null;
try {
out = response.getWriter();
}
catch (IOException e) {
e.printStackTrace();
}
response.setStatus(HttpServletResponse.SC_OK);
out.append(OutputEncapsulation.outputEncapsulationObject(PromptMessageEnum.SUCCESS, map, locale));
}
/**
* JWT验证方法
* @param request
* @return
*/
static Authentication getAuthentication(HttpServletRequest request) {
// 从Header中拿到token
String token = request.getHeader(HEADER_STRING);
if (token != null) {
try {
// 解析 Token
Claims claims = Jwts.parserBuilder()
.setSigningKey(key).build()
// 去掉 Bearer
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody();
// 获取用户名
String userName = claims.getSubject();
// 获取权限
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("auths"));
return new UsernamePasswordAuthenticationToken(userName, null, authorities);
} catch(Exception e) {
// the sub field was missing or did not have a value
return null;
}
} else {
return null;
}
}
}

View File

@ -0,0 +1,23 @@
package com.xkrs.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* 系统跨域配置
* @author tajochen
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Resource
private CorsInterceptor corsInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(corsInterceptor);
}
}

View File

@ -0,0 +1,29 @@
package com.xkrs.common.config;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 跨域处理
* @author tajochen
*/
@Component
public class CorsInterceptor implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//添加跨域CORS
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "false");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type , Authorization," +
"Accept,Origin,X-Requested-With");
response.setHeader("Access-Control-Max-Age", "216000");
response.setHeader("Content-Type","application/json;charset=UTF-8");
return true;
}
}

View File

@ -0,0 +1,37 @@
package com.xkrs.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMVC配置
* @author Tajochen
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/**
* 放行跨域请求
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
/**
* 定时任务线程池更改防止多个任务并行
*/
@Bean
public TaskScheduler taskScheduler() {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5);
return scheduler;
}
}

View File

@ -0,0 +1,65 @@
package com.xkrs.common.config;
import com.xkrs.common.account.CustomAuthenticationProvider;
import com.xkrs.common.account.JwtAuthenticationFilter;
import com.xkrs.common.account.JwtLoginFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 设置 HTTP 验证规则
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 关闭csrf验证
http.csrf().disable()
// 对请求进行认证
.authorizeRequests()
// 所有 / 的所有请求 都放行
//.antMatchers("/").permitAll()
// 所有OPTIONS请求都放行
.antMatchers(HttpMethod.OPTIONS).permitAll()
// 所有 /user/add 用户注册 的POST请求 都放行
.antMatchers(HttpMethod.POST, "/api/user/add").permitAll()
// 所有 /user/check/duplicate 检查用户名是否重复 的POST请求 都放行
.antMatchers(HttpMethod.POST, "/api/user/check/duplicate").permitAll()
// 所有 /login 用户登录 的POST请求 都放行
.antMatchers(HttpMethod.POST, "/api/login").permitAll()
// 所有 app 用户注册 的POST请求 都放行
.antMatchers(HttpMethod.POST, "/api/person-investigator/add").permitAll()
.antMatchers(HttpMethod.GET,"/api/user/booleanUserName").permitAll()
.antMatchers(HttpMethod.POST,"/importRsProjectExcel").permitAll()
.antMatchers(HttpMethod.POST,"/importCvProjectExcel").permitAll()
.antMatchers(HttpMethod.GET,"/excelOutWork").permitAll()
.antMatchers(HttpMethod.GET,"/selectMemberAndWorkHour").permitAll()
// 所有其它请求需要身份认证
.anyRequest().authenticated()
.and()
// 添加一个过滤器 所有访问 /login 的请求交给 JWTLoginFilter 来处理 这个类处理所有的JWT相关内容
.addFilterBefore(new JwtLoginFilter("/api/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class)
// 添加一个过滤器验证其他请求的Token是否合法
.addFilterBefore(new JwtAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
;}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 使用自定义身份验证组件
auth.authenticationProvider(new CustomAuthenticationProvider());
}
}

View File

@ -0,0 +1,59 @@
package com.xkrs.common.encapsulation;
import java.io.Serializable;
/**
* 输出信息对象
* @author tajochen
* @param <T>
*/
public class EncapsulationObejct<T> implements Serializable {
/**
* 状态码
*/
int status;
/**
* 提示信息
*/
String msg;
/**
* 数据
*/
T data;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "EncapsulationObejct{" +
"status=" + status +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}

View File

@ -0,0 +1,96 @@
package com.xkrs.common.encapsulation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
/**
* 输出信息封装
* @author tajochen
*/
@Component
public class OutputEncapsulation {
private static final Logger logger = LoggerFactory.getLogger(OutputEncapsulation.class);
/**
* 读取多国语言文件
* @return
*/
public static MessageSource messageSource() {
Properties properties = new Properties();
// 使用ClassLoader加载properties配置文件生成对应的输入流
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
// 使用properties对象加载输入流
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
/**
* 封装输出数据
* @param promptMessageEnum
* @param obj
* @return
*/
public static String outputEncapsulationObject(PromptMessageEnum promptMessageEnum, Object obj, Locale locale) {
EncapsulationObejct encapsulationObejct = new EncapsulationObejct();
encapsulationObejct.setStatus(promptMessageEnum.getCode());
encapsulationObejct.setMsg(messageSource().getMessage(promptMessageEnum.getText(),null,locale));
encapsulationObejct.setData(obj);
ObjectMapper objectMapper = new ObjectMapper();
// 忽略无法转换的对象
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
// 忽略json字符串中不识别的属性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 解决jackson无法反序列化LocalDateTime的问题,引入jsr310标准
JavaTimeModule javaTimeModule = new JavaTimeModule();
objectMapper.registerModule(javaTimeModule);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String strByEo = "";
try {
strByEo = objectMapper.writeValueAsString(encapsulationObejct);
} catch (JsonProcessingException e) {
e.printStackTrace();
logger.warn(e.toString());
}
return strByEo;
}
/**
* 输出请求值检验错误信息
* @param fieldErrors
* @return
*/
public static String outputEncapsulationErrorList(List<FieldError> fieldErrors, Locale locale){
List<String> errorMsg = new ArrayList<>();
for (FieldError fieldError : fieldErrors) {
String errMessage = fieldError.getDefaultMessage().subSequence(1,fieldError.getDefaultMessage().length()-1).toString();
errorMsg.add(messageSource().getMessage(errMessage,null,locale));
}
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,errorMsg,locale);
}
}

View File

@ -0,0 +1,64 @@
package com.xkrs.common.encapsulation;
/**
* 提示信息枚举
* @author tajochen
*/
public enum PromptMessageEnum{
// 执行成功
SUCCESS(0, "sys.message.success"),
// 用户权限错误或非法操作 1001-1999
USER_NOT_LOGGED(1001, "sys.message.user.not_logged_in"),
USER_LOGIN_ERROR(1002, "sys.message.user.login_error"),
USER_ACCOUNT_FORBIDDEN(1003, "sys.message.user.account_forbidden"),
USER_ACCOUNT_NOT_ACTIVATED(1004, "sys.message.user.account_not_activated"),
USER_HAS_OVERTIME(1005, "sys.message.user.overtime"),
USER_NO_PERMISSION(1006,"sys.message.user.no_permission"),
USER_ALREADY_LOGGED(1007, "sys.message.user.already_logged"),
// 请求参数错误或非法2001-2999
PARAM_NULL(2001, "sys.message.param.null"),
PARAM_ILLEGAL(2002, "sys.message.param.illegal"),
// 数据返回错误3001-3999
DATA_NONE(3001, "sys.message.data.none"),
DATA_WRONG(3002, "sys.message.data.wrong"),
DATA_EXIT(3003,"sys.message.exit"),
// 操作失败4001-4999
PROCESS_FAIL(4001,"sys.message.process.fail"),
PROCESS_OVERTIME(4002,"sys.message.process.overtime"),
FILE_EXISTS(4003,"sys.message.file.exists"),
FILE_WRITE_ERROR(4004,"sys.message.file.write.error"),
FILE_READ_ERROR(4005,"sys.message.file.read.error"),
// 系统内部错误或异常5001-5999
SYSTEM_INNER_ERROR(5001,"sys.message.system.inner_error"),
SYSTEM_ABNORMAL(5002,"sys.message.system.abnormal"),
SYSTEM_BUSY(5003,"sys.message.system.busy"),
SYSTEM_MAINTAIN(5004,"sys.message.system.maintain"),
// 数据库错误6001-6999
DATABASE_ERROR(6001,"sys.message.database.error");
private int code;
private String text;
private PromptMessageEnum(int code,String text) {
this.code = code;
this.text = text;
}
public String getText() {
return this.text;
}
public int getCode() {
return this.code;
}
}

View File

@ -0,0 +1,33 @@
package com.xkrs.common.tool;
/**
* CompareVersion 比较版本号
* @author tajochen
*/
public class CompareVersion {
/**
* 比较三位版本号 版本1>版本2 返回 1若版本1<版本2 返回 -1否则返回0
* @param version1 版本1
* @param version2 版本2
* @return
*/
public static int compareVersion(String version1, String version2) {
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
int n = Math.max(v1.length, v2.length);
for (int i = 0; i < n; i++) {
int v1Int = i < v1.length ? Integer.parseInt(v1[i]) : 0;
int v2Int = i < v2.length ? Integer.parseInt(v2[i]) : 0;
if (v1Int == v2Int) {
continue;
}
if (v1Int > v2Int){
return 1;
} else {
return -1;
}
}
return 0;
}
}

View File

@ -0,0 +1,98 @@
package com.xkrs.common.tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* dao接口类处理工具
* @author tajochen
*/
public class EntityUtil {
private static final Logger logger = LoggerFactory.getLogger(EntityUtil.class);
/**
* 将数组数据转换为实体类
* 此处数组元素的顺序必须与实体类构造函数中的属性顺序一致
* @param list 数组对象集合
* @param clazz 实体类
* @param <T> 实体类
* @param model 实例化的实体类
* @return 实体类集合
*/
public static <T> List<T> castEntity(List<Object[]> list, Class<T> clazz, Object model) {
List<T> returnList = new ArrayList<T>();
if (list.isEmpty()) {
return returnList;
}
//获取每个数组集合的元素个数
Object[] co = list.get(0);
//获取当前实体类的属性名属性值属性类别
List<Map> attributeInfoList = getFiledsInfo(model);
//创建属性类别数组
Class[] c2 = new Class[attributeInfoList.size()];
//如果数组集合元素个数与实体类属性个数不一致则发生错误
if (attributeInfoList.size() != co.length) {
return returnList;
}
//确定构造方法
for (int i = 0; i < attributeInfoList.size(); i++) {
c2[i] = (Class) attributeInfoList.get(i).get("type");
}
try {
for (Object[] o : list) {
Constructor<T> constructor = clazz.getConstructor(c2);
returnList.add(constructor.newInstance(o));
}
} catch (Exception ex) {
logger.error("实体数据转化为实体类发生异常:异常信息:{}", ex.getMessage());
return returnList;
}
return returnList;
}
/**
* 根据属性名获取属性值
* @param fieldName 属性名
* @param modle 实体类
* @return 属性值
*/
private static Object getFieldValueByName(String fieldName, Object modle) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = modle.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(modle, new Object[]{});
return value;
} catch (Exception e) {
return null;
}
}
/**
* 获取属性类型(type)属性名(name)属性值(value)的map组成的list
* @param model 实体类
* @return list集合
*/
private static List<Map> getFiledsInfo(Object model) {
Field[] fields = model.getClass().getDeclaredFields();
List<Map> list = new ArrayList(fields.length);
Map infoMap = null;
for (int i = 0; i < fields.length; i++) {
infoMap = new HashMap(3);
infoMap.put("type", fields[i].getType());
infoMap.put("name", fields[i].getName());
infoMap.put("value", getFieldValueByName(fields[i].getName(), model));
list.add(infoMap);
}
return list;
}
}

View File

@ -0,0 +1,51 @@
package com.xkrs.common.tool;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import javax.crypto.SecretKey;
import java.util.List;
/**
* token工具
* @author tajochen
*/
public class TokenUtil {
/**
* Token前缀
*/
static public final String TOKEN_PREFIX = "Bearer";
static public final String SECRETKEY = "0Y9H364Q9Y908262F25LMXGIKIN5N858XM3674GWL2DD8X1DS4W6I722IRY8PS4XPNB6U30345" +
"HBVCUL94STG8C3Z53T7A09JJ100I56YE9894CI11PX9J71HIZ8L5Y2O504C4E2K8276425UA8734833F45K36878FXAG799QV9LXUJ" +
"OI3XA2046UPG8TB2OT84R5T6ZB127N9ZPJ7AJMC41JVHB2WK2B6H8NL45LZNAZ666KHZH3QUT65UX6F8";
static SecretKey key = Keys.hmacShaKeyFor(SECRETKEY.getBytes());
public static String getTokenUserName(String token) {
String userName = "";
if (token != null) {
try {
// 解析 Token
Claims claims = Jwts.parserBuilder()
.setSigningKey(key).build()
// 去掉 Bearer
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody();
// 获取用户名
userName = claims.getSubject();
// 获取权限
List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("auths"));
} catch(Exception e) {
// the sub field was missing or did not have a 'jsmith' value
return null;
}
} else {
return null;
}
return userName;
}
}

View File

@ -0,0 +1,243 @@
package com.xkrs.controller;
import com.xkrs.common.encapsulation.PromptMessageEnum;
import com.xkrs.common.tool.TokenUtil;
import com.xkrs.dao.SysUserDao;
import com.xkrs.model.entity.SysUserEntity;
import com.xkrs.model.qo.SysUserQo;
import com.xkrs.model.validation.SysUserQoInsert;
import com.xkrs.model.validation.SysUserQoUpdate;
import com.xkrs.model.vo.SysUserVo;
import com.xkrs.service.SysUserService;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationErrorList;
import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
/**
* 系统用户Controller
* @author tajocehn
*/
@RestController
@RequestMapping(value = "/api/user")
public class SysUserController {
@Resource
private SysUserService sysUserService;
@Resource
private SysUserDao sysUserDao;
/**
* 登录用户Token验证
* @return
*/
@RequestMapping(value = "/logged/check",method = RequestMethod.POST)
public String loginUserTokenCheck(){
Locale locale = LocaleContextHolder.getLocale();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
@RequestMapping(value = "/check/duplicate", method = RequestMethod.POST)
public String checkDuplicate(@RequestParam(value="userName", required=false) String userName){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
// 验证用户名是否重复
if(!sysUserService.checkUserName(userName)){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"",locale);
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"OK",locale);
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(@Validated({SysUserQoInsert.class}) @RequestBody SysUserQo userQo,
BindingResult bindingResult){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 验证用户名是否重复
if(!sysUserService.checkUserName(userQo.getUserName())){
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,"该账号已经注册,请勿重复注册",locale);
}
// 添加新用户
sysUserService.addUser(userQo);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"OK",locale);
}
/*@RequestMapping(value="/get/all", method = RequestMethod.GET)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
public String getAllSysUser(){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
Iterable<SysUserVo> sysUserDtoList = sysUserService.getAllSysUser();
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,sysUserDtoList,locale);
}*/
/**
* 软删除指定id的普通用户
* @param id
* @return
*/
@RequestMapping(value = "/general/delete", method = RequestMethod.DELETE)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_general_user')")
public String deleteCustomUser(@RequestParam(value="userId", required=false) int id){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
// 验证数据合法性
int res = sysUserService.softDeleteGeneralUser(id);
if(res==1){
return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"",locale);
} else {
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"",locale);
}
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
@PreAuthorize("hasAnyAuthority('auth_system_manager','auth_administor')")
public String updateUser(@Validated({SysUserQoUpdate.class}) @RequestBody SysUserQo userQo,
BindingResult bindingResult){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
// 验证数据合法性
if(bindingResult.hasErrors()){
return outputEncapsulationErrorList(bindingResult.getFieldErrors(),locale);
}
// 修改用户
sysUserService.updateSysUser(userQo);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"OK",locale);
}
/**
* 判断用户名是否存在
* @param userName
* @return
*/
@GetMapping("/booleanUserName")
public String booleanUserName(@RequestParam("userName") String userName){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
Map map = new HashMap(3);
SysUserEntity sysUserEntity = sysUserDao.selectByUserName(userName);
if(sysUserEntity == null){
map.put("status",0);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,map,locale);
}else {
map.put("status",1);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,map,locale);
}
}
/**
* 查看用户信息
* @return
*/
@GetMapping("/selectAllUser")
@PreAuthorize("hasAnyAuthority('auth_administor')")
public String selectAllUser(@RequestHeader(value="Authorization") String token){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
// 验证token
String tokenUserName = TokenUtil.getTokenUserName(token);
SysUserEntity sysUserEntity = sysUserDao.selectByUserName(tokenUserName);
if(sysUserEntity == null){
return outputEncapsulationObject(PromptMessageEnum.USER_LOGIN_ERROR,"您还没有注册登录,请先注册登录",locale);
}
List<SysUserVo> sysUserVos = sysUserService.selectAllUser();
if(sysUserVos == null || sysUserVos.size() == 0){
return outputEncapsulationObject(PromptMessageEnum.DATA_NONE,"暂时还没有任何用户数据",locale);
}
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,sysUserVos,locale);
}
/**
* 管理员进行启用禁用的操作
* @param map
* @param token
* @return
*/
@PostMapping("/operateActiveFlag")
@PreAuthorize("hasAnyAuthority('auth_administor')")
public String operateActiveFlag(@RequestBody Map map,@RequestHeader(value="Authorization") String token){
Integer userId = (Integer) map.get("userId");
String keepType = (String) map.get("keepType");
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
// 验证token
String tokenUserName = TokenUtil.getTokenUserName(token);
SysUserEntity sysUserEntity = sysUserDao.selectByUserName(tokenUserName);
if(sysUserEntity == null){
return outputEncapsulationObject(PromptMessageEnum.USER_LOGIN_ERROR,"您还没有注册登录,请先注册登录",locale);
}
// 如果keepType等于1进行启用操作
if("1".equals(keepType)){
sysUserService.updateEnable(userId);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"启用成功",locale);
}else {
sysUserService.updateDisable(userId);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"禁用成功",locale);
}
}
/**
* 用户修改密码
* @param map
* @param token
* @return
*/
@PostMapping("/updatePassword")
@PreAuthorize("hasAnyAuthority('auth_administor','auth_general_user')")
public String updatePassword(@RequestBody Map map,@RequestHeader(value="Authorization") String token){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
String oldPassword = (String) map.get("oldPassword");
String newPassword = (String) map.get("newPassword");
String confirmPassword = (String) map.get("confirmPassword");
// 验证token
String tokenUserName = TokenUtil.getTokenUserName(token);
SysUserEntity sysUserEntity = sysUserDao.selectByUserName(tokenUserName);
if(sysUserEntity == null){
return outputEncapsulationObject(PromptMessageEnum.USER_LOGIN_ERROR,"您还没有注册登录,请先注册登录",locale);
}
return sysUserService.updatePassword(oldPassword,newPassword,confirmPassword,sysUserEntity);
}
/**
* 管理员修改用户的密码
* @param map
* @param token
* @return
*/
@PostMapping("/adminUpdatePassword")
@PreAuthorize("hasAnyAuthority('auth_administor')")
public String adminUpdatePassword(@RequestBody Map map,@RequestHeader(value="Authorization") String token){
// 获取区域信息
Locale locale = LocaleContextHolder.getLocale();
// 要修改的用户的id
Integer userId = (Integer) map.get("userId");
String newPassword = (String) map.get("newPassword");
String confirmPassword = (String) map.get("confirmPassword");
// 验证token
String tokenUserName = TokenUtil.getTokenUserName(token);
SysUserEntity sysUserEntity = sysUserDao.selectByUserName(tokenUserName);
if(sysUserEntity == null){
return outputEncapsulationObject(PromptMessageEnum.USER_LOGIN_ERROR,"您还没有注册登录,请先注册登录",locale);
}
return sysUserService.adminUpdatePassword(userId,newPassword,confirmPassword);
}
}

View File

@ -0,0 +1,22 @@
package com.xkrs.dao;
import com.xkrs.model.entity.RelRoleAuthorityEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @author XinYi Song
*/
public interface RelRoleAuthorityDao extends JpaRepository<RelRoleAuthorityEntity,Long> {
/**
* 根据userId查询出权限的id
* @param userId
* @return
*/
@Query(value = "select authority_id from rel_role_authority where user_id = ?",nativeQuery = true)
List<Integer> selectAuthorityByUserId(@Param("userId") Integer userId);
}

View File

@ -0,0 +1,10 @@
package com.xkrs.dao;
import com.xkrs.model.entity.RelUserRoleEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author XinYi Song
*/
public interface RelUserRoleDao extends JpaRepository<RelUserRoleEntity,Long> {
}

View File

@ -0,0 +1,32 @@
package com.xkrs.dao;
import com.xkrs.model.entity.SysAuthorityEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* SysAuthorityDao
* @author tajochen
*/
public interface SysAuthorityDao extends JpaRepository<SysAuthorityEntity,Integer> {
/**
* 查询权限实体列表根据用户名 Object[]
* @param userName 用户名
* @return 用户实体
*/
@Query(value = "SELECT a.id, a.authority_name, a.authority_name_zh, a.authority_desc " +
"FROM sys_authority a,rel_role_authority ra,sys_role r WHERE r.id = ra.role_id AND ra.authority_id = a.id AND r.id " +
"IN (SELECT r.id FROM sys_user u,sys_role r,rel_user_role ur " +
" WHERE u.user_name = :userName AND u.id = ur.user_id AND ur.role_id = r.id)", nativeQuery = true)
List<SysAuthorityEntity> selectByUserName(@Param("userName") String userName);
/**
* 根据id批量查询权限信息
* @param id
* @return
*/
List<SysAuthorityEntity> findAllByIdIn(List<Integer> id);
}

View File

@ -0,0 +1,60 @@
package com.xkrs.dao;
import com.xkrs.model.entity.SysRoleEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* SysRoleDao
* @author tajochen
*/
public interface SysRoleDao extends JpaRepository<SysRoleEntity,Integer> {
/**
* 查询用户角色列表根据用户id
* @param id
* @return
*/
@Query(value = "SELECT sys_role.id,sys_role.role_name,sys_role.role_name_zh,sys_role.role_desc " +
"FROM sys_role,rel_user_role " +
"WHERE sys_role.id = rel_user_role.role_id " +
"AND rel_user_role.user_id = :id ", nativeQuery = true)
List<SysRoleEntity> selectByUserId(@Param("id") Integer id);
/**
* 查询用户角色列表根据用户名
* @param userName
* @return
*/
@Query(value = "SELECT sys_role.id,sys_role.role_name,sys_role.role_name_zh,sys_role.role_desc " +
"FROM sys_role.ID = rel_user_role.role_id " +
"WHERE rel_user_role.user_id = sys_user.id " +
"AND rel_user_role.user_id = sys_user.id " +
"AND sys_user.user_name = :userName ", nativeQuery = true)
List<SysRoleEntity> selectByUserName(@Param("userName") String userName);
// /**
// * 根据用户名修改用户角色
// */
// @Modifying
// @Query(value = "UPDATE sys_user SET last_entry_time = now(), last_entry_ip = :ipAddress " +
// "WHERE user_name = :userName ;", nativeQuery = true)
// int updateUserRoleByUserName(@Param("userName") String userName);
/**
* 添加用户角色根据用户名和角色名
* @param userName
* @param roleName
* @return
*/
@Modifying
@Query(value = "INSERT INTO rel_user_role (id,role_id, user_id) " +
"SELECT nextval('rel_user_role_seq'),sys_role.ID,sys_user.ID FROM sys_role,sys_user " +
"WHERE sys_role.role_name = :roleName AND sys_user.user_name = :userName ", nativeQuery = true)
int insertRelUserRole(@Param("userName") String userName, @Param("roleName") String roleName);
}

View File

@ -0,0 +1,121 @@
package com.xkrs.dao;
import com.xkrs.model.entity.SysUserEntity;
import com.xkrs.model.vo.SysUserVo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* SysUserDao
* @author tajochen
*/
public interface SysUserDao extends JpaRepository<SysUserEntity,Integer> {
/**
* 检查系统用户名是否存在
* @param userName
* @return
*/
@Query(value = "SELECT COUNT(*) FROM sys_user WHERE user_name = :userName", nativeQuery = true)
int checkUserName(@Param("userName") String userName);
/**
* 查找用户实体根据用户名
* @param userName
* @return
*/
@Query(value = "SELECT * FROM sys_user WHERE user_name = :userName", nativeQuery = true)
SysUserEntity selectByUserName(@Param("userName") String userName);
/**
* 根据用户名查询用户信息
* @param userName
* @return
*/
SysUserEntity findByUserName(String userName);
/**
* 更新用户登录信息
* @param userName
* @param ipAddress
* @return
*/
@Modifying
@Query(value = "UPDATE sys_user SET last_entry_time = now(), last_entry_ip = :ipAddress " +
"WHERE user_name = :userName ;", nativeQuery = true)
int updateSysUserLogin(@Param("userName") String userName, @Param("ipAddress") String ipAddress);
/**
* 软删除系统用户根据用户名
* @param userName
* @return
*/
@Modifying
@Query(value = "UPDATE sys_user SET delete_flag = 1 " +
"WHERE user_name = :userName ;", nativeQuery = true)
int softDeleteSysUserByUserName(@Param("userName") String userName);
/**
* 软删除系统用户根据id
* @param id
* @return
*/
@Modifying
@Query(value = "UPDATE sys_user SET delete_flag = 1 " +
"WHERE id = :id ;", nativeQuery = true)
int softDeleteGeneralUserById(@Param("id") Integer id);
/**
* 删除系统用户危险操作
* @param userName
* @return
*/
@Modifying
@Query(value = "DELETE FROM sys_user WHERE user_name = :userName ;", nativeQuery = true)
int deleteSysUser(@Param("userName") String userName);
/**
* 查询用户信息
* @return
*/
@Query(value = "select new com.xkrs.model.vo.SysUserVo (id,reallyName,telephone,userDepartment,activeFlag,addTime) " +
"from SysUserEntity")
List<SysUserVo> selectAll();
/**
* 启用
* @param userId
*/
@Query(value = "update sys_user set active_flag = 0 where id = ?",nativeQuery = true)
@Modifying(clearAutomatically=true)
void updateEnable(Integer userId);
/**
* 禁用
* @param userId
*/
@Query(value = "update sys_user set active_flag = 1 where id = ?",nativeQuery = true)
@Modifying(clearAutomatically=true)
void updateDisable(Integer userId);
/**
* 用户修改密码
* @param userId
* @param newPassword
*/
@Query(value = "update sys_user set password = ?2 where id = ?1",nativeQuery = true)
@Modifying(clearAutomatically=true)
void updatePassword(Integer userId,String newPassword);
/**
* 根据id查询用户的信息
* @param userId
* @return
*/
@Query(value = "select * from sys_user where id = ?",nativeQuery = true)
SysUserEntity selectByUserId(Integer userId);
}

View File

@ -0,0 +1,71 @@
package com.xkrs.model.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* RelRoleAuthority 表实体类
* @author tajochen
*/
@Entity
@Table(name="rel_role_authority")
public class RelRoleAuthorityEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "rel_role_authority_seq_gen")
@SequenceGenerator(name = "rel_role_authority_seq_gen", sequenceName = "rel_role_authority_id_seq",allocationSize = 1)
private Integer id;
@Column(nullable = false)
private Integer roleId;
@Column(nullable = false)
private Integer authorityId;
private Integer userId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Integer getAuthorityId() {
return authorityId;
}
public void setAuthorityId(Integer authorityId) {
this.authorityId = authorityId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Override
public String toString() {
return "RelRoleAuthorityEntity{" +
"id=" + id +
", roleId=" + roleId +
", authorityId=" + authorityId +
", userId=" + userId +
'}';
}
}

View File

@ -0,0 +1,60 @@
package com.xkrs.model.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* RelUserRole 表实体类
* @author tajochen
*/
@Entity
@Table(name="rel_user_role")
public class RelUserRoleEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "rel_user_role_seq_gen")
@SequenceGenerator(name = "rel_user_role_seq_gen", sequenceName = "rel_user_role_id_seq",allocationSize = 1)
private Integer id;
@Column(nullable = false)
private Long userId;
@Column(nullable = false)
private Integer roleId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "RelUserRoleEntity{" +
"id=" + id +
", userId=" + userId +
", roleId=" + roleId +
'}';
}
}

View File

@ -0,0 +1,72 @@
package com.xkrs.model.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* SysAuthority 表实体类
* @author tajochen
*/
@Entity
@Table(name="sys_authority")
public class SysAuthorityEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sys_authority_seq_gen")
@SequenceGenerator(name = "sys_authority_seq_gen", sequenceName = "sys_authority_id_seq",allocationSize = 1)
private Integer id;
@Column(length = 64, nullable = false, unique = true,columnDefinition = "varchar(64)")
private String authorityName;
@Column(length = 64, columnDefinition = "varchar(64)")
private String authorityNameZh;
@Column(length = 128, columnDefinition = "varchar(128)")
private String authorityDesc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthorityName() {
return authorityName;
}
public void setAuthorityName(String authorityName) {
this.authorityName = authorityName == null ? null : authorityName.trim();
}
public String getAuthorityNameZh() {
return authorityNameZh;
}
public void setAuthorityNameZh(String authorityNameZh) {
this.authorityNameZh = authorityNameZh == null ? null : authorityNameZh.trim();
}
public String getAuthorityDesc() {
return authorityDesc;
}
public void setAuthorityDesc(String authorityDesc) {
this.authorityDesc = authorityDesc == null ? null : authorityDesc.trim();
}
@Override
public String toString() {
return "SysAuthorityEntity{" +
"id=" + id +
", authorityName='" + authorityName + '\'' +
", authorityDesc='" + authorityDesc + '\'' +
", authorityNameZh='" + authorityNameZh + '\'' +
'}';
}
}

View File

@ -0,0 +1,72 @@
package com.xkrs.model.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* SysRole 表实体类
* @author tajochen
*/
@Entity
@Table(name="sys_role")
public class SysRoleEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sys_role_seq_gen")
@SequenceGenerator(name = "sys_role_seq_gen", sequenceName = "sys_role_id_seq",allocationSize = 1)
private Integer id;
@Column(length = 32, nullable = false, unique = true,columnDefinition = "varchar(32)")
private String roleName;
@Column(length = 32, columnDefinition = "varchar(32)")
private String roleNameZh;
@Column(length = 64, columnDefinition = "varchar(64)")
private String roleDesc;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName == null ? null : roleName.trim();
}
public String getRoleDesc() {
return roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc == null ? null : roleDesc.trim();
}
public String getRoleNameZh() {
return roleNameZh;
}
public void setRoleNameZh(String roleNameZh) {
this.roleNameZh = roleNameZh == null ? null : roleNameZh.trim();
}
@Override
public String toString() {
return "SysRoleEntity{" +
"id=" + id +
", roleName='" + roleName + '\'' +
", roleNameZh='" + roleNameZh + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}

View File

@ -0,0 +1,205 @@
package com.xkrs.model.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* SysUser 表实体类
* @author tajochen
*/
@Entity
@Table(name="sys_user")
public class SysUserEntity implements Serializable {
/**
* 指定主键建立自增序列主键值取自序列
*/
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sys_user_seq_gen")
@SequenceGenerator(name = "sys_user_seq_gen", sequenceName = "sys_user_id_seq",allocationSize = 1)
private Integer id;
/**
* 用户名
*/
@Column(length = 16, nullable = false, unique = true, columnDefinition = "varchar(16)")
private String userName;
/**
* 用户真实姓名
*/
@Column(length = 32, columnDefinition = "varchar(32)")
private String reallyName;
/**
* 密码
*/
@Column(length = 64, nullable = false, columnDefinition = "varchar(64)")
private String password;
@Column(length = 32, nullable = false, columnDefinition = "varchar(32)")
private String salt;
@Column(length = 16, unique = true, columnDefinition = "varchar(16)")
private String telephone;
/**
* 所在部门
*/
@Column(length = 32, columnDefinition = "varchar(32)")
private String userDepartment;
@Column(columnDefinition = "varchar(192)")
private String signature;
@Column(nullable = false)
private Integer activeFlag;
@Column(nullable = false,columnDefinition = "smallint")
private Integer statusCode;
@Column(nullable = false)
private LocalDateTime addTime;
private LocalDateTime lastEntryTime;
@Column(nullable = false)
private Integer deleteFlag;
@Column(columnDefinition = "varchar(64)")
private String lastEntryIp;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getReallyName() {
return reallyName;
}
public void setReallyName(String reallyName) {
this.reallyName = reallyName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getUserDepartment() {
return userDepartment;
}
public void setUserDepartment(String userDepartment) {
this.userDepartment = userDepartment;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public Integer getActiveFlag() {
return activeFlag;
}
public void setActiveFlag(Integer activeFlag) {
this.activeFlag = activeFlag;
}
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
public LocalDateTime getLastEntryTime() {
return lastEntryTime;
}
public void setLastEntryTime(LocalDateTime lastEntryTime) {
this.lastEntryTime = lastEntryTime;
}
public Integer getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(Integer deleteFlag) {
this.deleteFlag = deleteFlag;
}
public String getLastEntryIp() {
return lastEntryIp;
}
public void setLastEntryIp(String lastEntryIp) {
this.lastEntryIp = lastEntryIp;
}
@Override
public String toString() {
return "SysUserEntity{" +
"id=" + id +
", userName='" + userName + '\'' +
", reallyName='" + reallyName + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", telephone='" + telephone + '\'' +
", userDepartment='" + userDepartment + '\'' +
", signature='" + signature + '\'' +
", activeFlag=" + activeFlag +
", statusCode=" + statusCode +
", addTime=" + addTime +
", lastEntryTime=" + lastEntryTime +
", deleteFlag=" + deleteFlag +
", lastEntryIp='" + lastEntryIp + '\'' +
'}';
}
}

View File

@ -0,0 +1,138 @@
package com.xkrs.model.qo;
import com.xkrs.model.validation.SysUserQoInsert;
import com.xkrs.model.validation.SysUserQoUpdate;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
/**
* SysUserQo
* @author tajochen
*/
public class SysUserQo {
@NotNull( message = "{SysUser.id.blank}",groups={SysUserQoUpdate.class})
private Integer id;
@NotBlank(message = "{SysUser.userName.blank}",groups={SysUserQoInsert.class})
@Size(min = 4,max = 16, message = "{SysUser.userName.length.illegal}",groups = {SysUserQoInsert.class,
SysUserQoUpdate.class})
/**
* regexp = "^([A-Za-z0-9_]+)$"
*/
@Pattern(regexp = "^(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\\d{8}$",message = "{SysUser.userName.format.illegal}",groups = {SysUserQoInsert.class,
SysUserQoUpdate.class})
private String userName;
@Size(max = 32, message = "{SysUser.nickName.length.illegal}",groups = {SysUserQoInsert.class,
SysUserQoUpdate.class})
private String reallyName;
@NotBlank(message = "{SysUser.password.blank}",groups = {SysUserQoInsert.class})
@Size(min = 6,max = 16, message = "{SysUser.password.length.illegal}",groups = {SysUserQoInsert.class,
SysUserQoUpdate.class})
@Pattern(regexp = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$",message = "{SysUser.password.format.illegal}",
groups = {SysUserQoInsert.class,SysUserQoUpdate.class})
private String password;
@Pattern(regexp = "^(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\\d{8}$",
message = "{SysUser.telephone.format.illegal}",groups = {SysUserQoInsert.class,SysUserQoUpdate.class})
private String telephone;
@NotNull(message = "{SysUser.statusCode.illegal}",groups={SysUserQoUpdate.class})
@Range(min=0,max=2,message = "{SysUser.statusCode.illegal}",groups = {SysUserQoInsert.class, SysUserQoUpdate.class})
private Integer statusCode;
private String userDepartment;
@NotNull(message = "{SysUser.deleteFlag.null}",groups={SysUserQoUpdate.class})
private Integer deleteFlag;
private Integer roleId;
private Integer authorityId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getReallyName() {
return reallyName;
}
public void setReallyName(String reallyName) {
this.reallyName = reallyName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public String getUserDepartment() {
return userDepartment;
}
public void setUserDepartment(String userDepartment) {
this.userDepartment = userDepartment;
}
public Integer getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(Integer deleteFlag) {
this.deleteFlag = deleteFlag;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Integer getAuthorityId() {
return authorityId;
}
public void setAuthorityId(Integer authorityId) {
this.authorityId = authorityId;
}
}

View File

@ -0,0 +1,8 @@
package com.xkrs.model.validation;
/**
* SysUserQoInsert
* @author tajochen
*/
public interface SysUserQoInsert {
}

View File

@ -0,0 +1,8 @@
package com.xkrs.model.validation;
/**
* SysUserQoUpdate
* @author tajochen
*/
public interface SysUserQoUpdate {
}

View File

@ -0,0 +1,67 @@
package com.xkrs.model.vo;
import java.io.Serializable;
/**
* FileServerResultVo 文件服务器查询结果
* @author tajochen
*/
public class FileServerResultVo<T> implements Serializable {
/**
* 状态信息
*/
String status;
/**
* 提示信息
*/
String message;
/**
* 数据
*/
T data;
public FileServerResultVo() {
}
public FileServerResultVo(String status, String msg, T data) {
this.status = status;
this.message = msg;
this.data = data;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "FileServerResultVo{" +
"status='" + status + '\'' +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}

View File

@ -0,0 +1,92 @@
package com.xkrs.model.vo;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* SysUserVo
* @Author tajochen
*/
public class SysUserVo implements Serializable {
private Integer id;
private String reallyName;
private String telephone;
private String userDepartment;
private Integer activeFlag;
private LocalDateTime addTime;
public SysUserVo(Integer id, String reallyName, String telephone, String userDepartment, Integer activeFlag, LocalDateTime addTime) {
this.id = id;
this.reallyName = reallyName;
this.telephone = telephone;
this.userDepartment = userDepartment;
this.activeFlag = activeFlag;
this.addTime = addTime;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getReallyName() {
return reallyName;
}
public void setReallyName(String reallyName) {
this.reallyName = reallyName;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getUserDepartment() {
return userDepartment;
}
public void setUserDepartment(String userDepartment) {
this.userDepartment = userDepartment;
}
public Integer getActiveFlag() {
return activeFlag;
}
public void setActiveFlag(Integer activeFlag) {
this.activeFlag = activeFlag;
}
public LocalDateTime getAddTime() {
return addTime;
}
public void setAddTime(LocalDateTime addTime) {
this.addTime = addTime;
}
@Override
public String toString() {
return "SysUserVo{" +
"id=" + id +
", reallyName='" + reallyName + '\'' +
", telephone='" + telephone + '\'' +
", userDepartment='" + userDepartment + '\'' +
", activeFlag=" + activeFlag +
", addTime=" + addTime +
'}';
}
}

View File

@ -0,0 +1,23 @@
package com.xkrs.service;
import com.xkrs.model.entity.SysAuthorityEntity;
import java.util.List;
/**
* 系统权限服务接口
* @author tajochen
*/
public interface SysAuthorityService {
/**
* 获取权限实体列表根据用户名
* @param userName
* @return
*/
List<SysAuthorityEntity> getSysAuthorityListByUserName(String userName);
List<SysAuthorityEntity> findAllByIdIn(List<Integer> id);
List<Integer> selectAuthorityByUserId(Integer userId);
}

View File

@ -0,0 +1,19 @@
package com.xkrs.service;
import com.xkrs.model.entity.SysRoleEntity;
import java.util.List;
/**
* 系统角色服务接口
* @author tajochen
*/
public interface SysRoleService {
/**
* 获取角色实体列表根据用户名
* @param userName
* @return
*/
List<SysRoleEntity> getSysRoleListByUserName(String userName);
}

View File

@ -0,0 +1,99 @@
package com.xkrs.service;
import com.xkrs.model.entity.SysUserEntity;
import com.xkrs.model.qo.SysUserQo;
import com.xkrs.model.vo.SysUserVo;
import java.util.List;
/**
* 系统用户服务接口
* @author tajochen
*/
public interface SysUserService {
/**
* 检查用户名
* @param userName
* @return
*/
boolean checkUserName(String userName);
/**
* 获取所有用户
* @return
*/
//Iterable<SysUserVo> getAllSysUser();
/**
* 保存用户
* @param sysUserQo
*/
void addUser(SysUserQo sysUserQo);
/**
* 获取系统用户实体根据用户名
* @param userName
* @return
*/
SysUserEntity getSysUserByUserName(String userName);
/**
* 用户登录更新
* @param userName
* @param ipAddress
* @return
*/
int updateSysUserLogin(String userName, String ipAddress);
/**
* 系统用户更新
* @param sysUserQo
* @return
*/
int updateSysUser(SysUserQo sysUserQo);
/**
* 软删除系统用户
* @param id
* @return
*/
int softDeleteGeneralUser(Integer id);
/**
* 查询用户的信息
* @return
*/
List<SysUserVo> selectAllUser();
/**
* 启用
* @param userId
*/
void updateEnable(Integer userId);
/**
* 禁用
* @param userId
*/
void updateDisable(Integer userId);
/**
* 用户修改密码
* @param oldPassword
* @param newPassword
* @param confirmPassword
* @param sysUserEntity
* @return
*/
String updatePassword(String oldPassword,String newPassword,String confirmPassword,SysUserEntity sysUserEntity);
/**
* 管理员修改用户的密码
* @param userId
* @param newPassword
* @param confirmPassword
* @return
*/
String adminUpdatePassword(Integer userId,String newPassword,String confirmPassword);
}

View File

@ -0,0 +1,43 @@
package com.xkrs.service.impl;
import com.xkrs.dao.RelRoleAuthorityDao;
import com.xkrs.dao.SysAuthorityDao;
import com.xkrs.model.entity.SysAuthorityEntity;
import com.xkrs.service.SysAuthorityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* 系统权限服务实现
* @author tajochen
*/
@Service
public class SysAuthorityServiceImpl implements SysAuthorityService {
Logger logger = LoggerFactory.getLogger(SysAuthorityServiceImpl.class);
@Resource
private SysAuthorityDao sysAuthorityDao;
@Resource
private RelRoleAuthorityDao relRoleAuthorityDao;
@Override
public List<SysAuthorityEntity> getSysAuthorityListByUserName(String userName) {
return sysAuthorityDao.selectByUserName(userName);
}
@Override
public List<SysAuthorityEntity> findAllByIdIn(List<Integer> id) {
return sysAuthorityDao.findAllByIdIn(id);
}
@Override
public List<Integer> selectAuthorityByUserId(Integer userId) {
return relRoleAuthorityDao.selectAuthorityByUserId(userId);
}
}

View File

@ -0,0 +1,29 @@
package com.xkrs.service.impl;
import com.xkrs.dao.SysRoleDao;
import com.xkrs.model.entity.SysRoleEntity;
import com.xkrs.service.SysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* 系统角色服务实现
* @author tajochen
*/
@Service
public class SysRoleServiceImpl implements SysRoleService {
Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);
@Resource
private SysRoleDao sysRoleDao;
@Override
public List<SysRoleEntity> getSysRoleListByUserName(String userName) {
return sysRoleDao.selectByUserName(userName);
}
}

View File

@ -0,0 +1,231 @@
package com.xkrs.service.impl;
import com.xkrs.common.encapsulation.PromptMessageEnum;
import com.xkrs.dao.RelRoleAuthorityDao;
import com.xkrs.dao.RelUserRoleDao;
import com.xkrs.dao.SysRoleDao;
import com.xkrs.dao.SysUserDao;
import com.xkrs.model.entity.RelRoleAuthorityEntity;
import com.xkrs.model.entity.RelUserRoleEntity;
import com.xkrs.model.entity.SysRoleEntity;
import com.xkrs.model.entity.SysUserEntity;
import com.xkrs.model.qo.SysUserQo;
import com.xkrs.model.vo.SysUserVo;
import com.xkrs.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Locale;
import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
import static com.xkrs.utils.DateTimeUtil.getNowTime;
import static com.xkrs.utils.EncryptDecryptUtil.encry256;
/**
* 系统用户服务实现
* @author tajochen
*/
@Service
public class SysUserServiceImpl implements SysUserService {
Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);
@Resource
private SysUserDao sysUserDao;
@Resource
private SysRoleDao sysRoleDao;
@Resource
private RelUserRoleDao relUserRoleDao;
@Resource
private RelRoleAuthorityDao relRoleAuthorityDao;
/**
* 检查用户名是否存在
* @param userName
* @return
*/
@Override
public boolean checkUserName(String userName) {
int num = sysUserDao.checkUserName(userName);
return (num == 0);
};
/**
* 新增用户
* @param sysUserQo
*/
@Transactional(rollbackFor=Exception.class)
@Override
public void addUser(SysUserQo sysUserQo) {
String salt = KeyGenerators.string().generateKey();
SysUserEntity sysUserEntity = new SysUserEntity();
sysUserEntity.setUserName(sysUserQo.getUserName());
sysUserEntity.setReallyName(sysUserQo.getReallyName());
sysUserEntity.setSalt(salt);
sysUserEntity.setPassword(encry256(sysUserQo.getPassword() + salt));
sysUserEntity.setTelephone(sysUserQo.getUserName());
sysUserEntity.setUserDepartment(sysUserQo.getUserDepartment());
sysUserEntity.setActiveFlag(1);
sysUserEntity.setStatusCode(0);
sysUserEntity.setAddTime(getNowTime());
sysUserEntity.setDeleteFlag(0);
sysUserDao.save(sysUserEntity);
RelUserRoleEntity relUserRoleEntity = new RelUserRoleEntity();
relUserRoleEntity.setUserId(sysUserEntity.getId().longValue());
relUserRoleEntity.setRoleId(2);
RelRoleAuthorityEntity relRoleAuthorityEntity = new RelRoleAuthorityEntity();
relRoleAuthorityEntity.setRoleId(2);
relRoleAuthorityEntity.setAuthorityId(2);
relRoleAuthorityEntity.setUserId(sysUserEntity.getId());
relUserRoleDao.save(relUserRoleEntity);
relRoleAuthorityDao.save(relRoleAuthorityEntity);
//sysRoleDao.insertRelUserRole(sysUserEntity.getUserName(),"role_general_user");
}
/**
* 查询所有用户Vo
* @return
*/
/*@Transactional(rollbackFor=Exception.class)
@Override
public Iterable<SysUserVo> getAllSysUser() {
Iterable<SysUserVo> ls = sysUserDao.selectAllSysUser();
return ls;
}*/
@Transactional(rollbackFor=Exception.class)
@Override
public SysUserEntity getSysUserByUserName(String userName) {
return sysUserDao.selectByUserName(userName);
}
@Transactional(rollbackFor=Exception.class)
@Override
public int updateSysUserLogin(String userName,String ipAddress) {
return sysUserDao.updateSysUserLogin(userName,ipAddress);
}
/**
* 更新用户
* @param sysUserQo
* @return
*/
@Transactional(rollbackFor=Exception.class)
@Override
public int updateSysUser(SysUserQo sysUserQo) {
SysUserEntity sysUserEntity = new SysUserEntity();
sysUserEntity.setReallyName(sysUserQo.getReallyName());
sysUserDao.save(sysUserEntity);
return 1;
}
/**
* 软删除普通用户
* @param id
* @return
*/
@Transactional(rollbackFor=Exception.class)
@Override
public int softDeleteGeneralUser(Integer id) {
String adminRole = "role_administor";
String sysRole ="role_system_manager";
List<SysRoleEntity> list = sysRoleDao.selectByUserId(id);
if(list.size()>0){
SysRoleEntity sysRoleEntity = list.get(1);
if(sysRole.equals(sysRoleEntity.getRoleName())||adminRole.equals(sysRoleEntity.getRoleName())){
sysUserDao.softDeleteGeneralUserById(id);
return 0;
}
}
return 1;
}
/**
* 查询用户的信息
* @return
*/
@Override
public List<SysUserVo> selectAllUser() {
return sysUserDao.selectAll();
}
/**
* 启用
* @param userId
*/
@Transactional(rollbackFor=Exception.class)
@Override
public void updateEnable(Integer userId) {
sysUserDao.updateEnable(userId);
}
/**
* 禁用
* @param userId
*/
@Transactional(rollbackFor=Exception.class)
@Override
public void updateDisable(Integer userId) {
sysUserDao.updateDisable(userId);
}
/**
* 用户修改密码
* @param oldPassword
* @param newPassword
* @param confirmPassword
* @param sysUserEntity
* @return
*/
@Transactional(rollbackFor=Exception.class)
@Override
public String updatePassword(String oldPassword, String newPassword, String confirmPassword, SysUserEntity sysUserEntity) {
Locale locale = LocaleContextHolder.getLocale();
String oldFrontPassword = encry256(oldPassword + sysUserEntity.getSalt());
if(!oldFrontPassword.equals(sysUserEntity.getPassword())){
return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"旧密码输入错误",locale);
}
if(!newPassword.equals(confirmPassword)){
return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"两次密码输入不一致",locale);
}
String newAfterPassword = encry256(newPassword + sysUserEntity.getSalt());
sysUserDao.updatePassword(sysUserEntity.getId(),newAfterPassword);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"密码修改成功",locale);
}
/**
* 管理员修改用户的密码
* @param userId
* @param newPassword
* @param confirmPassword
* @return
*/
@Transactional(rollbackFor=Exception.class)
@Override
public String adminUpdatePassword(Integer userId, String newPassword, String confirmPassword) {
Locale locale = LocaleContextHolder.getLocale();
if(!newPassword.equals(confirmPassword)){
return outputEncapsulationObject(PromptMessageEnum.PROCESS_FAIL,"两次密码输入不一致",locale);
}
SysUserEntity sysUserEntity = sysUserDao.selectByUserId(userId);
String newAfterPassword = encry256(newPassword + sysUserEntity.getSalt());
sysUserDao.updatePassword(userId,newAfterPassword);
return outputEncapsulationObject(PromptMessageEnum.SUCCESS,"密码修改成功",locale);
}
}

View File

@ -0,0 +1,211 @@
package com.xkrs.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
* 根据经纬度获取地址: 位置名称
* @author XinYi Song
*/
public class AddressUtils {
private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36";
/**
* 获取指定经纬度的地理位置
* @param latitude 纬度
* @param longitude 经度
* @return
*/
public static String getLocal(String latitude, String longitude) {
String ok = "ok";
String msg = "msg";
String info = getAdd(latitude, longitude);
ObjectMapper mapper = new ObjectMapper();
JsonNode node = null;
try {
node = mapper.readTree(info);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
assert node != null;
String province = null;
String city = null;
String county = null;
String road = null;
String address = null;
if (ok.equals(node.path(msg).asText())) {
province = node.path("result").path("addressComponent").path("province").asText();
city = node.path("result").path("addressComponent").path("city").asText();
county = node.path("result").path("addressComponent").path("county").asText();
road = node.path("result").path("addressComponent").path("road").asText();
address = node.path("result").path("addressComponent").path("address").asText();
}
String fireAddress = province + city + county + road + address;
return fireAddress;
}
/**
* 根据经纬度获取位置信息
* @param latitude 纬度
* @param longitude 经度
* @return
*/
public static String getAdd(String latitude, String longitude) {
// 读取成功标志
boolean isSuccess = false;
// 重复次数
int count = 10;
ObjectMapper mapper = new ObjectMapper();
Map<String, String> paramMap = new HashMap<>(3);
paramMap.put("lon", longitude);
paramMap.put("lat", latitude);
paramMap.put("ver", "1");
String paramStr = null;
try {
paramStr = mapper.writeValueAsString(paramMap);
} catch (JsonProcessingException e) {
log.error("转json失败,{}", (Object) e.getStackTrace());
}
String url = String.format("http://api.tianditu.gov.cn/geocoder?type=geocode&tk=5a1d34815475f88e6d8802da6be832ae&postStr=%s",
paramStr);
// 创建http对象
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(60000)
.build();
CloseableHttpClient client = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig).build();
// 创建并设置URI
URIBuilder uri = null;
// 创建Get请求
HttpGet get = null;
try {
URL url1 = new URL(url);
URI uri1 = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
uri = new URIBuilder(uri1);
get = new HttpGet(uri.build());
// 设置请求头
setGet(get);
} catch (URISyntaxException | MalformedURLException e) {
log.info("错误{}", (Object) e.getStackTrace());
}
//发送请求
HttpEntity entity = null;
InputStream is = null;
BufferedReader br = null;
// 创建响应对象
CloseableHttpResponse response = null;
String line;
String sLine = null;
String json = null;
while (!isSuccess && count > 0) {
try {
response = client.execute(get);
// 获取请求结果
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
log.info("实时定位数据未请求成功");
count--;
//close(is, br, response, client);
continue;
}
entity = response.getEntity();
is = entity.getContent();
br = new BufferedReader(
new InputStreamReader(is, StandardCharsets.UTF_8)
);
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
sLine = sb.toString();
sLine = sLine.substring(sLine.indexOf("{"));
//使用ObjectMapper对象对 User对象进行转换
try {
json = mapper.writeValueAsString(sLine);
} catch (JsonProcessingException e) {
log.info("json字符串转化异常{}", (Object) e.getStackTrace());
}
isSuccess = true;
} catch (ClientProtocolException e) {
log.info("请求超时等问题:{}", (Object) e.getStackTrace());
} catch (IOException e) {
log.info("I/O问题:{}", (Object) e.getStackTrace());
} finally {
close(is, br, response, client);
}
}
return sLine;
}
private static void close(InputStream is, BufferedReader br, CloseableHttpResponse response, CloseableHttpClient client){
try {
if (null != is){
is.close();
}
if (null != br){
br.close();
}
if (null != response){
response.close();
}
if (null != client){
client.close();
}
} catch (IOException e) {
log.info("IO错误{}", (Object) e.getStackTrace());
}
}
private static HttpGet setGet(HttpGet get) {
get.setHeader("Accept"
, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
get.setHeader("Accept-Encoding"
, "gzip, deflate");
get.setHeader("Accept-Language"
, "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6");
get.setHeader("Connection"
, "keep-alive");
get.setHeader("Cache-Control"
, "no-cache");
get.setHeader("Upgrade-Insecure-Requests"
, "1");
get.setHeader("User-Agent", USER_AGENT);
return get;
}
public static void main(String[] args) {
String map = getAdd("35.150684", "115.84691");
String local = getLocal("36.90033", "117.752853");
System.out.println(local);
}
}

View File

@ -0,0 +1,73 @@
package com.xkrs.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
/**
* @author xkrs
*/
public class BeanUtils {
/**
* 缓存BeanCopier 对象 提升性能
*/
private static final ConcurrentHashMap<String, org.springframework.cglib.beans.BeanCopier> BEAN_COPIER_MAP = new ConcurrentHashMap<>();
/**
* Bean属性复制工具方法
* @param sources 原始集合
* @param supplier: 目标类::new(eg: UserVO::new)
*/
public static <S, T> List<T> cgLibCopyList(List<S> sources, Supplier<T> supplier) {
List<T> list = new ArrayList<>(sources.size());
org.springframework.cglib.beans.BeanCopier beanCopier = null;
for (S source : sources) {
T t = supplier.get();
if (beanCopier == null) {
beanCopier = getBeanCopier(source.getClass(), t.getClass());
}
beanCopier.copy(source, t, null);
list.add(t);
}
return list;
}
/**
* Bean属性复制工具方法
* @param source 目标对象
* @param supplier: 目标类::new(eg: UserVO::new)
*/
public static <T> T cgLibCopyBean(Object source, Supplier<T> supplier) {
T t = supplier.get();
getBeanCopier(source.getClass(), t.getClass()).copy(source, t, null);
return t;
}
/**
* 获取BeanCopier对象 如果缓存中有从缓存中获取 如果没有则新创建对象并加入缓存
* @param sourceClass
* @param targetClass
* @return
*/
private static org.springframework.cglib.beans.BeanCopier getBeanCopier(Class<?> sourceClass, Class<?> targetClass) {
String key = getKey(sourceClass.getName(), targetClass.getName());
org.springframework.cglib.beans.BeanCopier beanCopier;
beanCopier = BEAN_COPIER_MAP.get(key);
if (beanCopier == null) {
beanCopier = org.springframework.cglib.beans.BeanCopier.create(sourceClass, targetClass, false);
BEAN_COPIER_MAP.put(key, beanCopier);
}
return beanCopier;
}
/**
* 生成缓存key
*/
private static String getKey(String sourceClassName, String targetClassName) {
return sourceClassName + targetClassName;
}
}

View File

@ -0,0 +1,177 @@
package com.xkrs.utils;
/**
* @author XinYi Song
*/
public interface CommonConstant {
/**
* 正常状态
*/
public static final String STATUS_NORMAL = "0";
/**
* 禁用状态
*/
public static final String STATUS_DISABLE = "1";
/**
* 删除标志
*/
public static final String DEL_FLAG_1 = "1";
/**
* 未删除
*/
public static final String DEL_FLAG_0 = "0";
/**
* 系统日志类型 登录
*/
public static final int LOG_TYPE_1 = 1;
/**
* 系统日志类型 操作
*/
public static final int LOG_TYPE_2 = 2;
/**
* 操作日志类型 查询
*/
public static final int OPERATE_TYPE_1 = 1;
/**
* 操作日志类型 添加
*/
public static final int OPERATE_TYPE_2 = 2;
/**
* 操作日志类型 更新
*/
public static final int OPERATE_TYPE_3 = 3;
/**
* 操作日志类型 删除
*/
public static final int OPERATE_TYPE_4 = 4;
/**
* 操作日志类型 倒入
*/
public static final int OPERATE_TYPE_5 = 5;
/**
* 操作日志类型 导出
*/
public static final int OPERATE_TYPE_6 = 6;
/** {@code 500 Server Error} (HTTP/1.0 - RFC 1945) */
public static final Integer SC_INTERNAL_SERVER_ERROR_500 = 500;
public static final Integer SC_INTERNAL_SERVER_ERROR_501 = 501;
public static final Integer SC_INTERNAL_SERVER_ERROR_502 = 502;
/** {@code 200 OK} (HTTP/1.0 - RFC 1945) */
public static final Integer SC_OK_200 = 200;
public static final Integer SC_OK_201 = 201;
public static final Integer SC_OK_202 = 202;
public static final Integer SC_OK_300 = 300;
public static final Integer SC_OK_301 = 301;
/**访问权限认证未通过 510*/
public static final Integer SC_JEECG_NO_AUTHZ=510;
/** 登录用户Shiro权限缓存KEY前缀 */
public static String PREFIX_USER_SHIRO_CACHE = "shiro:cache:org.jeecg.modules.shiro.authc.ShiroRealm.authorizationCache:";
/** 登录用户Token令牌缓存KEY前缀 */
public static final String PREFIX_USER_TOKEN = "prefix_user_token_";
/** Token缓存时间3600秒即一小时 */
public static final int TOKEN_EXPIRE_TIME = 3600;
/**
* 0一级菜单
*/
public static final Integer MENU_TYPE_0 = 0;
/**
* 1子菜单
*/
public static final Integer MENU_TYPE_1 = 1;
/**
* 2按钮权限
*/
public static final Integer MENU_TYPE_2 = 2;
/**通告对象类型USER:指定用户ALL:全体用户)*/
public static final String MSG_TYPE_UESR = "USER";
public static final String MSG_TYPE_ALL = "ALL";
/**发布状态0未发布1已发布2已撤销*/
public static final String NO_SEND = "0";
public static final String HAS_SEND = "1";
public static final String HAS_CANCLE = "2";
/**阅读状态0未读1已读*/
public static final String HAS_READ_FLAG = "1";
public static final String NO_READ_FLAG = "0";
/**优先级L低M中H高*/
public static final String PRIORITY_L = "L";
public static final String PRIORITY_M = "M";
public static final String PRIORITY_H = "H";
/**
* 短信模板方式 0 .登录模板1.注册模板2.忘记密码模板
* 3 信息变更
*/
public static final String SMS_TPL_TYPE_0 = "0";
public static final String SMS_TPL_TYPE_1 = "1";
public static final String SMS_TPL_TYPE_2 = "2";
public static final String SMS_TPL_TYPE_3 = "3";
/**
* 状态(0无效1有效)
*/
public static final String STATUS_0 = "0";
public static final String STATUS_1 = "1";
/**
* 同步工作流引擎1同步0不同步
*/
public static final Integer ACT_SYNC_1 = 1;
public static final Integer ACT_SYNC_0 = 0;
/**
* 消息类型1:通知公告2:系统消息
*/
public static final String MSG_CATEGORY_1 = "1";
public static final String MSG_CATEGORY_2 = "2";
/**
* 是否配置菜单的数据权限 1是0否
*/
public static final Integer RULE_FLAG_0 = 0;
public static final Integer RULE_FLAG_1 = 1;
/**
* 是否用户已被冻结 1正常(解冻) 2冻结
*/
public static final String USER_UNFREEZE = "1";
public static final String USER_FREEZE = "2";
/**
* 文件上传类型本地localMiniominio阿里云alioss
*/
public static final String UPLOAD_TYPE_LOCAL = "local";
public static final String UPLOAD_TYPE_MINIO = "minio";
public static final String UPLOAD_TYPE_OSS = "alioss";
/**
* 收入明细 1:收入 2:支出
*/
public static final Integer USER_IDENTITY_1 = 1;
public static final Integer USER_IDENTITY_2 = 2;
}

View File

@ -0,0 +1,54 @@
package com.xkrs.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 复制源对象的属性值
* @Author tajochen
*/
public class CopyPropertiesUtil {
/**
* 复制源对象和目标对象的属性值
* @param source 源对象
* @param target 目标对象
* @throws SecurityException
* @throws IllegalArgumentException
*/
public static void copy(Object source, Object target) {
//得到对象的Class
Class sourceClass = source.getClass();
Class targetClass = target.getClass();
//得到Class对象的所有属性
Field[] sourceFields = sourceClass.getDeclaredFields();
Field[] targetFields = targetClass.getDeclaredFields();
for(Field sourceField : sourceFields){
//属性名
String name = sourceField.getName();
//属性类型
Class type = sourceField.getType();
String methodName = name.substring(0, 1).toUpperCase() + name.substring(1);
try{
//得到属性对应get方法
Method getMethod = sourceClass.getMethod("get" + methodName);
//执行源对象的get方法得到属性值
Object value = getMethod.invoke(source);
//目标对象的属性名
for(Field targetField : targetFields){
String targetName = targetField.getName();
if(targetName.equals(name)){
//属性对应的set方法
Method setMethod = targetClass.getMethod("set" + methodName, type);
//执行目标对象的set方法
setMethod.invoke(target, value);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,205 @@
package com.xkrs.utils;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 日期时间工具
* @author tajochen
*/
public class DateTimeUtil {
private final static String COMMON_PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss";
private final static String COMMON_PATTERN_DATE = "yyyy-MM-dd";
private final static DateTimeFormatter COMMON_FORMATTER_DATETIME = DateTimeFormatter.ofPattern(COMMON_PATTERN_DATETIME);
private final static DateTimeFormatter COMMON_FORMATTER_DATE = DateTimeFormatter.ofPattern(COMMON_PATTERN_DATE);
private final static ZoneOffset DEFAULT_ZONE_OFFSET = ZoneOffset.of("+8");
/**
* 字符串转LocalDate
* @param date
* @return
*/
public static LocalDate stringToDate(String date) {
assert date != null;
return LocalDate.parse(date, COMMON_FORMATTER_DATE);
}
/**
* LocalDate转字符串
* @param date
* @return
*/
public static String dateToString(LocalDate date) {
assert date != null;
return COMMON_FORMATTER_DATE.format(date);
}
/**
* LocalDateTime转字符串
* @param dateTime
* @return
*/
public static String dateTimeToString(LocalDateTime dateTime) {
assert dateTime != null;
return COMMON_FORMATTER_DATETIME.format(dateTime);
}
/**
* 字符串转LocalDateTime
* @param dateStr
* @return
*/
public static LocalDateTime stringToDateTime(String dateStr) {
assert dateStr != null;
return LocalDateTime.parse(dateStr, COMMON_FORMATTER_DATETIME);
}
/**
* 字符串转Instant时间戳
* @param str
* @return
*/
public static Instant stringToInstant(String str) {
assert str != null;
return stringToDateTime(str).toInstant(DEFAULT_ZONE_OFFSET);
}
/**
* LocalDateTime转字符串格式化
* @param dateTime
* @param formatter
* @return
*/
public static String dateToStringFormatter(LocalDateTime dateTime, DateTimeFormatter formatter) {
assert dateTime != null;
return formatter.format(dateTime);
}
/**
* 字符串转LocalDateTime格式化
* @param dateStr
* @param formatter
* @return
*/
public static LocalDateTime stringToDateTimeFormatter(String dateStr, DateTimeFormatter formatter) {
assert dateStr != null;
return LocalDateTime.parse(dateStr, formatter);
}
/**
* 字符串转 local date
* @param dateStr
* @return
*/
public static LocalDate stringToDateFormatter(String dateStr){
LocalDate date = LocalDate.parse(dateStr, COMMON_FORMATTER_DATE);
return date;
}
/**
* 日期转时间戳
* @param dateTime
* @return
*/
public static long dateToTimeMillis(LocalDateTime dateTime) {
assert dateTime != null;
return dateTime.toInstant(DEFAULT_ZONE_OFFSET).toEpochMilli();
}
/**
* 时间戳转日期
* @param timeMillis
* @return
*/
public static LocalDateTime timeMillisToDate(long timeMillis) {
Instant instant = Instant.ofEpochMilli(timeMillis);
return LocalDateTime.ofInstant(instant, DEFAULT_ZONE_OFFSET);
}
/**
* 时间戳转时间
* @param timeMillis
* @return
*/
public static LocalDateTime timeMillisToTime(long timeMillis) {
LocalDateTime dateTime =LocalDateTime.ofEpochSecond(timeMillis,0, DEFAULT_ZONE_OFFSET);
return dateTime;
}
/**
* 获取当前时间 hh:mm:ss:nnn
* @return
*/
public static LocalDateTime getNowTime() {
LocalDateTime now = LocalDateTime.now();
return now;
}
/**
* 获取当前日期 yyyy-MM-dd
* @return
*/
public static LocalDate getToday() {
LocalDate now = LocalDate.now();
return now;
}
/**
* 获取当前 Instant 时间戳
* @return
*/
public static Instant getInstant() {
Instant timeStamp = Instant.now();
return timeStamp;
}
/**
* 判断日期格式是否合法 "yyyy-MM-dd"
* @param strDate
* @return
*/
public static boolean isValidDate(String strDate) {
final int minLen = 10;
if(strDate == null || strDate.length() < minLen) {
return false;
}
//正则表达式校验日期格式 yyyy-MM-dd
String eL = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-" +
"(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})" +
"(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)(([0-9]{3}[1-9]|[0-9]{2}[1-9]" +
"[0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-" +
"(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|" +
"((0[48]|[2468][048]|[3579][26])00))-02-29)";
Pattern pat = Pattern.compile(eL);
Matcher matcher = pat.matcher(strDate);
return matcher.matches();
}
/**
* 判断时间格式 格式必须为 "YYYY-MM-DD HH:mm:ss"
* @param sDateTime
* @return
*/
public static boolean isValidDateTime(String sDateTime) {
final int minLen = 19;
if ((sDateTime == null) || (sDateTime.length() < minLen)) {
return false;
}
String eL = "(((01[0-9]{2}|0[2-9][0-9]{2}|[1-9][0-9]{3})-(0?[13578]|1[02])-" +
"(0?[1-9]|[12]\\\\d|3[01]))|((01[0-9]{2}|0[2-9][0-9]{2}|[1-9][0-9]{3})-" +
"(0?[13456789]|1[012])-(0?[1-9]|[12]\\\\d|30))|((01[0-9]{2}|0[2-9][0-9]{2}|[1-9][0-9]{3})-0?2-" +
"(0?[1-9]|1\\\\d|2[0-8]))|(((1[6-9]|[2-9]\\\\d)(0[48]|[2468][048]|[13579][26])|((04|08|12|16|[2468][048]|" +
"[3579][26])00))-0?2-29)) (20|21|22|23|[0-1]?\\\\d):[0-5]?\\\\d:[0-5]?\\\\d";
Pattern pat = Pattern.compile(eL);
Matcher matcher = pat.matcher(sDateTime);
return matcher.matches();
}
}

View File

@ -0,0 +1,66 @@
package com.xkrs.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* SHA加密解密工具
* @author tajochen
*/
public class EncryptDecryptUtil {
/**
* SHA-256加密
* @param strText
* @return
*/
public static String encry256(final String strText){
return encrySha(strText,"SHA-256");
}
/**
* SHA-512加密
* @param strText
* @return
*/
public static String encry512(final String strText){
return encrySha(strText,"SHA-512");
}
/**
* 基础SHA加密
* @param strText
* @param strType
* @return
*/
private static String encrySha(final String strText, final String strType){
// 返回值
String strResult=null;
// 是否是有效的字符串
if (strText != null && strText.length()>0){
// 加密开始创建加密对象并传入加密类型
try {
MessageDigest messageDigest = MessageDigest.getInstance(strType);
// 传入加密的字符串
messageDigest.update(strText.getBytes());
// 得到bytes类型结果
byte[] byteBuffer = messageDigest.digest();
StringBuilder strHexString = new StringBuilder();
for (byte b : byteBuffer) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
strHexString.append('0');
}
strHexString.append(hex);
}
// 得到返回的结果
strResult = strHexString.toString();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return strResult;
}
}

View File

@ -0,0 +1,36 @@
package com.xkrs.utils;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
/**
* @author XinYi Song
*/
public class EntityManagerUtil {
/**
* 把List<Object[]>转换成List<T>
*/
public static <T> List<T> objectToBean(List<Object[]> objList, Class<T> clz) throws Exception{
if (objList==null || objList.size()==0) {
return null;
}
Class<?>[] cz = null;
Constructor<?>[] cons = clz.getConstructors();
for (Constructor<?> ct : cons) {
Class<?>[] clazz = ct.getParameterTypes();
if (objList.get(0).length == clazz.length) {
cz = clazz;
break;
}
}
List<T> list = new ArrayList<T>();
for (Object[] obj : objList) {
Constructor<T> cr = clz.getConstructor(cz);
list.add(cr.newInstance(obj));
}
return list;
}
}

View File

@ -0,0 +1,193 @@
package com.xkrs.utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author ZHY
* @date 2020/6/17 15:56
*/
public class ExcelImportUtil {
private Workbook wb;
private Sheet sheet;
private Row row;
String xls = ".xls";
String xlsx = ".xlsx";
/**
* 读取Excel
*
* @author ZHY
*/
public ExcelImportUtil(MultipartFile file) throws Exception {
String filename = file.getOriginalFilename();
String ext = filename.substring(filename.lastIndexOf("."));
InputStream is = file.getInputStream();
if (xls.equals(ext)) {
wb = new HSSFWorkbook(is);
} else if (xlsx.equals(ext)) {
wb = new XSSFWorkbook(is);
} else {
wb = null;
}
}
/**
* 读取Excel表格表头的内容输出
*
*/
public List<Map<String, Object>> readExcelTitleOut() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
if (wb != null) {
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
// 标题总列数
int colNum = row.getPhysicalNumberOfCells();
System.out.println("colNum:" + colNum);
Map<String, Object> map = new LinkedHashMap<String, Object>();
for (int i = 0; i < colNum; i++) {
String stringCellValue = row.getCell(i).getStringCellValue();
map.put(stringCellValue, null);
}
list.add(map);
return list;
}
return list;
}
/**
* 读取Excel表格表头
*
*/
public String[] readExcelTitle() {
String[] title = {};
if (wb != null) {
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
// 标题总列数
int colNum = row.getPhysicalNumberOfCells();
System.out.println("colNum:" + colNum);
title = new String[colNum];
for (int i = 0; i < colNum; i++) {
Cell cell = row.getCell(i);
title[i] = cell.getStringCellValue().replaceAll("\\s+", "");
}
}
return title;
}
/**
* 读取Excel表格的某一个数值
* @return
*/
public Map<String, Object> readExcelSomeTitle(){
Map<String, Object> map = new LinkedHashMap<>();
if (wb != null) {
sheet = wb.getSheetAt(0);
String title = parseExcel(sheet.getRow(2).getCell(1));
String remark = parseExcel(sheet.getRow(3).getCell(1));
map.put("date",title);
map.put("remark",remark);
}
return map;
}
/**
* 读取Excel数据内容
*
*/
public List<Map<String, String>> readExcelContent() {
List<Map<String, String>> list = new ArrayList<>();
if (wb != null) {
//获取sheet表
sheet = wb.getSheetAt(0);
// 得到总行数
int rowNum = sheet.getLastRowNum();
//获取表头的标题
String[] readExcelTitle = readExcelTitle();
// 正文内容应该从第二行开始,第一行为表头的标题
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
Map<String, String> map = new LinkedHashMap<>();
for (int j = 0; j < readExcelTitle.length; j++) {
//获取每一列的数据值
String str = parseExcel(row.getCell(j));
//判断对应行的列值是否为空
if (str != null || "".equals(str)) {
//表头的标题为键值列值为值
map.put(readExcelTitle[j], str);
}
}
//判段添加的对象是否为空
if (!map.isEmpty()){
list.add(map);
}
}
}
return list;
}
/**
*
* 根据Cell类型设置数据
*
*/
int ss = 20;
int xx = 58;
private String parseExcel(Cell cell) {
String result = "";
if (cell != null) {
SimpleDateFormat sdf = null;
switch (cell.getCellType()) {
// 数字类型
case NUMERIC:
// 处理日期格式时间格式
if (DateUtil.isCellDateFormatted(cell)) {
if (cell.getCellStyle().getDataFormat() == ss) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
String dateFormat = sdf.format(cell.getDateCellValue());
result = dateFormat;
} else if (cell.getCellStyle().getDataFormat() == xx) {
// 处理自定义日期格式m月d日(通过判断单元格的格式id解决id的值是58)
sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = DateUtil.getJavaDate(value);
result = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
DecimalFormat format = new DecimalFormat("#.###########");
String strVal = format.format(value);
result = strVal;
}
break;
// String类型
case STRING:
result = cell.getRichStringCellValue().toString();
break;
default:
break;
}
}
return result;
}
}

View File

@ -0,0 +1,127 @@
package com.xkrs.utils;
import org.apache.commons.codec.binary.Base64;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* @author XinYi Song
*/
public class FileUtil {
/**
* 根据base64判断图片是否为tiff
* @param base64
* @return
*/
public boolean checkImageBase64Format(String base64) {
byte[] b=java.util.Base64.getDecoder().decode(base64);
try {
// 判断是否为tiff格式
if((b[0] & 0xFF) == 0x49 && (b[1] & 0xFF)==0x49 && (b[2] & 0xFF)==0x2A){
return true;
}else {
return false;
}
}catch(Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据BASE64字符串生成图片文件此方法生成tiff格式
* @param base64
* @param fileName
* @param dictionary
*/
public void base64ToFile(String base64,String fileName,String dictionary) {
File file =null;
File dir=new File(dictionary);
// 无目录的情况下创建一个目录,会受权限影响,最好是已存在的目录
if(!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
FileOutputStream fos=null;
BufferedOutputStream bos=null;
try {
byte [] bytes=java.util.Base64.getDecoder().decode(base64);
//目录+文件名作为输出文件的全路径
file=new File(dictionary+fileName);
fos= new FileOutputStream(file);
bos=new BufferedOutputStream(fos);
bos.write(bytes);
}catch(Exception e) {
e.printStackTrace();
}finally {
if(bos!=null) {
try {
bos.close();
}catch(IOException e) {
e.printStackTrace();
}
}
if(fos!=null) {
try {
fos.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 将tiff图片转化为jpg生成新的文件
* @param oldPath 原图片的全路径
* @param newPath 生成新的图片的全路径
*/
public void tiffToJpg(String oldPath,String newPath) {
try {
BufferedImage bufferegImage= ImageIO.read(new File(oldPath));
//可以是png等其它图片格式
ImageIO.write(bufferegImage,"jpg",new File(newPath));
}catch(IOException e) {
e.printStackTrace();
}
}
/**
* 将任意图片文件转为base64读字节是最快的方式
* @param filePath 图片文件的全路径
* @return
*/
public String imageToBase64(String filePath) {
byte [] data =null;
try {
InputStream in =new FileInputStream(filePath);
data=new byte[in.available()];
in.read(data);
in.close();
}catch(Exception e) {
e.printStackTrace();
return null;
}
return new String(Base64.encodeBase64(data));
}
public static void main(String[] args) {
String oldPath = "C:/Users/xkrs/Desktop/WF/分布/maize";
String newPath = "E:/img";
try {
BufferedImage bufferegImage=ImageIO.read(new File(oldPath));
//可以是png等其它图片格式
ImageIO.write(bufferegImage,"jpg",new File(newPath));
}catch(IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,40 @@
package com.xkrs.utils;
import java.security.MessageDigest;
/**
* md5加密解密工具
* @author tajochen
*/
public class HashUtil {
/**
* MD5加密
*
* @param password
* @return
*/
public static String md5Encode(String password) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = password.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++){
byteArray[i] = (byte) charArray[i];
}
byte[] md5Bytes = md5.digest(byteArray);
StringBuilder hexValue = new StringBuilder();
for (byte md5Byte : md5Bytes) {
int val = ((int) md5Byte) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
}

View File

@ -0,0 +1,42 @@
package com.xkrs.utils;
import javax.servlet.http.HttpServletRequest;
/**
* IP地址处理工具
* @author tajochen
*/
public class IpUtil {
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
final String unkonwMsg = "unknown";
final char splitChar = ',';
if (ip != null && ip.length() != 0 && !unkonwMsg.equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个ip值第一个ip才是真实ip
if( ip.indexOf(splitChar)!=-1 ){
ip = ip.split(",")[0];
}
}
if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || unkonwMsg.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
System.out.println("获取客户端ip: " + ip);
return ip;
}
}

View File

@ -0,0 +1,35 @@
package com.xkrs.utils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author XinYi Song
*/
@Component
public class JdbcUtils {
@Resource
private JdbcTemplate jdbcTemplate;
/**
* jdbcTemplatebatchUpdate增加需自己定义sql需要配置
* @param list
*/
/*public List<FireTaskPhoto> batchWithJdbcTemplate(List<FireTaskPhoto> list){
String sql = "Insert into fire_task_photo(photo_fire_code,task_photo) values(?,?)";
jdbcTemplate.batchUpdate(sql,new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1,list.get(i).getPhotoFireCode());
ps.setString(2,list.get(i).getTaskPhoto());
}
@Override
public int getBatchSize() {
return list.size();
}
});
return list;
}*/
}

View File

@ -0,0 +1,21 @@
package com.xkrs.utils;
/**
* 数字工具
* @author tajochen
*/
public class NumberUtil {
public static boolean isStrNumeric(String str) {
if(str==null||str.length()==0){
return false;
}
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}

View File

@ -0,0 +1,152 @@
package com.xkrs.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author XinYi Song
*/
public class ObjectToBeanUtils {
public static Logger log = LoggerFactory.getLogger(ObjectToBeanUtils.class);
/**
* 把List<Object[]>转换成List<T>
*/
public static <T> List<T> objectToBean(List<Object[]> objList, Class<T> clz) throws Exception{
if (objList==null || objList.size()==0) {
return null;
}
Class<?>[] cz = null;
Constructor<?>[] cons = clz.getConstructors();
for (Constructor<?> ct : cons) {
Class<?>[] clazz = ct.getParameterTypes();
if (objList.get(0).length == clazz.length) {
cz = clazz;
break;
}
}
List<T> list = new ArrayList<T>();
for (Object[] obj : objList) {
Constructor<T> cr = clz.getConstructor(cz);
list.add(cr.newInstance(obj));
}
return list;
}
public static <T> List<T> objectToBeans(List<Object[]> objList, Class<T> clz) throws Exception{
if (objList==null || objList.size()==0) {
return null;
}
int length = objList.get(0).length;
log.info("*************>"+length);
Class<?>[] cz = null;
Constructor<?>[] cons = clz.getConstructors();
for (Constructor<?> ct : cons) {
Class<?>[] clazz = ct.getParameterTypes();
if (objList.get(0).length == clazz.length) {
cz = clazz;
break;
}
}
List<T> list = new ArrayList<T>();
log.info("---------->"+objList.get(0));
Constructor<T> cr = clz.getConstructor(cz);
T newInstance = cr.newInstance((Object) objList.get(0));
list.add(newInstance);
return list;
}
public static <T> List<T> castEntity(List<Object[]> list, Class<T> clazz, Object model) {
List<T> returnList = new ArrayList<T>();
if (list.isEmpty()) {
return returnList;
}
//获取每个数组集合的元素个数
Object[] co = list.get(0);
//获取当前实体类的属性名属性值属性类别
List<Map> attributeInfoList = getFiledsInfo(model);
//创建属性类别数组
Class[] c2 = new Class[attributeInfoList.size()];
//如果数组集合元素个数与实体类属性个数不一致则发生错误
if (attributeInfoList.size() != co.length) {
return returnList;
}
//确定构造方法
for (int i = 0; i < attributeInfoList.size(); i++) {
c2[i] = (Class) attributeInfoList.get(i).get("type");
}
try {
for (Object[] o : list) {
Constructor<T> constructor = clazz.getConstructor(c2);
returnList.add(constructor.newInstance(o));
}
} catch (Exception ex) {
log.info("实体数据转化为实体类发生异常:异常信息:{}", ex.getMessage());
return returnList;
}
return returnList;
}
/**
* 根据属性名获取属性值
*
* @param fieldName 属性名
* @param modle 实体类
* @return 属性值
*/
private static Object getFieldValueByName(String fieldName, Object modle) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = modle.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(modle, new Object[]{});
return value;
} catch (Exception e) {
return null;
}
}
/**
* 获取属性类型(type)属性名(name)属性值(value)的map组成的list
*
* @param model 实体类
* @return list集合
*/
private static List<Map> getFiledsInfo(Object model) {
Field[] fields = model.getClass().getDeclaredFields();
List<Map> list = new ArrayList(fields.length);
Map infoMap = null;
for (int i = 0; i < fields.length; i++) {
infoMap = new HashMap(3);
infoMap.put("type", fields[i].getType());
infoMap.put("name", fields[i].getName());
infoMap.put("value", getFieldValueByName(fields[i].getName(), model));
list.add(infoMap);
}
return list;
}
}

View File

@ -0,0 +1,37 @@
package com.xkrs.utils;
import org.geolatte.geom.Geometry;
import org.geolatte.geom.Point;
import org.geolatte.geom.codec.Wkt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 开源Gis工具集
* @author tajochen
*/
public class OpenGeoUtil {
Logger logger = LoggerFactory.getLogger(OpenGeoUtil.class);
/**
* wkt文本转为点数据
* @param wkt
* @return
*/
public static Point wktStrToPoint(String wkt) {
Point point = (Point) Wkt.fromWkt(wkt);
return point;
}
/**
* wkt文本转geometry
* @param wkt
* @return
*/
public static Geometry wktStrToGeom(String wkt) {
Geometry geom = Wkt.fromWkt(wkt);
return geom;
}
}

View File

@ -0,0 +1,188 @@
package com.xkrs.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author XinYi Song
*/
public class PhotoUtil {
public static Logger log = LoggerFactory.getLogger(PhotoUtil.class);
/**
* 上传单张图片
* @param imgFile
* @return
* @throws IOException
*/
public static String memoryPhoto(MultipartFile imgFile,String distributedTime,String distributedType) throws IOException {
//String uploadPath = "http://139.199.98.175:2088/wfTaskImage/";
String uploadPath = "http://192.168.2.172/";
//获取原始文件名
String originalFilename = imgFile.getOriginalFilename();
if (originalFilename != null && !"".equals(originalFilename)) {
//找到 . 的位置
int index = originalFilename.lastIndexOf(".");
//根据 . 的位置进行分割拿到文件后缀名
String suffix = originalFilename.substring(index);
//uuid生成新的文件名
String newName = UUID.randomUUID().toString() + suffix;
//将图片保存到本地/usr/etc/images/Folder
File file = new File("E:/img/");
if (!file.exists()) {
file.mkdirs();
}
String path = "E:/img/" + newName;
String uploadsImage = uploadPath + newName;
//实现上传
imgFile.transferTo(new File(path));
return "video/"+newName;
}
return null;
}
/**
* 以文件形式批量上传图片
* @param files
* @return
* @throws IOException
*/
/*public static List<FireTaskPhoto> uploadImage(MultipartFile[] files, String fireCode) throws IOException {
String uploadPath = "http://139.199.98.175:2099/wfTaskImage/";
String newName = "";
String oldName = "";
List<FireTaskPhoto> fireTaskPhotos = new ArrayList<>();
for(MultipartFile file : files){
//获取file图片名称
oldName = file.getOriginalFilename();
//找到 . 的位置
int index = oldName.lastIndexOf(".");
//根据 . 的位置进行分割拿到文件后缀名
String suffix = oldName.substring(index);
//uuid生成新的文件名
newName = UUID.randomUUID().toString() + suffix;
//将图片保存到本地/usr/etc/images/Folder
File file1 = new File("/home/web/wf-fire-service/wfTaskImage/");
//File file1 = new File("E:/wfTaskImage/");
if (!file1.exists()) {
file1.mkdirs();
}
String path = "/home/web/wf-fire-service/wfTaskImage/" + newName;
//String path = "E:/wfTaskImage/" + newName;
String uploadPaths = uploadPath + newName;
//实现上传
file.transferTo(new File(path));
FireTaskPhoto fireTaskPhoto = new FireTaskPhoto();
fireTaskPhoto.setPhotoFireCode(fireCode);
fireTaskPhoto.setTaskPhoto(uploadPaths);
fireTaskPhotos.add(fireTaskPhoto);
}
return fireTaskPhotos;
}*/
/**
* 删除本地或服务器储存的图片
* @param path
* @return
*/
public static String delFile(String path){
String resultInfo = null;
int lastIndexOf = path.lastIndexOf("/");
String imgPath = path.substring(lastIndexOf + 1,path.length());
System.out.println(imgPath);
imgPath = "/usr/local/etc/images/" + imgPath;
// img_path = "/usr/etc/images/Folder/" + img_path;
File file = new File(imgPath);
if(file.exists()){
if(file.delete()){
resultInfo = "删除成功!";
}else {
resultInfo = "删除失败!";
}
}else {
resultInfo = "文件不存在";
}
return resultInfo;
}
/**
* 通过图片路径解析 上传保存
* @param listImgSrc
* @return
*/
public static List downloadImage(List<String> listImgSrc) {
try {
List list = new ArrayList();
//开始时间
Date beginDate = new Date();
for (String url : listImgSrc) {
//开始时间
Date beginDate2 = new Date();
String imageName = url.substring(url.lastIndexOf("/") + 1, url.length());
URL uri = new URL(url);
InputStream in = uri.openStream();
//String pathUpload = "E:/img/" + imageName;
String pathUpload = "/home/web/wf-fire-service/wfimage/" + imageName;
FileOutputStream fo = new FileOutputStream(new File(pathUpload));
byte[] buf = new byte[1024];
int length = 0;
log.info("-------开始下载:" + url);
while ((length = in.read(buf, 0, buf.length)) != -1) {
fo.write(buf, 0, length);
}
in.close();
fo.close();
list.add(imageName);
log.info(imageName + "------下载完成");
//结束时间
Date overDate2 = new Date();
double time = overDate2.getTime() - beginDate2.getTime();
log.info("-----耗时:" + time / 1000 + "s");
}
Date overDate = new Date();
double time = overDate.getTime() - beginDate.getTime();
log.info("======总耗时:" + time / 1000 + "s");
return list;
} catch (Exception e) {
log.info("++++++下载失败");
}
return null;
}
/**
* 删除本地文件夹图片
* @param url
*/
public static void deleteImage(String url){
File file=new File(url);
//判断file是否是文件目录 若是返回TRUE
if (file.isDirectory()){
//name存储file文件夹中的文件名
String[] name =file.list();
for (int i=0; i<name.length; i++){
//此时就可得到文件夹中的文件
File f=new File(url, name[i]);
//删除文件
f.delete();
}
}
}
}

View File

@ -0,0 +1,48 @@
package com.xkrs.utils;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
/**
* @author XinYi Song
*/
@Component
public class Query {
/*@Resource
private ProjectOverviewDao projectOverviewDao;*/
/**
* 动态多条件查询项目信息
* @param
* @return
*/
/*public List<ProjectOverview> selectProjectByDynamic(String projectNumber, String projectName) {
Specification<ProjectOverview> specification = new Specification<ProjectOverview>() {
@Override
public Predicate toPredicate(Root<ProjectOverview> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> list = new ArrayList<>();
if (projectNumber != null && !"".equals(projectNumber)) {
list.add(criteriaBuilder.equal(root.get("projectNumber").as(String.class), projectNumber));
}
if (projectName != null && !"".equals(projectName)) {
list.add(criteriaBuilder.like(root.get("projectName").as(String.class), "%" + projectName + "%"));
}
Predicate[] predicates = new Predicate[list.size()];
return criteriaBuilder.and(list.toArray(predicates));
}
};
return projectOverviewDao.findAll(specification);
}*/
}

View File

@ -0,0 +1,62 @@
package com.xkrs.utils;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 随机字符串产生工具
* @author tajochen
*/
public class RandomUtil {
/**
* 获取随机字母数字组合
* @param length
* 字符串长度
* @return
*/
public static String getRandomCharAndNumr(Integer length) {
String str = "";
StringBuilder strBuffer = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
boolean b = random.nextBoolean();
// 字符串
if (b) {
//取得65大写字母还是97小写字母
int choice = random.nextBoolean() ? 65 : 97;
strBuffer.append((char) (choice + random.nextInt(26)));
} else {
// 数字
strBuffer.append(random.nextInt(10));
}
}
str = strBuffer.toString();
return str;
}
/**
* 验证随机字母数字组合是否纯数字与纯字母
* @param str
* @return true false
*/
public static boolean isRandomUsable(String str) {
// String regExp =
// "^[A-Za-z]+(([0-9]+[A-Za-z0-9]+)|([A-Za-z0-9]+[0-9]+))|[0-9]+(([A-Za-z]+[A-Za-z0-9]+)|([A-Za-z0-9]+[A-Za-z]+))$";
String regExp = "^([0-9]+)|([A-Za-z]+)$";
Pattern pat = Pattern.compile(regExp);
Matcher mat = pat.matcher(str);
return mat.matches();
}
/**
* 生成UUID
* @return
*/
public static String getUuid32(){
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
return uuid;
//  return UUID.randomUUID().toString().replace("-", "").toLowerCase();
}
}

View File

@ -0,0 +1,260 @@
package com.xkrs.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xkrs.model.vo.FileServerResultVo;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* 上传工具
* @author tajochen
**/
public class RequestUtil {
/**
* 发送管理命令到文件服务器
* @param url
* @param map
* @return
*/
public static FileServerResultVo postFileManage(String url, Map<String,String> map){
Logger log = LoggerFactory.getLogger(RequestUtil.class);
String body = "";
// 创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
// 创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
// 装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(map!=null){
for (Map.Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
// 设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
// 设置header报文头信息
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0");
httpPost.setHeader("Accept", "application");
httpPost.setHeader("Accept-Encoding", "gzip, deflate");
// 执行请求操作并拿到结果同步阻塞
CloseableHttpResponse response = client.execute(httpPost);
// 获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
// 释放链接
response.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
FileServerResultVo fileServerResultVo = new FileServerResultVo();
ObjectMapper mapper = new ObjectMapper();
try {
fileServerResultVo = mapper.readValue(body, FileServerResultVo.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
log.warn(e.toString());
}
return fileServerResultVo;
}
/**
* 模拟 get请求
* @param url 链接
* @param map 参数列表
*/
public static void getStandard(String url, Map<String,String> map) {
// 1.拿到一个httpclient的对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2.设置请求方式和请求信息
HttpPost httpPost = new HttpPost(url);
//2.1 提交header头信息
httpPost.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
//2.1 提交请求体
ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
// 装填参数
if(map!=null){
for (Map.Entry<String, String> entry : map.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 3.执行请求
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
// 4.获取返回值
String html = null;
try {
assert response != null;
html = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
// 5.打印
System.out.println(html);
}
/**
* 模拟Post请求 application/x-www-form-urlencoded
* @param url 资源地址
* @param map 参数列表
* @return
*/
public static String postStandard(String url, Map<String,String> map) {
String body = "";
// 创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
// 创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
// 装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(map!=null){
for (Map.Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
// 设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
// 设置header报文头信息
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0");
httpPost.setHeader("Accept", "application");
httpPost.setHeader("Accept-Encoding", "gzip, deflate");
// 执行请求操作并拿到结果同步阻塞
CloseableHttpResponse response = client.execute(httpPost);
// 获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
// 释放链接
response.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return body;
}
/**
* 模拟Post请求 multipart/form-data
* @param postFile
* @param postUrl
* @param postParam
* @return
*/
public static Map<String,Object> postFile(File postFile,String postUrl,Map<String,String> postParam) {
Logger log = LoggerFactory.getLogger(RequestUtil.class);
Map<String,Object> resultMap = new HashMap<String,Object>(16);
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
// 把一个普通参数和文件上传给下面这个地址
HttpPost httpPost = new HttpPost(postUrl);
// 设置传输参数
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
// 解决乱码问题
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.setCharset(StandardCharsets.UTF_8);
// 设置文件参数 获取文件名postFile.getName()
// 把文件转换成流对象FileBody
multipartEntity.addBinaryBody("file",postFile, ContentType.create("multipart/form-data", Consts.UTF_8),postFile.getName());
// 设计文件以外的参数
Set<String> keySet = postParam.keySet();
for (String key : keySet) {
// 相当于<input type="text" name="name" value=name>
multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("multipart/form-data", Consts.UTF_8)));
}
HttpEntity reqEntity = multipartEntity.build();
httpPost.setEntity(reqEntity);
// 设置header报文头信息
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0");
httpPost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Accept-Encoding","gzip, deflate");
// 发起请求返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
resultMap.put("statusCode", response.getStatusLine().getStatusCode());
// 获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
// 打印响应内容
resultMap.put("data", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
resultMap.put("message", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
resultMap.put("status", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
}
// 销毁
EntityUtils.consume(resEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
response.close();
}
} catch (IOException e1) {
e1.printStackTrace();
} finally{
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("上传结果:" + resultMap);
return resultMap;
}
}

View File

@ -0,0 +1,124 @@
package com.xkrs.utils;
/**
* 基于Twitter开源的分布式ID生成算法snowflake
* @author tajochen
**/
public class SnowFlakeUtil {
/**
* 起始时间戳
* 2018-01-01 00:00:00
*/
private final static long START_STMP = 1514736000L;
/**
* 序列在id中占用的位数
*/
private final static long SEQUENCE_BIT = 12L;
/**
* 机器标识占用的位数
*/
private final static long MACHINE_BIT = 5L;
/**
* 数据中心占用的位数
*/
private final static long DATACENTER_BIT = 5L;
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
/**
* 数据中心
*/
private long datacenterId;
/**
* 机器标识
*/
private long machineId;
/**
* 序列号
*/
private long sequence = 0L;
/**
* 上一次时间戳
*/
private long lastStmp = -1L;
public SnowFlakeUtil(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("data center id can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machine id can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
/**
* 产生下一个ID
* @return
*/
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
//相同毫秒内序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
//不同毫秒内序列号置为0
sequence = 0L;
}
lastStmp = currStmp;
//时间戳部分
return (currStmp - START_STMP) << TIMESTMP_LEFT
//数据中心部分
| datacenterId << DATACENTER_LEFT
//机器标识部分
| machineId << MACHINE_LEFT
//序列号部分
| sequence;
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
public static void main(String[] args) {
SnowFlakeUtil snowFlake = new SnowFlakeUtil(5, 5);
//测试次数
int testTimes = 10000;
long start = System.currentTimeMillis();
for (int i = 0; i < testTimes; i++) {
System.out.println(snowFlake.nextId());
}
System.out.println(System.currentTimeMillis() - start);
}
}

View File

@ -0,0 +1,62 @@
server.port = 6466
## 数据源配置
spring.datasource.url = jdbc:postgresql://192.168.2.9:5432/fire_point
spring.datasource.userName = fire_point
spring.datasource.password = fire_point123
spring.datasource.driverClassName = org.postgresql.Driver
server.tomcat.uri-encoding=UTF-8
# 关闭spring data 的redis仓库
spring.data.redis.repositories.enabled = false
# jackson 配置
spring.jackson.serialization.write-date-keys-as-timestamps=false
## Hikari连接池设置
spring.datasource.hikari.auto-commit = true
spring.datasource.hikari.maximum-pool-size = 100
spring.datasource.hikari.idle-timeout = 10000
spring.datasource.hikari.minimum-idle = 5
spring.datasource.hikari.validation-timeout = 3000
## Spring Data JPA 配置
spring.jpa.database = POSTGRESQL
spring.jpa.database-platform = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql = false
# 指定 ddl mode (none, validate, create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# 命名策略
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL95Dialect
#spring.jpa.properties.hibernate.dialect = org.hibernate.spatial.dialect.postgis.PostgisDialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
## Devtools配置
spring.devtools.livereload.enabled = true
## 多国语言配置
spring.messages.basename = i18n/messages
spring.messages.encoding = UTF-8
# 上传文件配置
spring.servlet.multipart.enabled=true
# 最大文件大小
spring.servlet.multipart.max-file-size = 64MB
# 最大请求大小
spring.servlet.multipart.max-request-size = 70MB
# Geoserver服务器地址
my.GeoserverAdress = http://139.199.98.175:9080/geoserver/
# 文件服务器地址
my.FileServerAdress = http://139.199.98.175:4096/
my.FileServerAdminAdress = http://127.0.0.1:4096/
## 自定义用户最大登录错误尝试次数
my.MaxLoginErrorCount = 5
## 自定义用户登录错误间隔时间(分钟)
my.LoginErrorIntervalTime = 60

View File

@ -0,0 +1,162 @@
sys.message.success = 成功
sys.message.null = 暂时还没有数据
sys.message.exit = 已存在相关内容,请勿重复操作
sys.message.user.not_logged_in = 用户未登录
sys.message.user.login_error = 用户登陆失败
sys.message.user.account_forbidden = 用户已被禁止
sys.message.user.account_not_activated = 用户未激活
sys.message.user.overtime = 用户登录超时
sys.message.user.no_permission = 用户权限不足
sys.message.user.already_logged = 用户已经登录
sys.message.param.null = 参数为空
sys.message.param.illegal = 参数非法
sys.message.data.none = 数据为空
sys.message.data.wrong = 数据错误
sys.message.process.fail = 处理失败
sys.message.process.overtime = 处理超时
sys.message.system.inner_error = 系统内部错误
sys.message.system.abnormal = 系统异常
sys.message.system.busy = 系统正忙,请稍后
sys.message.system.maintain = 系统维护中
sys.message.database.error = 数据库错误
sys.message.file.exists = 文件已存在
sys.message.file.write.error = 文件写入失败
sys.message.file.read.error = 文件读取失败
SysUser.id.blank = 用户id不能为空
SysUser.userName.blank = 用户名不能为空
SysUser.userName.length.illegal = 用户名长度不合法
SysUser.userName.format.illegal = 用户名格式不合法
SysUser.nickName.length.illegal = 用户昵称长度不合法
SysUser.userCode.length.illegal = 用户编码长度不合法
SysUser.userCode.format.illegal = 用户编码含有非法字符
SysUser.password.blank = 用户密码不能为空
SysUser.password.length.illegal = 用户密码长度不合法
SysUser.password.format.illegal = 用户密码格式不合法
SysUser.sex.num.null = 用户性别数字不能为空
SysUser.sex.num.illegal = 用户性别数字不合法
SysUser.telephone.format.illegal = 用户手机号码不合法
SysUser.email.length.illegal = 用户邮箱长度不合法
SysUser.email.format.illegal = 用户邮箱格式不合法
SysUser.admCode.illegal = 用户行政区划代码不合法
SysUser.address.length.illegal = 用户详细地址长度不合法
SysUser.birthday.format.illegal = 用户出生日期必须是 yyyy-MM-dd
SysUser.personalSignature.length.illegal = 用户个性签名长度非法
SysUser.portraitId.illegal = 用户头像id非法
SysUser.statusCode.null = 用户当前状态编码为空
SysUser.statusCode.illegal = 用户当前状态编码非法
SysUser.deleteFlag.null = 用户删除标记不能是空
TrajectoryRecord.id.null = id 不能为空
TrajectoryRecord.startTimeTs.null = startTimeTs 不能为空
SatelliteFirePoint.id.null = id 不能为空
SatelliteFirePoint.fireCode.null = fireCode 不能为空
SatelliteFirePoint.fireCode.length.illegal = fireCode 长度过长
SatelliteFirePoint.countyCode.null = countyCode 不能为空
SatelliteFirePoint.countyCode.length.illegal = countyCode 长度过长
SatelliteFirePoint.countyName.null = countyName 不能为空
SatelliteFirePoint.countyName.length.illegal = countyName 长度过长
SatelliteFirePoint.satelliteType.null = satelliteType 不能为空
SatelliteFirePoint.fireStatus.null = fireStatus 不能为空
SatelliteFirePoint.verifyStatus.null = verifyStatus 不能为空
SatelliteFirePoint.satelliteTimeTs.null = satelliteTimeTs 不能为空
PictureFirePoint.id.null = id 不能为空
PictureFirePoint.fireCode.null = fireCode 不能为空
PictureFirePoint.fireCode.length.illegal = fireCode 长度过长
PictureFirePoint.pictureName.length.illegal = pictureName 长度过长
PictureFirePoint.picturePath.null = picturePath 不能为空
PictureFirePoint.picturePath.length.illegal = picturePath 长度过长
PictureFirePoint.memo.length.illegal = memo 长度过长
PictureFirePoint.size.length.illegal = size 长度过长
PictureFirePoint.md5.null = md5 不能为空
PictureFirePoint.md5.length.illegal = md5 长度过长
PictureFirePoint.shootTimeTs.null = shootTimeTs 不能为空
PersonInvestigator.id.null = id 不能为空
PersonInvestigator.name.null = name 不能为空
PersonInvestigator.name.length.illegal = name 长度过长
PersonInvestigator.code.length.illegal = code 长度过长
PersonInvestigator.telephone.null = telephone 不能为空
PersonInvestigator.telephone.format.illegal = telephone 格式非法
PersonInvestigator.sex.null = sex 不能为空
PersonInvestigator.sex.format.illegal = sex 格式非法
PersonInvestigator.idCard.length.illegal = idCard 长度过长
PersonInvestigator.memo.length.illegal = memo 长度过长
PersonInvestigator.linkUserName.null = linkUserName 不能为空
PersonInvestigator.linkUserName.format.illegal = linkUserName 格式非法
PersonInvestigator.password.null = password 不能为空
PersonInvestigator.password.format.illegal = password 格式非法
InvestigateFirePoint.verifyTimeTs.null = verifyTimeTs 不能为空
InvestigateFirePoint.id.null = id 不能为空
InvestigateFirePoint.fireCode.null = fireCode 不能为空
InvestigateFirePoint.fireCode.length.illegal = fireCode 长度过长
InvestigateFirePoint.countyCode.null = countyCode 不能为空
InvestigateFirePoint.countyCode.length.illegal = countyCode 长度过长
InvestigateFirePoint.countyName.null = countyName 不能为空
InvestigateFirePoint.countyName.length.illegal = countyName 长度过长
InvestigateFirePoint.address.null = address 不能为空
InvestigateFirePoint.fireArea.null = fireArea 不能为空
InvestigateFirePoint.verifyType.null = verifyType 不能为空
InvestigateFirePoint.satelliteType.null = satelliteType 不能为空
InvestigateFirePoint.satelliteType.length.illegal = satelliteType 长度过长
FileDocument.id.null = id 不能为空
FileDocument.name.null = name 不能为空
FileDocument.name.length.illegal = name 长度过长
FileDocument.category.length.illegal = category 长度过长
FileDocument.filePath.null = filePath 不能为空
FileDocument.filePath.length.illegal = filePath 长度过长
FileDocument.size.length.illegal = size 长度过长
FileDocument.md5.null = md5 不能为空
FileDocument.md5.length.illegal = md5 长度过长
FileDocument.memo.length.illegal = memo 长度过长
FileDocument.checkingToken.length.illegal = checkingToken 长度过长
AppFile.id.null = id 不能为空
AppFile.name.null = name 不能为空
AppFile.name.length.illegal = name 长度过长
AppFile.appPath.null = appPath 不能为空
AppFile.appPath.length.illegal = appPath 长度过长
AppFile.versionNumber.null = versionNumber 不能为空
AppFile.versionNumber.length.illegal = versionNumber 长度过长
AppFile.versionNumber.format.illegal = versionNumber 格式不合法
AppFile.size.null = size 不能为空
AppFile.size.length.illegal = size 长度过长
AppFile.md5.null = md5 不能为空
AppFile.md5.length.illegal = md5 长度过长
AppFile.memo.length.illegal = memo 长度过长
RealFirePoint.id.null = id 不能为空
RealFirePoint.fireCode.null = fireCode 不能为空
RealFirePoint.fireCode.length.illegal = fireCode 不合法
RealFirePoint.countyCode.null = countyCode 不能为空
RealFirePoint.countyCode.length.illegal = countyCode 不合法
RealFirePoint.countyName.null = countyName 不能为空
RealFirePoint.countyName.length.illegal = countyName 不合法
RealFirePoint.address.null = address 不能为空
RealFirePoint.address.length.illegal = address 不合法
RealFirePoint.fireArea.null = fireArea 不能为空
RealFirePoint.verifyTimeTs.null = verifyTimeTs 不能为空
RealFirePoint.verifyType.null = verifyType 不能为空
InvestigationTeam.id.null = id 不能为空
InvestigationTeam.teamName.null = teamName 不能为空
InvestigationTeam.teamName.length.illegal = teamName 长度过长
InvestigationTeam.memo.length.illegal = memo 长度过长
InvestigationTeam.userName.null = userName 不能为空
InvestigationTeam.userName.length.illegal = userName 长度过长
InvestigationTeam.userRealName.null = userRealName 不能为空
InvestigationTeam.userRealName.length.illegal = userRealName 长度过长
RelTeamInvestigator.id.null = id 不能为空
RelTeamInvestigator.teamCode.null = teamCode 不能为空
RelTeamInvestigator.teamCode.length.illegal = teamCode 长度过长
RelTeamInvestigator.userName.null = userName 不能为空
RelTeamInvestigator.userName.length.illegal = userName 长度过长
RelTeamInvestigator.teamDeputy.null = teamDeputy 不能为空
RelTeamInvestigator.memo.length.illegal = memo 长度过长
RelTeamInvestigator.userRealName.null = userRealName 不能为空
RelTeamInvestigator.userRealName.length.illegal = userRealName 长度过长

View File

@ -0,0 +1,162 @@
sys.message.success = success
sys.message.null = null
sys.message.exit = data already exists
sys.message.user.not_logged_in = user not logged in
sys.message.user.login_error = user login failed
sys.message.user.account_forbidden = this account is forbidden
sys.message.user.account_not_activated = this account not activated
sys.message.user.overtime = user login timeout
sys.message.user.no_permission = user permission denied
sys.message.user.already_logged = user already logged
sys.message.param.null = parameter is null
sys.message.param.illegal = parameter is illegal
sys.message.data.none = data is none
sys.message.data.wrong = data is wrong
sys.message.process.fail = process fail
sys.message.process.overtime = process overtime
sys.message.system.inner_error = system inner error
sys.message.system.abnormal = system abnormal
sys.message.system.busy = system is busy
sys.message.system.maintain = system maintenance
sys.message.database.error = database error
sys.message.file.exists = file exists
sys.message.file.write.error = file write error
sys.message.file.read.error = file read error
SysUser.id.blank = user id can't be blank
SysUser.userName.blank = user name can't be blank
SysUser.userName.length.illegal = user name length illegal
SysUser.userName.format.illegal = user name format illegal
SysUser.nickName.length.illegal = user nickname length illegal
SysUser.userCode.length.illegal = user code length illegal
SysUser.userCode.format.illegal = user code cantains illegal character
SysUser.password.blank = user password can't be blank
SysUser.password.length.illegal = user password length illegal
SysUser.password.format.illegal = user password format illegal
SysUser.sex.num.null = user sex num can't be blank
SysUser.sex.num.illegal = user sex num illegal
SysUser.telephone.format.illegal = user telephone format illegal
SysUser.email.length.illegal = user email length illegal
SysUser.email.format.illegal = user email format illegal
SysUser.admCode.illegal = user administrative area code illegal
SysUser.address.length.illegal = user address length illegal
SysUser.birthday.format.illegal = user birthday must be yyyy-MM-dd
SysUser.personalSignature.length.illegal = user personal signature length illegal
SysUser.portraitId.illegal = user portrait id illegal
SysUser.statusCode.null = user current status code can't be blank
SysUser.statusCode.illegal = user current status code illegal
SysUser.deleteFlag.null = user delete flag can't be null
TrajectoryRecord.id.null = id can't be null
TrajectoryRecord.startTimeTs.null = startTimeTs can't be null
SatelliteFirePoint.id.null = id can't be blank
SatelliteFirePoint.fireCode.null = fireCode can't be blank
SatelliteFirePoint.fireCode.length.illegal = fireCode length illegal
SatelliteFirePoint.countyCode.null = countyCode can't be blank
SatelliteFirePoint.countyCode.length.illegal = countyCode length illegal
SatelliteFirePoint.countyName.null = countyName can't be blank
SatelliteFirePoint.countyName.length.illegal = countyName length illegal
SatelliteFirePoint.satelliteType.null = satelliteType can't be blank
SatelliteFirePoint.fireStatus.null = fireStatus can't be blank
SatelliteFirePoint.verifyStatus.null = verifyStatus can't be blank
SatelliteFirePoint.satelliteTimeTs.null = satelliteTimeTs can't be blank
PictureFirePoint.id.null = id can't be blank
PictureFirePoint.fireCode.null = fireCode can't be blank
PictureFirePoint.fireCode.length.illegal = fireCode length illegal
PictureFirePoint.pictureName.length.illegal = pictureName length illegal
PictureFirePoint.picturePath.null = picturePath can't be blank
PictureFirePoint.picturePath.length.illegal = picturePath length illegal
PictureFirePoint.memo.length.illegal = memo length illegal
PictureFirePoint.size.length.illegal = size length illegal
PictureFirePoint.md5.null = md5 can't be blank
PictureFirePoint.md5.length.illegal = md5 length illegal
PictureFirePoint.shootTimeTs.null = shootTimeTs can't be blank
PersonInvestigator.id.null = id can't be blank
PersonInvestigator.name.null = name can't be blank
PersonInvestigator.name.length.illegal = name length illegal
PersonInvestigator.code.length.illegal = code length illegal
PersonInvestigator.telephone.null = telephone can't be blank
PersonInvestigator.telephone.format.illegal = telephone format illegal
PersonInvestigator.sex.null = sex format can't be blank
PersonInvestigator.sex.format.illegal = sex format illegal
PersonInvestigator.idCard.length.illegal = idCard length illegal
PersonInvestigator.memo.length.illegal = memo length illegal
PersonInvestigator.linkUserName.null = linkUserName can't be blank
PersonInvestigator.linkUserName.format.illegal = linkUserName format illegal
PersonInvestigator.password.null = password can't be blank
PersonInvestigator.password.format.illegal = password format
InvestigateFirePoint.verifyTimeTs.null = verifyTimeTs can't be blank
InvestigateFirePoint.id.null = id can't be blank
InvestigateFirePoint.fireCode.null = fireCode can't be blank
InvestigateFirePoint.fireCode.length.illegal = fireCode length illegal
InvestigateFirePoint.countyCode.null = countyCode can't be blank
InvestigateFirePoint.countyCode.length.illegal = countyCode length illegal
InvestigateFirePoint.countyName.null = countyName can't be blank
InvestigateFirePoint.countyName.length.illegal = countyName length illegal
InvestigateFirePoint.address.null = address can't be blank
InvestigateFirePoint.fireArea.null = fireArea can't be blank
InvestigateFirePoint.verifyType.null = verifyType can't be blank
InvestigateFirePoint.satelliteType.null = satelliteType can't be blank
InvestigateFirePoint.satelliteType.length.illegal = satelliteType length illegal
FileDocument.id.null = id can't be blank
FileDocument.name.null = name can't be blank
FileDocument.name.length.illegal = name length illegal
FileDocument.category.length.illegal = category length illegal
FileDocument.filePath.null = filePath can't be blank
FileDocument.filePath.length.illegal = filePath length illegal
FileDocument.size.length.illegal = size length illegal
FileDocument.md5.null = md5 can't be blank
FileDocument.md5.length.illegal = md5 length illegal
FileDocument.memo.length.illegal = memo length illegal
FileDocument.checkingToken.length.illegal = checkingToken length illegal
AppFile.id.null = id can't be blank
AppFile.name.null = name can't be blank
AppFile.name.length.illegal = name length illegal
AppFile.appPath.null = appPath can't be blank
AppFile.appPath.length.illegal = appPath length illegal
AppFile.versionNumber.null = versionNumber can't be blank
AppFile.versionNumber.length.illegal = versionNumber length illegal
AppFile.versionNumber.format.illegal = versionNumber illegal
AppFile.size.null = size can't be blank
AppFile.size.length.illegal = size length illegal
AppFile.md5.null = md5 can't be blank
AppFile.md5.length.illegal = md5 length illegal
AppFile.memo.length.illegal = memo length illegal
RealFirePoint.id.null = id can't be blank
RealFirePoint.fireCode.null = fireCode can't be blank
RealFirePoint.fireCode.length.illegal = fireCode illegal
RealFirePoint.countyCode.null = countyCode can't be blank
RealFirePoint.countyCode.length.illegal = countyCode
RealFirePoint.countyName.null = countyName can't be blank
RealFirePoint.countyName.length.illegal = countyName illegal
RealFirePoint.address.null = address can't be blank
RealFirePoint.address.length.illegal = address illegal
RealFirePoint.fireArea.null = fireArea can't be blank
RealFirePoint.verifyTimeTs.null = verifyTimeTs can't be blank
RealFirePoint.verifyType.null = verifyType can't be blank
InvestigationTeam.id.null = id can't be blank
InvestigationTeam.teamName.null = teamName can't be blank
InvestigationTeam.teamName.length.illegal = teamName length illegal
InvestigationTeam.memo.length.illegal = memo length illegal
InvestigationTeam.userName.null = userName can't be blank
InvestigationTeam.userName.length.illegal = userName length illegal
InvestigationTeam.userRealName.null = userRealName can't be blank
InvestigationTeam.userRealName.length.illegal = userRealName length illegal
RelTeamInvestigator.id.null = id can't be blank
RelTeamInvestigator.teamCode.null = teamCode can't be blank
RelTeamInvestigator.teamCode.length.illegal = teamCode length illegal
RelTeamInvestigator.userName.null = userName can't be blank
RelTeamInvestigator.userName.length.illegal = userName length illegal
RelTeamInvestigator.teamDeputy.null = teamDeputy can't be blank
RelTeamInvestigator.memo.length.illegal = memo length illegal
RelTeamInvestigator.userRealName.null = userRealName can't be blank
RelTeamInvestigator.userRealName.length.illegal = userRealName length illegal

View File

@ -0,0 +1,162 @@
sys.message.success = 成功
sys.message.null = 暂时还没有数据
sys.message.exit = 已存在相关内容,请勿重复操作
sys.message.user.not_logged_in = 用户未登录
sys.message.user.login_error = 用户登陆失败
sys.message.user.account_forbidden = 用户已被禁止
sys.message.user.account_not_activated = 用户未激活
sys.message.user.overtime = 用户登录超时
sys.message.user.no_permission = 用户权限不足
sys.message.user.already_logged = 用户已经登录
sys.message.param.null = 参数为空
sys.message.param.illegal = 参数非法
sys.message.data.none = 数据为空
sys.message.data.wrong = 数据错误
sys.message.process.fail = 处理失败
sys.message.process.overtime = 处理超时
sys.message.system.inner_error = 系统内部错误
sys.message.system.abnormal = 系统异常
sys.message.system.busy = 系统正忙,请稍后
sys.message.system.maintain = 系统维护中
sys.message.database.error = 数据库错误
sys.message.file.exists = 文件已存在
sys.message.file.write.error = 文件写入失败
sys.message.file.read.error = 文件读取失败
SysUser.id.blank = 用户id不能为空
SysUser.userName.blank = 用户名不能为空
SysUser.userName.length.illegal = 用户名长度不合法
SysUser.userName.format.illegal = 用户名格式不合法
SysUser.nickName.length.illegal = 用户昵称长度不合法
SysUser.userCode.length.illegal = 用户编码长度不合法
SysUser.userCode.format.illegal = 用户编码含有非法字符
SysUser.password.blank = 用户密码不能为空
SysUser.password.length.illegal = 用户密码长度不合法
SysUser.password.format.illegal = 用户密码格式不合法
SysUser.sex.num.null = 用户性别数字不能为空
SysUser.sex.num.illegal = 用户性别数字不合法
SysUser.telephone.format.illegal = 用户手机号码不合法
SysUser.email.length.illegal = 用户邮箱长度不合法
SysUser.email.format.illegal = 用户邮箱格式不合法
SysUser.admCode.illegal = 用户行政区划代码不合法
SysUser.address.length.illegal = 用户详细地址长度不合法
SysUser.birthday.format.illegal = 用户出生日期必须是 yyyy-MM-dd
SysUser.personalSignature.length.illegal = 用户个性签名长度非法
SysUser.portraitId.illegal = 用户头像id非法
SysUser.statusCode.null = 用户当前状态编码为空
SysUser.statusCode.illegal = 用户当前状态编码非法
SysUser.deleteFlag.null = 用户删除标记不能是空
TrajectoryRecord.id.null = id 不能为空
TrajectoryRecord.startTimeTs.null = startTimeTs 不能为空
SatelliteFirePoint.id.null = id 不能为空
SatelliteFirePoint.fireCode.null = fireCode 不能为空
SatelliteFirePoint.fireCode.length.illegal = fireCode 长度过长
SatelliteFirePoint.countyCode.null = countyCode 不能为空
SatelliteFirePoint.countyCode.length.illegal = countyCode 长度过长
SatelliteFirePoint.countyName.null = countyName 不能为空
SatelliteFirePoint.countyName.length.illegal = countyName 长度过长
SatelliteFirePoint.satelliteType.null = satelliteType 不能为空
SatelliteFirePoint.fireStatus.null = fireStatus 不能为空
SatelliteFirePoint.verifyStatus.null = verifyStatus 不能为空
SatelliteFirePoint.satelliteTimeTs.null = satelliteTimeTs 不能为空
PictureFirePoint.id.null = id 不能为空
PictureFirePoint.fireCode.null = fireCode 不能为空
PictureFirePoint.fireCode.length.illegal = fireCode 长度过长
PictureFirePoint.pictureName.length.illegal = pictureName 长度过长
PictureFirePoint.picturePath.null = picturePath 不能为空
PictureFirePoint.picturePath.length.illegal = picturePath 长度过长
PictureFirePoint.memo.length.illegal = memo 长度过长
PictureFirePoint.size.length.illegal = size 长度过长
PictureFirePoint.md5.null = md5 不能为空
PictureFirePoint.md5.length.illegal = md5 长度过长
PictureFirePoint.shootTimeTs.null = shootTimeTs 不能为空
PersonInvestigator.id.null = id 不能为空
PersonInvestigator.name.null = name 不能为空
PersonInvestigator.name.length.illegal = name 长度过长
PersonInvestigator.code.length.illegal = code 长度过长
PersonInvestigator.telephone.null = telephone 不能为空
PersonInvestigator.telephone.format.illegal = telephone 格式非法
PersonInvestigator.sex.null = sex 不能为空
PersonInvestigator.sex.format.illegal = sex 格式非法
PersonInvestigator.idCard.length.illegal = idCard 长度过长
PersonInvestigator.memo.length.illegal = memo 长度过长
PersonInvestigator.linkUserName.null = linkUserName 不能为空
PersonInvestigator.linkUserName.format.illegal = linkUserName 格式非法
PersonInvestigator.password.null = password 不能为空
PersonInvestigator.password.format.illegal = password 格式非法
InvestigateFirePoint.verifyTimeTs.null = verifyTimeTs 不能为空
InvestigateFirePoint.id.null = id 不能为空
InvestigateFirePoint.fireCode.null = fireCode 不能为空
InvestigateFirePoint.fireCode.length.illegal = fireCode 长度过长
InvestigateFirePoint.countyCode.null = countyCode 不能为空
InvestigateFirePoint.countyCode.length.illegal = countyCode 长度过长
InvestigateFirePoint.countyName.null = countyName 不能为空
InvestigateFirePoint.countyName.length.illegal = countyName 长度过长
InvestigateFirePoint.address.null = address 不能为空
InvestigateFirePoint.fireArea.null = fireArea 不能为空
InvestigateFirePoint.verifyType.null = verifyType 不能为空
InvestigateFirePoint.satelliteType.null = satelliteType 不能为空
InvestigateFirePoint.satelliteType.length.illegal = satelliteType 长度过长
FileDocument.id.null = id 不能为空
FileDocument.name.null = name 不能为空
FileDocument.name.length.illegal = name 长度过长
FileDocument.category.length.illegal = category 长度过长
FileDocument.filePath.null = filePath 不能为空
FileDocument.filePath.length.illegal = filePath 长度过长
FileDocument.size.length.illegal = size 长度过长
FileDocument.md5.null = md5 不能为空
FileDocument.md5.length.illegal = md5 长度过长
FileDocument.memo.length.illegal = memo 长度过长
FileDocument.checkingToken.length.illegal = checkingToken 长度过长
AppFile.id.null = id 不能为空
AppFile.name.null = name 不能为空
AppFile.name.length.illegal = name 长度过长
AppFile.appPath.null = appPath 不能为空
AppFile.appPath.length.illegal = appPath 长度过长
AppFile.versionNumber.null = versionNumber 不能为空
AppFile.versionNumber.length.illegal = versionNumber 长度过长
AppFile.versionNumber.format.illegal = versionNumber 格式不合法
AppFile.size.null = size 不能为空
AppFile.size.length.illegal = size 长度过长
AppFile.md5.null = md5 不能为空
AppFile.md5.length.illegal = md5 长度过长
AppFile.memo.length.illegal = memo 长度过长
RealFirePoint.id.null = id 不能为空
RealFirePoint.fireCode.null = fireCode 不能为空
RealFirePoint.fireCode.length.illegal = fireCode 不合法
RealFirePoint.countyCode.null = countyCode 不能为空
RealFirePoint.countyCode.length.illegal = countyCode 不合法
RealFirePoint.countyName.null = countyName 不能为空
RealFirePoint.countyName.length.illegal = countyName 不合法
RealFirePoint.address.null = address 不能为空
RealFirePoint.address.length.illegal = address 不合法
RealFirePoint.fireArea.null = fireArea 不能为空
RealFirePoint.verifyTimeTs.null = verifyTimeTs 不能为空
RealFirePoint.verifyType.null = verifyType 不能为空
InvestigationTeam.id.null = id 不能为空
InvestigationTeam.teamName.null = teamName 不能为空
InvestigationTeam.teamName.length.illegal = teamName 长度过长
InvestigationTeam.memo.length.illegal = memo 长度过长
InvestigationTeam.userName.null = userName 不能为空
InvestigationTeam.userName.length.illegal = userName 长度过长
InvestigationTeam.userRealName.null = userRealName 不能为空
InvestigationTeam.userRealName.length.illegal = userRealName 长度过长
RelTeamInvestigator.id.null = id 不能为空
RelTeamInvestigator.teamCode.null = teamCode 不能为空
RelTeamInvestigator.teamCode.length.illegal = teamCode 长度过长
RelTeamInvestigator.userName.null = userName 不能为空
RelTeamInvestigator.userName.length.illegal = userName 长度过长
RelTeamInvestigator.teamDeputy.null = teamDeputy 不能为空
RelTeamInvestigator.memo.length.illegal = memo 长度过长
RelTeamInvestigator.userRealName.null = userRealName 不能为空
RelTeamInvestigator.userRealName.length.illegal = userRealName 长度过长

View File

@ -0,0 +1,13 @@
package com.xkrs;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FirePointApplicationTests {
@Test
void contextLoads() {
}
}