commit 4b9ebf8c001eb668e9adfdf138ed12506e2cab5e Author: 黄昕 Date: Wed Oct 25 15:01:22 2023 +0800 OCT 1. 初始化仓库 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f2d67c3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +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/ +/logs/ diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..cb28b0e Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..5f0536e --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/assembly.xml b/assembly.xml new file mode 100644 index 0000000..2544339 --- /dev/null +++ b/assembly.xml @@ -0,0 +1,48 @@ + + ${project.version} + + tgz + + + + ${project.build.directory} + ${file.separator} + + BeiDouPlatform.jar + + + + config + ${file.separator}config + + + dist + ${file.separator}dist + + + bin + ${file.separator}bin + + + src/main/resources/ + + + banner.txt + + + ${file.separator} + + + + + lib + compile + + ${groupId}:${artifactId} + + + + \ No newline at end of file diff --git a/config/application-local.properties b/config/application-local.properties new file mode 100644 index 0000000..c00f424 --- /dev/null +++ b/config/application-local.properties @@ -0,0 +1,41 @@ +server.port=9276 +server.servlet.context-path=/tunnel + +# mysql +spring.datasource.url=jdbc:mysql://101.35.234.160:32306/beidou?serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=convertToNull&useUnicode=true +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.datasource.username=cmhi +spring.datasource.password=cmHi10086! + +# SQL Server +#spring.datasource.url=jdbc:sqlserver://localhost:1433;database=BeiDouDataBase;integratedSecurity=true;encrypt=true;trustServerCertificate=true +#spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver +#spring.datasource.username=sa +#spring.datasource.password=sa123456 + +#spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource +spring.datasource.dbcp2.max-total=128 +spring.datasource.dbcp2.max-wait-millis=10000 +spring.datasource.dbcp2.max-idle=32 +spring.datasource.dbcp2.min-idle=8 +spring.datasource.dbcp2.initial-size=8 +spring.datasource.dbcp2.validation-query=SELECT 1 +spring.datasource.dbcp2.test-while-idle=true +spring.datasource.dbcp2.connection-properties=characterEncoding=utf8 + +#mybatis +#mybatis.configuration.map-underscore-to-camel-case: true +mybatis.mapper-locations=classpath*:mappers/*.xml +mybatis.type-aliases-package=com.cmhi.game_database_service.pojo.entry +mybatis.configuration.default-enum-type-handler=com.cmhi.game_database_service.common.CommonEnumHandler +#mybatis.configuration.log-impl=lombok.extern.slf4j.Slf4j + +#pagehelper +pagehelper.helper-dialect=mysql +pagehelper.reasonable=true +pagehelper.support-methods-arguments=true +pagehelper.pageSizeZero=true +pagehelper.params.count=countSql +#config log +logging.config=file:config/logback.xml +log4j.logger.org.mybatis=debug \ No newline at end of file diff --git a/config/application.properties b/config/application.properties new file mode 100644 index 0000000..07f154c --- /dev/null +++ b/config/application.properties @@ -0,0 +1 @@ +spring.profiles.active=local \ No newline at end of file diff --git a/config/logback.xml b/config/logback.xml new file mode 100644 index 0000000..8b68eb2 --- /dev/null +++ b/config/logback.xml @@ -0,0 +1,95 @@ + + + + + + + + + + [%d{yy-MM-dd HH:mm:ss:SSS}][%-5p][%c{0}][%M\(%L\)][%t]: %m%n + + + + + ${LOG_PATH}/biz.log + + ${LOG_PATH}/biz.log.%d{yyyyMMdd} + + + + [%d{yy-MM-dd HH:mm:ss:SSS}][%-5p][%c{0}][%M\(%L\)][%t]: %m%n + + + + ${LOG_PATH}/system.log + + ${LOG_PATH}/system.log.%d{yyyyMMdd} + + + + [%d{yy-MM-dd HH:mm:ss:SSS}][%-5p][%c{0}][%M\(%L\)][%t]: %m%n + + + + + ${LOG_PATH}/data.log + + ${LOG_PATH}/data.log.%d{yyyyMMdd} + + + + [%d{yy-MM-dd HH:mm:ss:SSS}][%-5p][%c{0}][%M\(%L\)][%t]: %m%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..66df285 --- /dev/null +++ b/mvnw @@ -0,0 +1,308 @@ +#!/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# 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 /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + 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 + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -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 "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); 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="$(\unset -f command 2>/dev/null; \command -v 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 + +# 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/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# 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. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +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 "$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 + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,205 @@ +@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 Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@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 "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\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 WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_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 WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_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('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@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 "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\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% + +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..43d0d5b --- /dev/null +++ b/pom.xml @@ -0,0 +1,211 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.5 + + + com.cmhi + game_database_service + 0.0.1-SNAPSHOT + game_database_service + game_database_service + + 21 + + + + org.springframework.boot + spring-boot-starter-jdbc + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + com.mysql + mysql-connector-j + runtime + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.restdocs + spring-restdocs-mockmvc + test + + + org.springframework.boot + spring-boot-starter-undertow + + + org.mybatis + mybatis-spring + 3.0.2 + + + javax.servlet + javax.servlet-api + 4.0.1 + provided + + + org.mybatis + mybatis + 3.5.13 + + + org.hibernate.validator + hibernate-validator + 6.2.3.Final + + + org.jetbrains + annotations + 23.0.0 + compile + + + commons-codec + commons-codec + + + commons-io + commons-io + 1.3.2 + + + jakarta.validation + jakarta.validation-api + 2.0.2 + + + com.github.ulisesbocchio + jasypt-spring-boot + 3.0.4 + + + commons-lang + commons-lang + 2.6 + + + + + GameDatabaseService + + + org.asciidoctor + asciidoctor-maven-plugin + 2.2.1 + + + generate-docs + prepare-package + + process-asciidoc + + + html + book + + + + + + org.springframework.restdocs + spring-restdocs-asciidoctor + ${spring-restdocs.version} + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.cmhi.game_database_service.GameDatabaseServiceApplication + true + lib/ + + + ./ + + + + config/** + templates/** + static/** + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + package + + single + + + + + true + + assembly.xml + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + false + + **/com/cmhi/game_database_service/**/*.java + + + + + + + diff --git a/src/main/java/com/cmhi/game_database_service/GameDatabaseServiceApplication.java b/src/main/java/com/cmhi/game_database_service/GameDatabaseServiceApplication.java new file mode 100644 index 0000000..e2d0f4e --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/GameDatabaseServiceApplication.java @@ -0,0 +1,17 @@ +package com.cmhi.game_database_service; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@MapperScan(basePackages = {"com.cmhi.game_database_service.mapper"}) +@EnableScheduling +public class GameDatabaseServiceApplication { + + public static void main(String[] args) { + SpringApplication.run(GameDatabaseServiceApplication.class, args); + } + +} diff --git a/src/main/java/com/cmhi/game_database_service/common/BaseEnum.java b/src/main/java/com/cmhi/game_database_service/common/BaseEnum.java new file mode 100644 index 0000000..c535c08 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/common/BaseEnum.java @@ -0,0 +1,22 @@ +package com.cmhi.game_database_service.common; + +/** + * The interface Base enum. + * + * @author + */ +public interface BaseEnum { + /** + * Gets value. + * + * @return the value + */ + Integer getValue(); + + /** + * Gets description. + * + * @return the description + */ + String getDescription(); +} diff --git a/src/main/java/com/cmhi/game_database_service/common/CommonEnumHandler.java b/src/main/java/com/cmhi/game_database_service/common/CommonEnumHandler.java new file mode 100644 index 0000000..d4bae2d --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/common/CommonEnumHandler.java @@ -0,0 +1,145 @@ +package com.cmhi.game_database_service.common; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; + +/** + * The type Common enum handler. + * + * @param the type parameter + * @author + */ +public final class CommonEnumHandler extends BaseTypeHandler { + /** + * The Enum type. + */ + private final Class enumType; + /** + * The Enums. + */ + private final List enums; + + /** + * Instantiates a new Common enum handler. + * + * @param type the type + */ + public CommonEnumHandler(Class type) { + if (type == null) { + throw new IllegalArgumentException("Type argument cannot be null"); + } + + this.enumType = type; + this.enums = Arrays.asList(type.getEnumConstants()); + } + + /** + * Code of e. + * + * @param the type parameter + * @param enumClass the enum class + * @param code the code + * @return the e + */ + public static & BaseEnum> E codeOf(Class enumClass, int code) { + E[] enumCodes = enumClass.getEnumConstants(); + + for (E e : enumCodes) { + if (e.getValue() == code) { + return e; + } + } + + return null; + } + + /** + * Sets non null parameter. + * + * @param preparedStatement the prepared statement + * @param i the + * @param e the e + * @param jdbcType the jdbc type + * @throws SQLException the sql exception + */ + @Override + public void setNonNullParameter(PreparedStatement preparedStatement, int i, E e, JdbcType jdbcType) throws SQLException { + preparedStatement.setInt(i, e.getValue()); + } + + /** + * Gets nullable result. + * + * @param resultSet the result set + * @param s the s + * @return the nullable result + * @throws SQLException the sql exception + */ + @Override + public E getNullableResult(ResultSet resultSet, String s) throws SQLException { + if (resultSet.getObject(s) == null) { + return null; + } + + int val = resultSet.getInt(s); + return locateEnumStatus(val); + } + + /** + * Gets nullable result. + * + * @param resultSet the result set + * @param index the index + * @return the nullable result + * @throws SQLException the sql exception + */ + @Override + public E getNullableResult(ResultSet resultSet, int index) throws SQLException { + if (resultSet.getObject(index) == null) { + return null; + } + + int val = resultSet.getInt(index); + return locateEnumStatus(val); + } + + /** + * Gets nullable result. + * + * @param callableStatement the callable statement + * @param index the index + * @return the nullable result + * @throws SQLException the sql exception + */ + @Override + public E getNullableResult(CallableStatement callableStatement, int index) throws SQLException { + if (callableStatement.getObject(index) == null) { + return null; + } + + int val = callableStatement.getInt(index); + return locateEnumStatus(val); + } + + /** + * Locate enum status e. + * + * @param index the index + * @return the e + */ + private E locateEnumStatus(int index) { + for (E e : enums) { + if (e.getValue() == index) { + return e; + } + } + throw new IllegalArgumentException(enumType.getName() + " unknown enumerated type index:" + index); + } +} diff --git a/src/main/java/com/cmhi/game_database_service/common/ConstValue.java b/src/main/java/com/cmhi/game_database_service/common/ConstValue.java new file mode 100644 index 0000000..b238592 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/common/ConstValue.java @@ -0,0 +1,15 @@ +package com.cmhi.game_database_service.common; + +public class ConstValue { + /** + * The constant STRING_HTTP_AUTH_HEAD. + */ + public static final String STRING_HTTP_AUTH_HEAD = "Bearer "; + + public static class Protocol { + /** + * The constant VERSION. + */ + public static final int VERSION = 1; + } +} diff --git a/src/main/java/com/cmhi/game_database_service/common/ErrorCode.java b/src/main/java/com/cmhi/game_database_service/common/ErrorCode.java new file mode 100644 index 0000000..879035d --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/common/ErrorCode.java @@ -0,0 +1,393 @@ +package com.cmhi.game_database_service.common; + +import javax.servlet.http.HttpServletResponse; + +/** + * The enum Error code. + * + * @author + */ +public enum ErrorCode implements BaseEnum { + /** + * The Err ok. + */ + ERR_OK(0, "成功"), + /** + * The Err password. + */ + ERR_PASSWORD(1, "密码错误"), + /** + * The Err usernotfound. + */ + ERR_USERNOTFOUND(2, "用户不存在"), + /** + * The Err passwordmore. + */ + ERR_PASSWORDMORE(3, "连续密码错误达上限,再次输入错误将锁定用户"), + /** + * The Err userlock. + */ + ERR_USERLOCK(4, "密码错误达上限,用户被锁定"), + /** + * The Err account. + */ + ERR_ACCOUNT(5, "用户账户异常"), + /** + * The Err userexist. + */ + ERR_USEREXIST(6, "该用户已经存在"), + /** + * The Err passwordsimple. + */ + ERR_PASSWORDSIMPLE(7, "用户密码强度不符合要求"), + /** + * The Err inputformat. + */ + ERR_INPUTFORMAT(8, "输入信息格式有误"), + /** + * The Err inputmiss. + */ + ERR_INPUTMISS(9, "缺少必要输入信息"), + /** + * The Err permission. + */ + ERR_PERMISSION(10, "操作员权限不足"), + /** + * The Err reqtimeout. + */ + ERR_REQTIMEOUT(11, "请求超时"), + /** + * The Err params. + */ + ERR_PARAMS(12, "参数错误"), + /** + * The Err systemexception. + */ + ERR_SYSTEMEXCEPTION(13, "系统异常"), + /** + * The Err unknowncmd. + */ + ERR_UNKNOWNCMD(14, "未知命令"), + /** + * The Err logout. + */ + ERR_LOGOUT(15, "用户未登录"), + /** + * The Err tokentimeout. + */ + ERR_TOKENTIMEOUT(16, "Token超时"), + /** + * The Err tokennotfound. + */ + ERR_TOKENNOTFOUND(17, "非法Token"), + /** + * The Err missauthhead. + */ + ERR_MISSAUTHHEAD(18, "Http 请求缺少认证头部"), + /** + * The Err nosuchdevice. + */ + ERR_NOSUCHDEVICE(19, "没有这个设备"), + /** + * The Err deviceexists. + */ + ERR_DEVICEEXISTS(20, "设备已经存在"), + /** + * The Err paramexception. + */ + ERR_PARAMEXCEPTION(21, "参数异常"), + /** + * The Err devicelocked. + */ + ERR_DEVICELOCKED(22, "设备已锁定"), + /** + * The Err version. + */ + ERR_VERSION(23, "协议版本不兼容,请升级系统"), + /** + * The Err nosuchtype. + */ + ERR_NOSUCHTYPE(24, "没有这个类型的处置设备"), + /** + * The Err removemore. + */ + ERR_REMOVEMORE(25, "禁止同时删除多个设备"), + /** + * The Err taskrunning. + */ + ERR_TASKRUNNING(26, "同类任务正在运行"), + /** + * The Err unsupport. + */ + ERR_UNSUPPORT(27, "不支持的操作"), + /** + * The Err interrupt. + */ + ERR_INTERRUPT(28, "操作中断"), + /** + * The Err calldevice. + */ + ERR_CALLDEVICE(29, "调用设备失败"), + /** + * The Err nosuchtask. + */ + ERR_NOSUCHTASK(30, "没有该任务"), + /** + * The Err tasknotrunning. + */ + ERR_TASKNOTRUNNING(31, "该任务没有运行"), + /** + * The Err requesttimeout. + */ + ERR_REQUESTTIMEOUT(32, "请求超时"), + /** + * The Err unabledisposeip. + */ + ERR_UNABLEDISPOSEIP(33, "无法处置该IP"), + /** + * The Err haohan error. + */ + ERR_HAOHAN_ERROR(34, "浩瀚设备返回错误"), + /** + * The Err database. + */ + ERR_DATABASE(35, "操作数据库失败"), + /** + * The Err ipnodevice. + */ + ERR_IPNODEVICE(36, "找不到处置该IP的设备"), + /** + * The Err untrusthost. + */ + ERR_UNTRUSTHOST(37, "未经授权的客户端"), + /** + * The Err untrusttoken. + */ + ERR_UNTRUSTTOKEN(38, "未经授权的Token"), + /** + * The Err unknowninterface. + */ + ERR_UNKNOWNINTERFACE(39, "未提供该接口"), + /** + * The Err decrypt base 64. + */ + ERR_DECRYPT_BASE64(100, "BASE64解密失败"), + /** + * The Err encrypt base 64. + */ + ERR_ENCRYPT_BASE64(101, "BASE64加密失败"), + /** + * The Err decrypt aes 128. + */ + ERR_DECRYPT_AES128(102, "AES128解密失败"), + /** + * The Err encrypt aes 128. + */ + ERR_ENCRYPT_AES128(103, "AES128加密失败"), + /** + * The Err decrypt 3 des. + */ + ERR_DECRYPT_3DES(104, "3DES解密失败"), + /** + * The Err encrypt 3 des. + */ + ERR_ENCRYPT_3DES(105, "3DES加密失败"), + /** + * The Err decrypt unknown. + */ + ERR_DECRYPT_UNKNOWN(106, "不支持的解密算法"), + /** + * The Err encrypt unknown. + */ + ERR_ENCRYPT_UNKNOWN(107, "不支持的加密算法"), + /** + * The Err json encode. + */ + ERR_JSON_ENCODE(108, "Json 序列号错误"), + /** + * The Err json decode. + */ + ERR_JSON_DECODE(109, "Json 反序列化错误"), + /** + * The Err encrypt aes 256. + */ + ERR_ENCRYPT_AES256(110, "AES256加密失败"), + /** + * The Err decrypt aes 256. + */ + ERR_DECRYPT_AES256(111, "AES256解密失败"), + /** + * The Err nodevice areacode. + */ + ERR_NODEVICE_AREACODE(112, "区域无该设备"), + /** + * The Err specifiedip exists. + */ + ERR_SPECIFIEDIP_EXISTS(113, "指定的IP已经存在"), + /** + * The Err specifiedip notexists. + */ + ERR_SPECIFIEDIP_NOTEXISTS(114, "指定的IP地址不存在"), + /** + * The Err server processreq. + */ + ERR_SERVER_PROCESSREQ(115, "服务器处理请求错误"), + /** + * The Err huawei error. + */ + ERR_HUAWEI_ERROR(116, "华为设备返回错误"), + /** + * The Err pengxin error. + */ + ERR_PENGXIN_ERROR(117, "鹏信设备返回错误"), + /** + * The Err upf error. + */ + ERR_UPF_ERROR(118, "UPF设备返回错误"), + /** + * The Err nosuchumcprotectobject. + */ + ERR_NOSUCHUMCPROTECTOBJECT(200, "没有找到UMC防护对象"), + + /** + * The Err protectobjectexists. + */ + ERR_PROTECTOBJECTEXISTS(201, "该防护对象已经存在"), + + /** + * The Err tractionstrategyrunning. + */ + ERR_TRACTIONSTRATEGYRUNNING(201, "该防护策略正在运行"), + + /** + * The Err nosuchprotectstrategy. + */ + ERR_NOSUCHPROTECTSTRATEGY(202, "没有该防护策略"), + + + /** + * The Err businessexists. + */ + ERR_BUSINESSEXISTS(300, "该业务已经存在"), + + /** + * Err businessnotexists error code. + */ + ERR_BUSINESSNOTEXISTS(301, "该业务不存在"), + + /** + * Err addbusiness error code. + */ + ERR_ADDBUSINESS(302, "添加客户业务失败"), + + /** + * Err delbusiness error code. + */ + ERR_DELBUSINESS(303, "删除客户业务失败"), + + /** + * Err not found device error code. + */ + ERR_NOTFOUNDDEVICE(304, "找不到设备先添加设备"), + /** + * The Err huawei firewall error. + */ + ERR_HUAWEIFIREWALL_ERROR(305, "华为防火墙返回错误"), + /** + * The Err emos create message error. + */ + EMOS_CREATEMESSAGE_ERROR(306, "EMOS发送信息错误"), + ; + + /** + * The Errno. + */ + private final int errno; + /** + * The Err msg. + */ + private final String errMsg; + + /** + * Instantiates a new Error code. + * + * @param err the err + * @param msg the msg + */ + ErrorCode(int err, String msg) { + this.errno = err; + this.errMsg = msg; + } + + /** + * Gets code. + * + * @return the code + */ + public int getCode() { + return errno; + } + + /** + * Gets http code. + * + * @return the http code + */ + public int getHttpCode() { + switch (this) { + case ERR_OK: + return HttpServletResponse.SC_OK; + case ERR_SYSTEMEXCEPTION: + case ERR_PARAMEXCEPTION: + return HttpServletResponse.SC_EXPECTATION_FAILED; + case ERR_TOKENTIMEOUT: + case ERR_REQTIMEOUT: + return HttpServletResponse.SC_REQUEST_TIMEOUT; + case ERR_UNTRUSTTOKEN: + case ERR_UNTRUSTHOST: + case ERR_LOGOUT: + return HttpServletResponse.SC_UNAUTHORIZED; + case ERR_MISSAUTHHEAD: + case ERR_PARAMS: + case ERR_INPUTFORMAT: + case ERR_INPUTMISS: + return HttpServletResponse.SC_BAD_REQUEST; + case ERR_UNSUPPORT: + return HttpServletResponse.SC_METHOD_NOT_ALLOWED; + case ERR_UNKNOWNINTERFACE: + return HttpServletResponse.SC_NOT_FOUND; + default: + return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; + } + } + + /** + * Gets msg. + * + * @return the msg + */ + public String getMsg() { + return errMsg; + } + + + /** + * Gets value. + * + * @return the value + */ + @Override + public Integer getValue() { + return this.errno; + } + + /** + * Gets description. + * + * @return the description + */ + @Override + public String getDescription() { + return this.errMsg; + } +} diff --git a/src/main/java/com/cmhi/game_database_service/common/ProtoCryptoType.java b/src/main/java/com/cmhi/game_database_service/common/ProtoCryptoType.java new file mode 100644 index 0000000..7341b53 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/common/ProtoCryptoType.java @@ -0,0 +1,78 @@ +package com.cmhi.game_database_service.common; + +/** + * The enum Proto crypto type. + * + * @author + */ +public enum ProtoCryptoType { + /** + * The Crypto none. + */ + CRYPTO_NONE(0, "不加密"), + /** + * The Crypto base 64. + */ + CRYPTO_BASE64(1, "Base64编码"), + /** + * The Crypto aes 128. + */ + CRYPTO_AES128(2, "AES128加密"), + /** + * The Crypto des. + */ + CRYPTO_DES(3, "DES对称加密"), + /** + * Crypto aes 256 proto crypto type. + */ + CRYPTO_AES256(4, "AES256加密"), + ; + + /** + * The Code. + */ + private final int code; + /** + * The Readme. + */ + private final String readme; + + /** + * Instantiates a new Proto crypto type. + * + * @param code the code + * @param readme the readme + */ + ProtoCryptoType(int code, String readme) { + this.code = code; + this.readme = readme; + } + + /** + * Verify crypto valuable boolean. + * + * @param code the code + * @return the boolean + */ + public static boolean verifyCryptoValuable(int code) { + return code >= CRYPTO_NONE.getCode() && code <= CRYPTO_DES.getCode(); + } + + /** + * Gets code. + * + * @return the code + */ + public int getCode() { + return this.code; + } + + /** + * Gets readme. + * + * @return the readme + */ + public String getReadme() { + return this.readme; + } +} diff --git a/src/main/java/com/cmhi/game_database_service/common/SecurityConfigValue.java b/src/main/java/com/cmhi/game_database_service/common/SecurityConfigValue.java new file mode 100644 index 0000000..f63f7a2 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/common/SecurityConfigValue.java @@ -0,0 +1,31 @@ +package com.cmhi.game_database_service.common; + +/** + * The type Security config value. + * + * @author + */ +public class SecurityConfigValue { + + /** + * Instantiates a new Security config value. + */ + private SecurityConfigValue() { + throw new AssertionError("Instantiating utility class."); + } + + /** + * The constant AES_KEY. + */ + public static String AES_KEY = ""; + + /** + * The constant DES_KEY. + */ + public static String DES_KEY = ""; + + /** + * The constant SECURITY_PROTOCOL_TYPE. + */ + public static Integer SECURITY_PROTOCOL_TYPE = 0; +} diff --git a/src/main/java/com/cmhi/game_database_service/exception/ControllerNotSupportException.java b/src/main/java/com/cmhi/game_database_service/exception/ControllerNotSupportException.java new file mode 100644 index 0000000..f59a72d --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/exception/ControllerNotSupportException.java @@ -0,0 +1,29 @@ +package com.cmhi.game_database_service.exception; + +import com.cmhi.game_database_service.common.ErrorCode; +import lombok.Getter; +import lombok.Setter; + +/** + * The type Controller not support exception. + * + * @author + */ +@Getter +@Setter +public class ControllerNotSupportException extends RuntimeException { + /** + * The Err. + */ + private ErrorCode err; + + /** + * Instantiates a new Security protocol exception. + * + * @param err the err + */ + public ControllerNotSupportException(ErrorCode err) { + super(); + this.err = err; + } +} diff --git a/src/main/java/com/cmhi/game_database_service/exception/ControllerRequestTimeoutException.java b/src/main/java/com/cmhi/game_database_service/exception/ControllerRequestTimeoutException.java new file mode 100644 index 0000000..3b4355c --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/exception/ControllerRequestTimeoutException.java @@ -0,0 +1,45 @@ +package com.cmhi.game_database_service.exception; + +import com.cmhi.game_database_service.common.ErrorCode; +import lombok.Getter; +import lombok.Setter; + +/** + * The type Controller request timeout exception. + * + * @author + */ +@Getter +@Setter +public class ControllerRequestTimeoutException extends RuntimeException { + /** + * The Err. + */ + private ErrorCode err; + + /** + * The Message. + */ + private String message; + + /** + * Instantiates a new Controller request timeout exception. + * + * @param err the err + * @param msg the msg + */ + public ControllerRequestTimeoutException(ErrorCode err, String msg) { + super(); + this.err = err; + this.message = err.getMsg() + ", " + msg; + } + + /** + * Gets exception message. + * + * @return the exception message + */ + public String getExceptionMessage() { + return this.message; + } +} diff --git a/src/main/java/com/cmhi/game_database_service/exception/GlobalExceptionHandler.java b/src/main/java/com/cmhi/game_database_service/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..cd063fc --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/exception/GlobalExceptionHandler.java @@ -0,0 +1,213 @@ +package com.cmhi.game_database_service.exception; + +import com.cmhi.game_database_service.common.ConstValue; +import com.cmhi.game_database_service.common.ErrorCode; +import com.cmhi.game_database_service.misc.Helper; +import com.cmhi.game_database_service.pojo.dto.protocol.base.BaseRespStatus; +import com.cmhi.game_database_service.pojo.dto.protocol.base.ProtocolRespDTO; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.ObjectError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * The type Global exception handler. + * + * @author + */ +@ControllerAdvice +@Slf4j +public class GlobalExceptionHandler { + /** + * Handle exception protocol resp dto. + * + * @param rsp the rsp + * @param req the req + * @param ex the ex + * @return the protocol resp dto + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseBody + public ProtocolRespDTO handleException(HttpServletResponse rsp, + HttpServletRequest req, + MethodArgumentNotValidException ex) { + try { + String reqType = req.getMethod(); + String reqPath = req.getRequestURI(); + String reqIp = req.getRemoteAddr(); + String reqToken = req.getHeader("Authorization"); + + if (reqToken != null && !reqToken.isEmpty()) { + reqToken = reqToken.replace(ConstValue.STRING_HTTP_AUTH_HEAD, ""); + } + + StringBuilder sb = new StringBuilder("["); + + List errList = ex.getBindingResult().getAllErrors(); + + for (int i = 0; i < errList.size(); i++) { + log.debug("Verify params error {}: {}", i, errList.get(i)); + sb.append("\"") + .append(i) + .append(": ") + .append(errList.get(i).getDefaultMessage()) + .append("\""); + if (i < errList.size() - 1) { + sb.append(", "); + } + } + sb.append("]"); + + log.error("Interface [{}] request <{}> from {}, token = <{}>\n" + + "+++ Request: {}\n" + + "--- Verify params failed: {}", + reqType, reqPath, reqIp, reqToken, Helper.inputStream2String(req.getInputStream()), sb); + } catch (Exception ignored) { + } + + log.debug("Argument Exception: ", ex); + + List exMsg = new ArrayList<>(); + + AtomicInteger idx = new AtomicInteger(); + + ex.getBindingResult() + .getAllErrors() + .forEach(v -> exMsg.add(idx.getAndIncrement() + ": " + v.getDefaultMessage())); + + rsp.setStatus(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()); + + return ProtocolRespDTO.result(ErrorCode.ERR_PARAMEXCEPTION, + ErrorCode.ERR_PARAMEXCEPTION.getHttpCode(), + exMsg.toArray(new String[0])); + } + + /** + * Handle exception protocol resp dto. + * + * @param rsp the rsp + * @param req the req + * @param ex the ex + * @return the protocol resp dto + */ + @ExceptionHandler(SecurityProtocolException.class) + @ResponseBody + public ProtocolRespDTO handleException(HttpServletResponse rsp, + HttpServletRequest req, + SecurityProtocolException ex) { + try { + String reqType = req.getMethod(); + String reqPath = req.getRequestURI(); + String reqIp = req.getRemoteAddr(); + String reqToken = req.getHeader("Authorization"); + + if (reqToken != null && !reqToken.isEmpty()) { + reqToken = reqToken.replace(ConstValue.STRING_HTTP_AUTH_HEAD, ""); + } + log.error("Interface [{}] request <{}> from {}, token = <{}>\n" + + "+++ Request: {}\n" + + "--- Verify params failed: {}", + reqType, reqPath, reqIp, reqToken, Helper.inputStream2String(req.getInputStream()), + ex.getMessage() == null ? ex.getDescription() : ex.getMessage()); + } catch (Exception ignored) { + } + + log.debug("SecurityProtocolException Exception: ", ex); + + List errMeg = new ArrayList<>(); + rsp.setStatus(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()); + + errMeg.add(ex.getErr().getMsg()); + + if (ex.getDescription() != null && !ex.getDescription().isEmpty()) { + errMeg.add(ex.getDescription()); + } + + if (ex.getMessage() != null && !ex.getMessage().isEmpty()) { + errMeg.add(ex.getMessage()); + } + + return ProtocolRespDTO.result(ErrorCode.ERR_PARAMEXCEPTION, + ErrorCode.ERR_PARAMEXCEPTION.getHttpCode(), + errMeg.toArray(new String[0])); + } + + /** + * Handle exception protocol resp dto. + * + * @param rsp the rsp + * @param req the req + * @param ex the ex + * @return the protocol resp dto + */ + @ExceptionHandler(ControllerRequestTimeoutException.class) + @ResponseBody + public ProtocolRespDTO handleException(HttpServletResponse rsp, + HttpServletRequest req, + ControllerRequestTimeoutException ex) { + try { + String reqType = req.getMethod(); + String reqPath = req.getRequestURI(); + String reqIp = req.getRemoteAddr(); + String reqToken = req.getHeader("Authorization"); + if (reqToken != null && !reqToken.isEmpty()) { + reqToken = reqToken.replace(ConstValue.STRING_HTTP_AUTH_HEAD, ""); + } + log.error("Interface [{}] request <{}> from {}, token = <{}>\n" + + "+++ Request: {}\n" + + "--- Verify params failed: {}", + reqType, reqPath, reqIp, reqToken, Helper.inputStream2String(req.getInputStream()), + ex.getMessage()); + } catch (Exception ignored) { + } + + List errMeg = new ArrayList<>(); + rsp.setStatus(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()); + + if (ex.getMessage() != null && !ex.getMessage().isEmpty()) { + errMeg.add(ex.getMessage()); + } + + return ProtocolRespDTO.result(ErrorCode.ERR_PARAMEXCEPTION, + ErrorCode.ERR_PARAMEXCEPTION.getHttpCode(), + errMeg.toArray(new String[0])); + } + + /** + * Handle exception protocol resp dto. + * + * @param rsp the rsp + * @param ex the ex + * @return the protocol resp dto + */ + @ExceptionHandler(Throwable.class) + @ResponseBody + public ProtocolRespDTO handleException(HttpServletResponse rsp, Throwable ex) { + List errMeg = new ArrayList<>(); + log.debug("Throwable Exception: ", ex); + + rsp.setStatus(ErrorCode.ERR_PARAMEXCEPTION.getHttpCode()); + + if (ex instanceof ControllerNotSupportException) { + errMeg.add(((ControllerNotSupportException) ex).getErr().getMsg()); + } else { + errMeg.add(ErrorCode.ERR_PARAMEXCEPTION.getMsg()); + } + + if (ex.getMessage() != null && ex.getMessage().length() > 0) { + errMeg.add(ex.getMessage()); + } + + return ProtocolRespDTO.result(ErrorCode.ERR_PARAMEXCEPTION, + ErrorCode.ERR_PARAMEXCEPTION.getHttpCode(), + errMeg.toArray(new String[0])); + } +} diff --git a/src/main/java/com/cmhi/game_database_service/exception/SecurityProtocolException.java b/src/main/java/com/cmhi/game_database_service/exception/SecurityProtocolException.java new file mode 100644 index 0000000..827d54d --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/exception/SecurityProtocolException.java @@ -0,0 +1,38 @@ +package com.cmhi.game_database_service.exception; + +import com.cmhi.game_database_service.common.ErrorCode; +import lombok.Getter; +import lombok.Setter; + +/** + * The type Security exception. + * + * @author + */ +@Getter +@Setter +public class SecurityProtocolException extends RuntimeException { + /** + * The Err. + */ + private ErrorCode err; + + private String description; + + /** + * Instantiates a new Security exception. + * + * @param err the err + */ + public SecurityProtocolException(ErrorCode err) { + super(); + this.err = err; + this.description = null; + } + + public SecurityProtocolException(ErrorCode err, String readme) { + super(); + this.err = err; + this.description = readme; + } +} diff --git a/src/main/java/com/cmhi/game_database_service/misc/Helper.java b/src/main/java/com/cmhi/game_database_service/misc/Helper.java new file mode 100644 index 0000000..48efdc0 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/misc/Helper.java @@ -0,0 +1,111 @@ +package com.cmhi.game_database_service.misc; + +import lombok.extern.slf4j.Slf4j; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * The type Helper. + * + * @author + */ +@Slf4j +public class Helper { + + /** + * Instantiates a new Helper. + */ + private Helper() { + throw new AssertionError("Instantiating utility class."); + } + + /** + * Gets current datetime. + * + * @return the current datetime + */ + public static String getCurrentDatetime() { + return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + } + + /** + * Gets timestamp second. + * + * @param dateTime the date time + * @return the timestamp second + */ + public static int getTimestampSecond(String dateTime) { + return (int) (Timestamp.valueOf(dateTime).toInstant().toEpochMilli() / 1000); + } + + /** + * Gets timestamp milli second. + * + * @param dateTime the date time + * @return the timestamp milli second + */ + public static long getTimestampMilliSecond(String dateTime) { + return Timestamp.valueOf(dateTime).toInstant().toEpochMilli(); + } + + /** + * Gets timestamp diff. + * + * @param begin the begin + * @param end the end + * @return the timestamp diff + */ + public static int getTimestampDiff(String begin, String end) { + int starTime = getTimestampSecond(begin); + int endTm = getTimestampSecond(end); + + return endTm - starTime; + } + + /** + * Gets timestamp diff now. + * + * @param begin the begin + * @return the timestamp diff now + */ + public static int getTimestampDiffNow(String begin) { + int starTime = getTimestampSecond(begin); + int endTm = (int) (System.currentTimeMillis() / 1000); + + return endTm - starTime; + } + + /** + * Input stream 2 string string. + * + * @param inputStream the input stream + * @return the string + */ + public static String inputStream2String(InputStream inputStream) { + StringBuilder sb = new StringBuilder(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, + StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + sb.append(line); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + + return sb.toString(); + } +} diff --git a/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseIdResp.java b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseIdResp.java new file mode 100644 index 0000000..ff34711 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseIdResp.java @@ -0,0 +1,35 @@ +package com.cmhi.game_database_service.pojo.dto.protocol.base; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +/** + * The type Base id resp. + * + * @author + */ +@EqualsAndHashCode(callSuper = true) +@Data +@AllArgsConstructor +@NoArgsConstructor +@JsonPropertyOrder({"id", "devId", "taskId", "status", "message"}) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BaseIdResp extends BaseRespStatus { + /** + * The Id. + */ + private String id; + /** + * The Dev id. + */ + private String devId; + + /** + * The Task id. + */ + private String taskId; +} diff --git a/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseProtocolDTO.java b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseProtocolDTO.java new file mode 100644 index 0000000..cf3b4ad --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseProtocolDTO.java @@ -0,0 +1,54 @@ +package com.cmhi.game_database_service.pojo.dto.protocol.base; + +import com.cmhi.game_database_service.validation.ValidGroups; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.hibernate.validator.constraints.Range; + +import javax.validation.Valid; +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.NotNull; + +/** + * The type Base protocol dto. + * + * @param the type parameter + * @author + */ +@Data +@NoArgsConstructor + +@JsonPropertyOrder({"ver", "cryptoType", "timeStamp", "msgContent"}) +public class BaseProtocolDTO { + /** + * 当前协议版本号 + */ + @NotNull(message = "ver 字段不能为空", groups = ValidGroups.ProtocolCommonValid.class) + @Range(min = 3, max = 9999, message = "ver 字段最小值为 3", groups = ValidGroups.ProtocolCommonValid.class) + private Integer ver; + + /** + * msgContent字段内容编码格式 + */ + @NotNull(message = "cryptoType 字段不能为空", groups = ValidGroups.ProtocolCommonValid.class) + @Range(min = 0, max = 4, + message = "cryptoType 字段取值为 [0, 4]" + , groups = ValidGroups.ProtocolCommonValid.class) + private Integer cryptoType; + + /** + * 当前UTC时间戳(ms) + */ + @NotNull(message = "timeStamp 字段不能为空", groups = ValidGroups.ProtocolCommonValid.class) + @DecimalMin(value = "1595494343000", + message = "timeStamp 字段值不能为过去时间" + , groups = ValidGroups.ProtocolCommonValid.class) + private Long timeStamp; + + /** + * 协议详细内容 + */ + @Valid + private T msgContent; +} diff --git a/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseRespStatus.java b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseRespStatus.java new file mode 100644 index 0000000..2cc47d0 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/BaseRespStatus.java @@ -0,0 +1,25 @@ +package com.cmhi.game_database_service.pojo.dto.protocol.base; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * The type Response status. + * + * @author + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class BaseRespStatus { + + /** + * 0:成功;其它:失败原因. + */ + private Integer status; + /** + * 登录消息: status状态码对应的提示信息 + */ + private String[] message; +} diff --git a/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/IdArraysReq.java b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/IdArraysReq.java new file mode 100644 index 0000000..54dd43d --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/IdArraysReq.java @@ -0,0 +1,40 @@ +package com.cmhi.game_database_service.pojo.dto.protocol.base; + +import com.cmhi.game_database_service.validation.ValidGroups; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * The type Id arrays req. + * + * @author + */ +@Getter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class IdArraysReq { + + /** + * The Id. + */ + @NotNull(message = "id 字段不能为空", + groups = {ValidGroups.IdArrayValid.class, ValidGroups.GetDevVerReqValid.class}) + @Size(min = 1, message = "id 字段必须指定明确id编号", groups = ValidGroups.ExplicitIdArrayValid.class) + private String[] id; + + /** + * The Task id. + */ + @NotNull(message = "taskId 字段不能为空", groups = ValidGroups.TaskStopReqValid.class) + @Size(min = 1, max = 20, message = "taskId 字段id个数取值范围为[1, 20]", + groups = ValidGroups.TaskStopReqValid.class) + private String[] taskId; +} diff --git a/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/ProtocolReqDTO.java b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/ProtocolReqDTO.java new file mode 100644 index 0000000..8043878 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/ProtocolReqDTO.java @@ -0,0 +1,48 @@ +package com.cmhi.game_database_service.pojo.dto.protocol.base; + +import com.cmhi.game_database_service.common.ConstValue; +import lombok.NoArgsConstructor; +import lombok.ToString; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpHeaders; + +import java.util.Objects; + +/** + * The type Protocol req dto. + * + * @param the type parameter + * @author + */ +@NoArgsConstructor +@ToString +@Slf4j +public class ProtocolReqDTO extends BaseProtocolDTO { + /** + * Gets auth token. + * + * @param headers the headers + * @return the auth token + */ + public String getAuthToken(HttpHeaders headers) { + // 是否有必要的HTTP Head字段 + if (headers == null) { + log.error("Http request is missing authentication header"); + return ""; + } + + try { + String authString = Objects.requireNonNull(headers.get("Authorization")).get(0); + + if (!authString.startsWith(ConstValue.STRING_HTTP_AUTH_HEAD)) { + log.error("Input Authorization header error: [{}]", authString); + return ""; + } + // 保持当前请求token内容 + return authString.replaceFirst(ConstValue.STRING_HTTP_AUTH_HEAD, ""); + } catch (Exception ex) { + log.error(ex.getMessage()); + return ""; + } + } +} diff --git a/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/ProtocolRespDTO.java b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/ProtocolRespDTO.java new file mode 100644 index 0000000..05b9cd9 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/pojo/dto/protocol/base/ProtocolRespDTO.java @@ -0,0 +1,93 @@ +package com.cmhi.game_database_service.pojo.dto.protocol.base; + + +import com.cmhi.game_database_service.common.ConstValue; +import com.cmhi.game_database_service.common.ErrorCode; +import com.cmhi.game_database_service.common.SecurityConfigValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * The type Protocol resp dto. + * + * @param the type parameter + * @author + */ +@Slf4j +@EqualsAndHashCode(callSuper = true) +@Data +@NoArgsConstructor +@AllArgsConstructor +@JsonPropertyOrder({"ver", "cryptoType", "timeStamp", "code", "msgContent"}) +public class ProtocolRespDTO extends BaseProtocolDTO { + /** + * The constant OBJECT_MAPPER. + */ + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + /** + * The Code. + */ + private Integer code; + + /** + * Result protocol resp dto. + * + * @param the type parameter + * @param err the err + * @param httpCode the http code + * @param respMsg the resp msg + * @return the protocol resp dto + */ + private static ProtocolRespDTO result(ErrorCode err, Integer httpCode, T respMsg) { + ProtocolRespDTO resp = new ProtocolRespDTO<>(); + + resp.setVer(ConstValue.Protocol.VERSION); + resp.setCode(httpCode); + resp.setCryptoType(SecurityConfigValue.SECURITY_PROTOCOL_TYPE); + resp.setTimeStamp(System.currentTimeMillis()); + resp.setMsgContent(respMsg); + return resp; + } + + /** + * Result protocol resp dto. + * + * @param the type parameter + * @param err the err + * @param respMsg the resp msg + * @return the protocol resp dto + */ + public static ProtocolRespDTO result(ErrorCode err, T respMsg) { + return result(err, err.getHttpCode(), respMsg); + } + + /** + * Result protocol resp dto. + * + * @param err the err + * @return the protocol resp dto + */ + public static ProtocolRespDTO result(ErrorCode err) { + BaseRespStatus rspMsg = new BaseRespStatus(err.getCode(), new String[]{err.getMsg()}); + return result(err, err.getHttpCode(), rspMsg); + } + + /** + * Result protocol resp dto. + * + * @param errCode the err code + * @param httpCode the http code + * @param message the message + * @return the protocol resp dto + */ + public static ProtocolRespDTO result(ErrorCode errCode, Integer httpCode, String[] message) { + BaseRespStatus rspMsg = new BaseRespStatus(errCode.getCode(), message); + return result(errCode, httpCode, rspMsg); + } +} diff --git a/src/main/java/com/cmhi/game_database_service/security/arithmetic/CryptoHelper.java b/src/main/java/com/cmhi/game_database_service/security/arithmetic/CryptoHelper.java new file mode 100644 index 0000000..44225c4 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/security/arithmetic/CryptoHelper.java @@ -0,0 +1,230 @@ +package com.cmhi.game_database_service.security.arithmetic; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +/** + * The type Crypto helper. + * + * @author + */ +@Slf4j +public class CryptoHelper { + + /** + * Instantiates a new Crypto helper. + */ + private CryptoHelper() { + throw new AssertionError("Instantiating utility class."); + } + + /** + * The constant AES_ALGORITHM_STR. + */ + private static final String AES_ALGORITHM_STR = "AES/ECB/PKCS5Padding"; + + /** + * The constant DES_ALGORITHM_STR. + */ + private static final String DES_ALGORITHM_STR = "DES/ECB/PKCS5Padding"; + + /** + * Base 64 decryption byte [ ]. + * + * @param ciphertext the ciphertext + * @return the byte [ ] + */ + public static byte[] base64Decryption(String ciphertext) { + return Base64.decodeBase64(ciphertext); + } + + /** + * Base 64 encryption string. + * + * @param plaintext the plaintext + * @return the string + */ + public static String base64Encryption(byte[] plaintext) { + return Base64.encodeBase64String(plaintext); + } + + /** + * Sha 256 encryption byte [ ]. + * + * @param plaintext the plaintext + * @return the byte [ ] + * @throws NoSuchAlgorithmException the no such algorithm exception + */ + public static byte[] sha256Encryption(String plaintext) throws NoSuchAlgorithmException { + MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(plaintext.getBytes(StandardCharsets.UTF_8)); + return messageDigest.digest(); + } + + /** + * Md 5 encryption string. + * + * @param plaintext the plaintext + * @return the string + * @throws NoSuchAlgorithmException the no such algorithm exception + */ + public static String md5Encryption(String plaintext) throws NoSuchAlgorithmException { + MessageDigest messageDigest = MessageDigest.getInstance("MD5"); + messageDigest.update(plaintext.getBytes(StandardCharsets.UTF_8)); + return base64Encryption(messageDigest.digest()); + } + + /** + * Aes 128 encryption byte [ ]. + * + * @param plaintext the plaintext + * @param aesKey the aes key + * @return the byte [ ] + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws NoSuchPaddingException the no such padding exception + * @throws InvalidKeyException the invalid key exception + * @throws BadPaddingException the bad padding exception + * @throws IllegalBlockSizeException the illegal block size exception + */ + public static byte[] aes128Encryption(byte[] plaintext, String aesKey) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { + KeyGenerator keyGen = KeyGenerator.getInstance("AES"); + SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); + secureRandom.setSeed(aesKey.getBytes()); + + keyGen.init(128, secureRandom); + Cipher cipher = Cipher.getInstance(AES_ALGORITHM_STR); + SecretKeySpec key = new SecretKeySpec(keyGen.generateKey().getEncoded(), "AES"); + cipher.init(Cipher.ENCRYPT_MODE, key); + return cipher.doFinal(plaintext); + } + + /** + * Aes 128 decryption byte [ ]. + * + * @param ciphertext the ciphertext + * @param aesKey the aes key + * @return the byte [ ] + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws NoSuchPaddingException the no such padding exception + * @throws InvalidKeyException the invalid key exception + * @throws BadPaddingException the bad padding exception + * @throws IllegalBlockSizeException the illegal block size exception + */ + public static byte[] aes128Decryption(byte[] ciphertext, String aesKey) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { + KeyGenerator keyGen = KeyGenerator.getInstance("AES"); + SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); + secureRandom.setSeed(aesKey.getBytes()); + + keyGen.init(128, secureRandom); + Cipher cipher = Cipher.getInstance(AES_ALGORITHM_STR); + SecretKeySpec key = new SecretKeySpec(keyGen.generateKey().getEncoded(), "AES"); + cipher.init(Cipher.DECRYPT_MODE, key); + return cipher.doFinal(ciphertext); + } + + /** + * Aes 256 encryption byte [ ]. + * + * @param plaintext the plaintext + * @param aesKey the aes key + * @return the byte [ ] + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws NoSuchPaddingException the no such padding exception + * @throws InvalidKeyException the invalid key exception + * @throws BadPaddingException the bad padding exception + * @throws IllegalBlockSizeException the illegal block size exception + */ + public static byte[] aes256Encryption(byte[] plaintext, String aesKey) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { + Cipher cipher = Cipher.getInstance(AES_ALGORITHM_STR); + SecretKeySpec key = new SecretKeySpec(sha256Encryption(aesKey), "AES"); + cipher.init(Cipher.ENCRYPT_MODE, key); + return cipher.doFinal(plaintext); + } + + /** + * Aes 256 decryption byte [ ]. + * + * @param ciphertext the ciphertext + * @param aesKey the aes key + * @return the byte [ ] + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws NoSuchPaddingException the no such padding exception + * @throws InvalidKeyException the invalid key exception + * @throws BadPaddingException the bad padding exception + * @throws IllegalBlockSizeException the illegal block size exception + */ + public static byte[] aes256Decryption(byte[] ciphertext, String aesKey) throws NoSuchAlgorithmException, + NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { + Cipher cipher = Cipher.getInstance(AES_ALGORITHM_STR); + SecretKeySpec key = new SecretKeySpec(sha256Encryption(aesKey), "AES"); + cipher.init(Cipher.DECRYPT_MODE, key); + return cipher.doFinal(ciphertext); + } + + /** + * Des decryption byte [ ]. + * + * @param ciphertext the ciphertext + * @param desKey the des key + * @return the byte [ ] + * @throws InvalidKeyException the invalid key exception + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws NoSuchPaddingException the no such padding exception + * @throws BadPaddingException the bad padding exception + * @throws IllegalBlockSizeException the illegal block size exception + */ + public static byte[] desDecryption(byte[] ciphertext, String desKey) throws InvalidKeyException, + NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, + IllegalBlockSizeException { + KeyGenerator keyGen = KeyGenerator.getInstance("DES"); + SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); + secureRandom.setSeed(desKey.getBytes()); + + keyGen.init(56, secureRandom); + Cipher cipher = Cipher.getInstance(DES_ALGORITHM_STR); + SecretKeySpec key = new SecretKeySpec(keyGen.generateKey().getEncoded(), "DES"); + cipher.init(Cipher.DECRYPT_MODE, key); + return cipher.doFinal(ciphertext); + } + + /** + * Des encryption byte [ ]. + * + * @param plaintext the plaintext + * @param desKey the des key + * @return the byte [ ] + * @throws InvalidKeyException the invalid key exception + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws NoSuchPaddingException the no such padding exception + * @throws BadPaddingException the bad padding exception + * @throws IllegalBlockSizeException the illegal block size exception + */ + public static byte[] desEncryption(byte[] plaintext, String desKey) throws InvalidKeyException, + NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, + IllegalBlockSizeException { + KeyGenerator keyGen = KeyGenerator.getInstance("DES"); + SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); + secureRandom.setSeed(desKey.getBytes()); + + keyGen.init(56, secureRandom); + Cipher cipher = Cipher.getInstance(DES_ALGORITHM_STR); + SecretKeySpec key = new SecretKeySpec(keyGen.generateKey().getEncoded(), "DES"); + cipher.init(Cipher.ENCRYPT_MODE, key); + return cipher.doFinal(plaintext); + } +} diff --git a/src/main/java/com/cmhi/game_database_service/security/configure/EncryptionPropertyResolver.java b/src/main/java/com/cmhi/game_database_service/security/configure/EncryptionPropertyResolver.java new file mode 100644 index 0000000..3c5defc --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/security/configure/EncryptionPropertyResolver.java @@ -0,0 +1,73 @@ +package com.cmhi.game_database_service.security.configure; + +import com.cmhi.game_database_service.security.arithmetic.CryptoHelper; +import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver; +import lombok.extern.slf4j.Slf4j; + +import javax.crypto.BadPaddingException; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import org.apache.commons.lang.StringUtils; + +/** + * The type Encryption property resolver. + * + * @author + */ +@Slf4j +public class EncryptionPropertyResolver implements EncryptablePropertyResolver { + /** + * The Password. + */ + private final String password; + + /** + * Instantiates a new Encryption property resolver. + * + * @param key the key + */ + public EncryptionPropertyResolver(String key) { + this.password = key + "cmcc@10086!"; + } + + /** + * Resolve property value string. + * + * @param value the value + * @return the string + */ + @Override + public String resolvePropertyValue(String value) { + final String encPrefix = "ENC@"; + if (StringUtils.isBlank(value)) { + return value; + } + //值以ENC@开头的均为加密 + if (value.startsWith(encPrefix)) { + try { + return resolveValue(value.substring(encPrefix.length())); + } catch (Exception e) { + return value; + } + } + //不需要解密的值直接返回 + return value; + } + + /** + * Resolve value string. + * + * @param value the value + * @return the string + */ + private String resolveValue(String value) throws IllegalBlockSizeException, InvalidKeyException, + BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { + //自定义密文解密 + byte[] encode = CryptoHelper.aes256Decryption(CryptoHelper.base64Decryption(value), password); + + return new String(encode, StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/com/cmhi/game_database_service/security/protocol/DecryptRequestProtocol.java b/src/main/java/com/cmhi/game_database_service/security/protocol/DecryptRequestProtocol.java new file mode 100644 index 0000000..cfa600c --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/security/protocol/DecryptRequestProtocol.java @@ -0,0 +1,66 @@ +package com.cmhi.game_database_service.security.protocol; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.IOUtils; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +/** + * The type Decrypt request protocol. + * + * @author + */ +@Slf4j +public class DecryptRequestProtocol implements HttpInputMessage { + + /** + * The Input message. + */ + private final HttpInputMessage inputMessage; + + /** + * The Msg content. + */ + private final String msgContent; + + /** + * Instantiates a new Decrypt request protocol. + * + * @param inputMessage the input message + * @param msgContent the msg content + */ + @Contract(pure = true) + public DecryptRequestProtocol(HttpInputMessage inputMessage, String msgContent) { + this.inputMessage = inputMessage; + this.msgContent = msgContent; + } + + /** + * Gets body. + * + * @return the body + */ + @Override + @NotNull + public InputStream getBody() throws IOException { + // 返回解密后的内容 + return IOUtils.toInputStream(msgContent, StandardCharsets.UTF_8.toString()); + } + + /** + * Gets headers. + * + * @return the headers + */ + @Override + @NotNull + public HttpHeaders getHeaders() { + return inputMessage.getHeaders(); + } +} diff --git a/src/main/java/com/cmhi/game_database_service/validation/ValidGroups.java b/src/main/java/com/cmhi/game_database_service/validation/ValidGroups.java new file mode 100644 index 0000000..cca99b8 --- /dev/null +++ b/src/main/java/com/cmhi/game_database_service/validation/ValidGroups.java @@ -0,0 +1,112 @@ +package com.cmhi.game_database_service.validation; + +/** + * The interface Valid groups. + * + * @author + */ +public interface ValidGroups { + /** + * The interface Protocol common valid. + * + * @author + */ + interface ProtocolCommonValid { + } + + /** + * The interface Login req valid. + * + * @author + */ + interface LoginReqValid extends LogoutReqValid { + } + + /** + * The interface Logout req valid. + * + * @author + */ + interface LogoutReqValid extends ProtocolCommonValid { + } + + /** + * The interface Upgrade device valid. + * + * @author + */ + interface UpgradeDeviceValid extends ProtocolCommonValid { + } + + /** + * The interface Add device valid. + * + * @author + */ + interface AddDeviceValid extends UpgradeDeviceValid { + } + + /** + * The interface Id array valid. + * + * @author + */ + interface IdArrayValid extends ProtocolCommonValid { + } + + /** + * The interface Explicit id array valid. + * + * @author + */ + interface ExplicitIdArrayValid extends IdArrayValid { + } + + /** + * The interface Task start req common valid. + * + * @author + */ + interface TaskStartReqCommonValid extends ProtocolCommonValid { + } + + /** + * The interface Task start req valid. + * + * @author + */ + interface TaskStartReqValid extends TaskStartReqCommonValid { + } + + /** + * The interface Task start mul req valid. + * + * @author + */ + interface TaskStartMulReqValid extends TaskStartReqCommonValid { + } + + /** + * The interface Task stop req valid. + * + * @author + */ + interface TaskStopReqValid extends ProtocolCommonValid { + } + + /** + * The interface Get dev ver req valid. + * + * @author + */ + interface GetDevVerReqValid extends ProtocolCommonValid { + } + + /** + * The interface Add device valid. + * + * @author + */ + interface AddUserInfoValid extends ProtocolCommonValid { + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/src/test/java/com/cmhi/game_database_service/GameDatabaseServiceApplicationTests.java b/src/test/java/com/cmhi/game_database_service/GameDatabaseServiceApplicationTests.java new file mode 100644 index 0000000..6d6014b --- /dev/null +++ b/src/test/java/com/cmhi/game_database_service/GameDatabaseServiceApplicationTests.java @@ -0,0 +1,13 @@ +package com.cmhi.game_database_service; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class GameDatabaseServiceApplicationTests { + + @Test + void contextLoads() { + } + +}