forked from gushen/template-springboot-hucky
init: first commit
This commit is contained in:
2
.gitattributes
vendored
Normal file
2
.gitattributes
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/mvnw text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
36
.gitignore
vendored
Normal file
36
.gitignore
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
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/
|
||||
|
||||
### Application ###
|
||||
/src/main/resources/application.yaml
|
||||
3
.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
3
.mvn/wrapper/maven-wrapper.properties
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip
|
||||
295
mvnw
vendored
Normal file
295
mvnw
vendored
Normal file
@@ -0,0 +1,295 @@
|
||||
#!/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
|
||||
#
|
||||
# http://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.3.4
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
|
||||
# MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
set -euf
|
||||
[ "${MVNW_VERBOSE-}" != debug ] || set -x
|
||||
|
||||
# OS specific support.
|
||||
native_path() { printf %s\\n "$1"; }
|
||||
case "$(uname)" in
|
||||
CYGWIN* | MINGW*)
|
||||
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
|
||||
native_path() { cygpath --path --windows "$1"; }
|
||||
;;
|
||||
esac
|
||||
|
||||
# set JAVACMD and JAVACCMD
|
||||
set_java_home() {
|
||||
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
|
||||
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"
|
||||
JAVACCMD="$JAVA_HOME/jre/sh/javac"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACCMD="$JAVA_HOME/bin/javac"
|
||||
|
||||
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
|
||||
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
|
||||
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
else
|
||||
JAVACMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v java
|
||||
)" || :
|
||||
JAVACCMD="$(
|
||||
'set' +e
|
||||
'unset' -f command 2>/dev/null
|
||||
'command' -v javac
|
||||
)" || :
|
||||
|
||||
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
|
||||
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# hash string like Java String::hashCode
|
||||
hash_string() {
|
||||
str="${1:-}" h=0
|
||||
while [ -n "$str" ]; do
|
||||
char="${str%"${str#?}"}"
|
||||
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
|
||||
str="${str#?}"
|
||||
done
|
||||
printf %x\\n $h
|
||||
}
|
||||
|
||||
verbose() { :; }
|
||||
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
|
||||
|
||||
die() {
|
||||
printf %s\\n "$1" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
trim() {
|
||||
# MWRAPPER-139:
|
||||
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
|
||||
# Needed for removing poorly interpreted newline sequences when running in more
|
||||
# exotic environments such as mingw bash on Windows.
|
||||
printf "%s" "${1}" | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
scriptDir="$(dirname "$0")"
|
||||
scriptName="$(basename "$0")"
|
||||
|
||||
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
|
||||
while IFS="=" read -r key value; do
|
||||
case "${key-}" in
|
||||
distributionUrl) distributionUrl=$(trim "${value-}") ;;
|
||||
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
|
||||
esac
|
||||
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
|
||||
case "${distributionUrl##*/}" in
|
||||
maven-mvnd-*bin.*)
|
||||
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
|
||||
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
|
||||
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
|
||||
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
|
||||
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
|
||||
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
|
||||
*)
|
||||
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
|
||||
distributionPlatform=linux-amd64
|
||||
;;
|
||||
esac
|
||||
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
|
||||
;;
|
||||
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
|
||||
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
|
||||
esac
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
distributionUrlNameMain="${distributionUrlName%.*}"
|
||||
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
|
||||
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
|
||||
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
|
||||
|
||||
exec_maven() {
|
||||
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
|
||||
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
|
||||
}
|
||||
|
||||
if [ -d "$MAVEN_HOME" ]; then
|
||||
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
exec_maven "$@"
|
||||
fi
|
||||
|
||||
case "${distributionUrl-}" in
|
||||
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
|
||||
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
|
||||
esac
|
||||
|
||||
# prepare tmp dir
|
||||
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
|
||||
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
|
||||
trap clean HUP INT TERM EXIT
|
||||
else
|
||||
die "cannot create temp dir"
|
||||
fi
|
||||
|
||||
mkdir -p -- "${MAVEN_HOME%/*}"
|
||||
|
||||
# Download and Install Apache Maven
|
||||
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
verbose "Downloading from: $distributionUrl"
|
||||
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
# select .zip or .tar.gz
|
||||
if ! command -v unzip >/dev/null; then
|
||||
distributionUrl="${distributionUrl%.zip}.tar.gz"
|
||||
distributionUrlName="${distributionUrl##*/}"
|
||||
fi
|
||||
|
||||
# verbose opt
|
||||
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
|
||||
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
|
||||
|
||||
# normalize http auth
|
||||
case "${MVNW_PASSWORD:+has-password}" in
|
||||
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
|
||||
esac
|
||||
|
||||
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
|
||||
verbose "Found wget ... using wget"
|
||||
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
|
||||
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
|
||||
verbose "Found curl ... using curl"
|
||||
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
|
||||
elif set_java_home; then
|
||||
verbose "Falling back to use Java to download"
|
||||
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
|
||||
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
cat >"$javaSource" <<-END
|
||||
public class Downloader extends java.net.Authenticator
|
||||
{
|
||||
protected java.net.PasswordAuthentication getPasswordAuthentication()
|
||||
{
|
||||
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
|
||||
}
|
||||
public static void main( String[] args ) throws Exception
|
||||
{
|
||||
setDefault( new Downloader() );
|
||||
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
|
||||
}
|
||||
}
|
||||
END
|
||||
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
|
||||
verbose " - Compiling Downloader.java ..."
|
||||
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
|
||||
verbose " - Running Downloader.java ..."
|
||||
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
|
||||
fi
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
if [ -n "${distributionSha256Sum-}" ]; then
|
||||
distributionSha256Result=false
|
||||
if [ "$MVN_CMD" = mvnd.sh ]; then
|
||||
echo "Checksum validation is not supported for maven-mvnd." >&2
|
||||
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
elif command -v sha256sum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
elif command -v shasum >/dev/null; then
|
||||
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
|
||||
distributionSha256Result=true
|
||||
fi
|
||||
else
|
||||
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
|
||||
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ $distributionSha256Result = false ]; then
|
||||
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
|
||||
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# unzip and move
|
||||
if command -v unzip >/dev/null; then
|
||||
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
|
||||
else
|
||||
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
|
||||
fi
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
actualDistributionDir=""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
|
||||
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$distributionUrlNameMain"
|
||||
fi
|
||||
fi
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
# enable globbing to iterate over items
|
||||
set +f
|
||||
for dir in "$TMP_DOWNLOAD_DIR"/*; do
|
||||
if [ -d "$dir" ]; then
|
||||
if [ -f "$dir/bin/$MVN_CMD" ]; then
|
||||
actualDistributionDir="$(basename "$dir")"
|
||||
break
|
||||
fi
|
||||
fi
|
||||
done
|
||||
set -f
|
||||
fi
|
||||
|
||||
if [ -z "$actualDistributionDir" ]; then
|
||||
verbose "Contents of $TMP_DOWNLOAD_DIR:"
|
||||
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
|
||||
die "Could not find Maven distribution directory in extracted archive"
|
||||
fi
|
||||
|
||||
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
|
||||
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
|
||||
|
||||
clean || :
|
||||
exec_maven "$@"
|
||||
189
mvnw.cmd
vendored
Normal file
189
mvnw.cmd
vendored
Normal file
@@ -0,0 +1,189 @@
|
||||
<# : batch portion
|
||||
@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 http://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.3.4
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM MVNW_REPOURL - repo url base for downloading maven distribution
|
||||
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
|
||||
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
|
||||
@SET __MVNW_CMD__=
|
||||
@SET __MVNW_ERROR__=
|
||||
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
|
||||
@SET PSModulePath=
|
||||
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
|
||||
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
|
||||
)
|
||||
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
|
||||
@SET __MVNW_PSMODULEP_SAVE=
|
||||
@SET __MVNW_ARG0_NAME__=
|
||||
@SET MVNW_USERNAME=
|
||||
@SET MVNW_PASSWORD=
|
||||
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
|
||||
@echo Cannot start maven from wrapper >&2 && exit /b 1
|
||||
@GOTO :EOF
|
||||
: end batch / begin powershell #>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
if ($env:MVNW_VERBOSE -eq "true") {
|
||||
$VerbosePreference = "Continue"
|
||||
}
|
||||
|
||||
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
|
||||
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
|
||||
if (!$distributionUrl) {
|
||||
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
|
||||
}
|
||||
|
||||
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
|
||||
"maven-mvnd-*" {
|
||||
$USE_MVND = $true
|
||||
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
|
||||
$MVN_CMD = "mvnd.cmd"
|
||||
break
|
||||
}
|
||||
default {
|
||||
$USE_MVND = $false
|
||||
$MVN_CMD = $script -replace '^mvnw','mvn'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# apply MVNW_REPOURL and calculate MAVEN_HOME
|
||||
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
|
||||
if ($env:MVNW_REPOURL) {
|
||||
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
|
||||
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
|
||||
}
|
||||
$distributionUrlName = $distributionUrl -replace '^.*/',''
|
||||
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
|
||||
|
||||
$MAVEN_M2_PATH = "$HOME/.m2"
|
||||
if ($env:MAVEN_USER_HOME) {
|
||||
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
|
||||
}
|
||||
|
||||
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
|
||||
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
|
||||
}
|
||||
|
||||
$MAVEN_WRAPPER_DISTS = $null
|
||||
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
|
||||
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
|
||||
} else {
|
||||
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
|
||||
}
|
||||
|
||||
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
|
||||
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
|
||||
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
|
||||
|
||||
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
|
||||
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
exit $?
|
||||
}
|
||||
|
||||
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
|
||||
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
|
||||
}
|
||||
|
||||
# prepare tmp dir
|
||||
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
|
||||
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
|
||||
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
|
||||
trap {
|
||||
if ($TMP_DOWNLOAD_DIR.Exists) {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
}
|
||||
|
||||
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
|
||||
|
||||
# Download and Install Apache Maven
|
||||
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
|
||||
Write-Verbose "Downloading from: $distributionUrl"
|
||||
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
|
||||
|
||||
$webclient = New-Object System.Net.WebClient
|
||||
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
|
||||
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
|
||||
}
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
|
||||
|
||||
# If specified, validate the SHA-256 sum of the Maven distribution zip file
|
||||
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
|
||||
if ($distributionSha256Sum) {
|
||||
if ($USE_MVND) {
|
||||
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
|
||||
}
|
||||
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
|
||||
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
|
||||
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
|
||||
}
|
||||
}
|
||||
|
||||
# unzip and move
|
||||
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
|
||||
|
||||
# Find the actual extracted directory name (handles snapshots where filename != directory name)
|
||||
$actualDistributionDir = ""
|
||||
|
||||
# First try the expected directory name (for regular distributions)
|
||||
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
|
||||
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
|
||||
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
|
||||
$actualDistributionDir = $distributionUrlNameMain
|
||||
}
|
||||
|
||||
# If not found, search for any directory with the Maven executable (for snapshots)
|
||||
if (!$actualDistributionDir) {
|
||||
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
|
||||
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
|
||||
if (Test-Path -Path $testPath -PathType Leaf) {
|
||||
$actualDistributionDir = $_.Name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$actualDistributionDir) {
|
||||
Write-Error "Could not find Maven distribution directory in extracted archive"
|
||||
}
|
||||
|
||||
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
|
||||
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
|
||||
try {
|
||||
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
|
||||
} catch {
|
||||
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
|
||||
Write-Error "fail to move MAVEN_HOME"
|
||||
}
|
||||
} finally {
|
||||
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
|
||||
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
|
||||
}
|
||||
|
||||
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
|
||||
136
pom.xml
Normal file
136
pom.xml
Normal file
@@ -0,0 +1,136 @@
|
||||
<?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>3.2.3</version>
|
||||
<relativePath /> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>icu.sunway</groupId>
|
||||
<artifactId>sunway-user-sys</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<name>sunway-user-sys</name>
|
||||
<description>Sunway User System</description>
|
||||
<url />
|
||||
<licenses>
|
||||
<license />
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer />
|
||||
</developers>
|
||||
<scm>
|
||||
<connection />
|
||||
<developerConnection />
|
||||
<tag />
|
||||
<url />
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
<springdoc.version>2.2.0</springdoc.version>
|
||||
<lombok.version>1.18.30</lombok.version>
|
||||
<mybatis-plus.version>3.5.5</mybatis-plus.version>
|
||||
<dynamic-datasource.version>4.3.1</dynamic-datasource.version>
|
||||
<mysql.version>8.0.33</mysql.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<!-- 核心依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 数据库相关 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<version>${mysql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
|
||||
<version>${mybatis-plus.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 工具类 -->
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>0.11.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>0.11.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>0.11.5</version>
|
||||
</dependency>
|
||||
<!-- 添加验证依赖 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<!-- API文档 -->
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>${springdoc.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 安全 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 测试 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- 动态数据源 -->
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
|
||||
<version>${dynamic-datasource.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,13 @@
|
||||
package icu.sunway.ai_spring_example;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class AiSpringExampleApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AiSpringExampleApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package icu.sunway.ai_spring_example.Config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 跨域配置类
|
||||
* 用于配置允许的跨域请求来源、方法、头信息等
|
||||
*/
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
|
||||
@Bean
|
||||
public CorsFilter corsFilter() {
|
||||
// 创建CorsConfiguration对象
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
|
||||
// 允许所有域名进行跨域请求
|
||||
config.addAllowedOriginPattern("*");
|
||||
|
||||
// 允许的请求头
|
||||
config.addAllowedHeader("*");
|
||||
|
||||
// 允许的请求方法
|
||||
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
|
||||
|
||||
// 允许发送Cookie
|
||||
config.setAllowCredentials(true);
|
||||
|
||||
// 预检请求的有效期,单位为秒
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
// 创建UrlBasedCorsConfigurationSource对象
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
|
||||
// 对所有URL应用跨域配置
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
|
||||
// 返回CorsFilter实例
|
||||
return new CorsFilter(source);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package icu.sunway.ai_spring_example.Config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
|
||||
redisTemplate.setConnectionFactory(redisConnectionFactory);
|
||||
|
||||
// 设置键的序列化器为 StringRedisSerializer
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
|
||||
|
||||
// 设置值的序列化器为 GenericJackson2JsonRedisSerializer
|
||||
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
|
||||
redisTemplate.setValueSerializer(serializer);
|
||||
redisTemplate.setHashValueSerializer(serializer);
|
||||
|
||||
redisTemplate.afterPropertiesSet();
|
||||
return redisTemplate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package icu.sunway.ai_spring_example.Config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
// 启用跨域配置
|
||||
.cors(cors -> cors.configurationSource(
|
||||
request -> new org.springframework.web.cors.CorsConfiguration().applyPermitDefaultValues()))
|
||||
// 禁用默认的登录表单和HTTP基本认证
|
||||
.formLogin(form -> form.disable())
|
||||
.httpBasic(basic -> basic.disable())
|
||||
// 允许所有请求通过,取消默认登录验证
|
||||
.authorizeHttpRequests((authz) -> authz
|
||||
.anyRequest().permitAll())
|
||||
// 禁用CSRF保护
|
||||
.csrf(csrf -> csrf.disable())
|
||||
// 设置会话创建策略为无状态
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package icu.sunway.ai_spring_example.Controllers;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import icu.sunway.ai_spring_example.Service.IExampleEntityService;
|
||||
|
||||
@Controller
|
||||
@RestController
|
||||
@RequestMapping("/example")
|
||||
public class EaxmpleEntityController {
|
||||
@Resource
|
||||
private IExampleEntityService exampleEntityService;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package icu.sunway.ai_spring_example.Entity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@TableName("example_entity")
|
||||
public class ExampleEntity {
|
||||
private Long id;
|
||||
private String name;
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package icu.sunway.ai_spring_example.Mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
|
||||
import icu.sunway.ai_spring_example.Entity.ExampleEntity;
|
||||
|
||||
@Mapper
|
||||
public interface ExampleEntityMapper extends BaseMapper<ExampleEntity> {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package icu.sunway.ai_spring_example.Service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import icu.sunway.ai_spring_example.Entity.ExampleEntity;
|
||||
|
||||
public interface IExampleEntityService extends IService<ExampleEntity> {
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package icu.sunway.ai_spring_example.Service.Implements;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import icu.sunway.ai_spring_example.Entity.ExampleEntity;
|
||||
import icu.sunway.ai_spring_example.Mapper.ExampleEntityMapper;
|
||||
import icu.sunway.ai_spring_example.Service.IExampleEntityService;
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class ExampleEntityServiceImpl extends ServiceImpl<ExampleEntityMapper, ExampleEntity>
|
||||
implements IExampleEntityService {
|
||||
|
||||
@Resource
|
||||
private ExampleEntityMapper exampleEntityMapper;
|
||||
|
||||
}
|
||||
287
src/main/java/icu/sunway/ai_spring_example/Utils/DateUtils.java
Normal file
287
src/main/java/icu/sunway/ai_spring_example/Utils/DateUtils.java
Normal file
@@ -0,0 +1,287 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import java.time.*;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 日期时间工具类
|
||||
*/
|
||||
public class DateUtils {
|
||||
|
||||
/**
|
||||
* 常用日期时间格式
|
||||
*/
|
||||
public static final String FORMAT_DATE = "yyyy-MM-dd";
|
||||
public static final String FORMAT_TIME = "HH:mm:ss";
|
||||
public static final String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss";
|
||||
public static final String FORMAT_DATETIME_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
|
||||
public static final String FORMAT_DATE_CHINESE = "yyyy年MM月dd日";
|
||||
public static final String FORMAT_DATETIME_CHINESE = "yyyy年MM月dd日 HH时mm分ss秒";
|
||||
|
||||
/**
|
||||
* 获取当前日期时间
|
||||
*
|
||||
* @return LocalDateTime
|
||||
*/
|
||||
public static LocalDateTime now() {
|
||||
return LocalDateTime.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期
|
||||
*
|
||||
* @return LocalDate
|
||||
*/
|
||||
public static LocalDate today() {
|
||||
return LocalDate.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间
|
||||
*
|
||||
* @return LocalTime
|
||||
*/
|
||||
public static LocalTime currentTime() {
|
||||
return LocalTime.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期时间
|
||||
*
|
||||
* @param dateTime 日期时间
|
||||
* @param pattern 格式
|
||||
* @return 格式化后的字符串
|
||||
*/
|
||||
public static String format(LocalDateTime dateTime, String pattern) {
|
||||
if (dateTime == null) {
|
||||
return null;
|
||||
}
|
||||
return dateTime.format(DateTimeFormatter.ofPattern(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期
|
||||
*
|
||||
* @param date 日期
|
||||
* @param pattern 格式
|
||||
* @return 格式化后的字符串
|
||||
*/
|
||||
public static String format(LocalDate date, String pattern) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
return date.format(DateTimeFormatter.ofPattern(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化时间
|
||||
*
|
||||
* @param time 时间
|
||||
* @param pattern 格式
|
||||
* @return 格式化后的字符串
|
||||
*/
|
||||
public static String format(LocalTime time, String pattern) {
|
||||
if (time == null) {
|
||||
return null;
|
||||
}
|
||||
return time.format(DateTimeFormatter.ofPattern(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析日期时间字符串
|
||||
*
|
||||
* @param dateTimeStr 日期时间字符串
|
||||
* @param pattern 格式
|
||||
* @return LocalDateTime
|
||||
*/
|
||||
public static LocalDateTime parseDateTime(String dateTimeStr, String pattern) {
|
||||
if (dateTimeStr == null || dateTimeStr.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析日期字符串
|
||||
*
|
||||
* @param dateStr 日期字符串
|
||||
* @param pattern 格式
|
||||
* @return LocalDate
|
||||
*/
|
||||
public static LocalDate parseDate(String dateStr, String pattern) {
|
||||
if (dateStr == null || dateStr.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析时间字符串
|
||||
*
|
||||
* @param timeStr 时间字符串
|
||||
* @param pattern 格式
|
||||
* @return LocalTime
|
||||
*/
|
||||
public static LocalTime parseTime(String timeStr, String pattern) {
|
||||
if (timeStr == null || timeStr.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return LocalTime.parse(timeStr, DateTimeFormatter.ofPattern(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* Date转LocalDateTime
|
||||
*
|
||||
* @param date Date
|
||||
* @return LocalDateTime
|
||||
*/
|
||||
public static LocalDateTime dateToLocalDateTime(Date date) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* LocalDateTime转Date
|
||||
*
|
||||
* @param dateTime LocalDateTime
|
||||
* @return Date
|
||||
*/
|
||||
public static Date localDateTimeToDate(LocalDateTime dateTime) {
|
||||
if (dateTime == null) {
|
||||
return null;
|
||||
}
|
||||
return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算两个日期时间之间的差值
|
||||
*
|
||||
* @param start 开始时间
|
||||
* @param end 结束时间
|
||||
* @param unit 时间单位
|
||||
* @return 差值
|
||||
*/
|
||||
public static long between(LocalDateTime start, LocalDateTime end, ChronoUnit unit) {
|
||||
if (start == null || end == null || unit == null) {
|
||||
return 0;
|
||||
}
|
||||
return unit.between(start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期时间加减
|
||||
*
|
||||
* @param dateTime 日期时间
|
||||
* @param amount 数量
|
||||
* @param unit 时间单位
|
||||
* @return 计算后的日期时间
|
||||
*/
|
||||
public static LocalDateTime plus(LocalDateTime dateTime, long amount, ChronoUnit unit) {
|
||||
if (dateTime == null || unit == null) {
|
||||
return null;
|
||||
}
|
||||
return dateTime.plus(amount, unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期时间加减
|
||||
*
|
||||
* @param dateTime 日期时间
|
||||
* @param amount 数量
|
||||
* @param unit 时间单位
|
||||
* @return 计算后的日期时间
|
||||
*/
|
||||
public static LocalDateTime minus(LocalDateTime dateTime, long amount, ChronoUnit unit) {
|
||||
if (dateTime == null || unit == null) {
|
||||
return null;
|
||||
}
|
||||
return dateTime.minus(amount, unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本周的第一天(周一)
|
||||
*
|
||||
* @return LocalDate
|
||||
*/
|
||||
public static LocalDate firstDayOfWeek() {
|
||||
return today().with(DayOfWeek.MONDAY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本周的最后一天(周日)
|
||||
*
|
||||
* @return LocalDate
|
||||
*/
|
||||
public static LocalDate lastDayOfWeek() {
|
||||
return today().with(DayOfWeek.SUNDAY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本月的第一天
|
||||
*
|
||||
* @return LocalDate
|
||||
*/
|
||||
public static LocalDate firstDayOfMonth() {
|
||||
return today().withDayOfMonth(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本月的最后一天
|
||||
*
|
||||
* @return LocalDate
|
||||
*/
|
||||
public static LocalDate lastDayOfMonth() {
|
||||
return today().withDayOfMonth(today().lengthOfMonth());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本年的第一天
|
||||
*
|
||||
* @return LocalDate
|
||||
*/
|
||||
public static LocalDate firstDayOfYear() {
|
||||
return today().withDayOfYear(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本年的最后一天
|
||||
*
|
||||
* @return LocalDate
|
||||
*/
|
||||
public static LocalDate lastDayOfYear() {
|
||||
return today().withDayOfYear(today().lengthOfYear());
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断两个日期是否是同一天
|
||||
*
|
||||
* @param date1 日期1
|
||||
* @param date2 日期2
|
||||
* @return 是否是同一天
|
||||
*/
|
||||
public static boolean isSameDay(LocalDateTime date1, LocalDateTime date2) {
|
||||
if (date1 == null || date2 == null) {
|
||||
return false;
|
||||
}
|
||||
return date1.toLocalDate().isEqual(date2.toLocalDate());
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断日期是否在指定范围内
|
||||
*
|
||||
* @param dateTime 日期时间
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @return 是否在范围内
|
||||
*/
|
||||
public static boolean isBetween(LocalDateTime dateTime, LocalDateTime startTime, LocalDateTime endTime) {
|
||||
if (dateTime == null || startTime == null || endTime == null) {
|
||||
return false;
|
||||
}
|
||||
return dateTime.isAfter(startTime) && dateTime.isBefore(endTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* 加密工具类
|
||||
*/
|
||||
public class EncryptUtils {
|
||||
|
||||
/**
|
||||
* MD5加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String md5(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
|
||||
return byteArrayToHexString(bytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SHA-1加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String sha1(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-1");
|
||||
byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
|
||||
return byteArrayToHexString(bytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SHA-256加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String sha256(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
|
||||
return byteArrayToHexString(bytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SHA-512加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String sha512(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-512");
|
||||
byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
|
||||
return byteArrayToHexString(bytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* BASE64加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String base64Encode(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* BASE64解密
|
||||
*
|
||||
* @param str 待解密字符串
|
||||
* @return 解密后字符串
|
||||
*/
|
||||
public static String base64Decode(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return new String(Base64.getDecoder().decode(str), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* HMAC-MD5加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @param key 密钥
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String hmacMd5(String str, String key) {
|
||||
return hmac(str, key, "HmacMD5");
|
||||
}
|
||||
|
||||
/**
|
||||
* HMAC-SHA1加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @param key 密钥
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String hmacSha1(String str, String key) {
|
||||
return hmac(str, key, "HmacSHA1");
|
||||
}
|
||||
|
||||
/**
|
||||
* HMAC-SHA256加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @param key 密钥
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String hmacSha256(String str, String key) {
|
||||
return hmac(str, key, "HmacSHA256");
|
||||
}
|
||||
|
||||
/**
|
||||
* HMAC-SHA512加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @param key 密钥
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String hmacSha512(String str, String key) {
|
||||
return hmac(str, key, "HmacSHA512");
|
||||
}
|
||||
|
||||
/**
|
||||
* HMAC通用加密方法
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @param key 密钥
|
||||
* @param algorithm 算法
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
private static String hmac(String str, String key, String algorithm) {
|
||||
if (str == null || str.isEmpty() || key == null || key.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), algorithm);
|
||||
Mac mac = Mac.getInstance(algorithm);
|
||||
mac.init(secretKeySpec);
|
||||
byte[] bytes = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
|
||||
return byteArrayToHexString(bytes);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字节数组转换为十六进制字符串
|
||||
*
|
||||
* @param bytes 字节数组
|
||||
* @return 十六进制字符串
|
||||
*/
|
||||
private static String byteArrayToHexString(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte aByte : bytes) {
|
||||
String hex = Integer.toHexString(0xFF & aByte);
|
||||
if (hex.length() == 1) {
|
||||
sb.append('0');
|
||||
}
|
||||
sb.append(hex);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机字符串
|
||||
*
|
||||
* @param length 长度
|
||||
* @return 随机字符串
|
||||
*/
|
||||
public static String generateRandomString(int length) {
|
||||
if (length <= 0) {
|
||||
return "";
|
||||
}
|
||||
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
int index = (int) (Math.random() * characters.length());
|
||||
sb.append(characters.charAt(index));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成盐值
|
||||
*
|
||||
* @return 盐值
|
||||
*/
|
||||
public static String generateSalt() {
|
||||
return generateRandomString(16);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带盐值的MD5加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @param salt 盐值
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String md5WithSalt(String str, String salt) {
|
||||
return md5(str + salt);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带盐值的SHA-256加密
|
||||
*
|
||||
* @param str 待加密字符串
|
||||
* @param salt 盐值
|
||||
* @return 加密后字符串
|
||||
*/
|
||||
public static String sha256WithSalt(String str, String salt) {
|
||||
return sha256(str + salt);
|
||||
}
|
||||
}
|
||||
352
src/main/java/icu/sunway/ai_spring_example/Utils/FileUtils.java
Normal file
352
src/main/java/icu/sunway/ai_spring_example/Utils/FileUtils.java
Normal file
@@ -0,0 +1,352 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 文件工具类
|
||||
*/
|
||||
public class FileUtils {
|
||||
|
||||
/**
|
||||
* 获取文件扩展名
|
||||
*
|
||||
* @param fileName 文件名
|
||||
* @return 扩展名
|
||||
*/
|
||||
public static String getFileExtension(String fileName) {
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
int lastDotIndex = fileName.lastIndexOf('.');
|
||||
if (lastDotIndex == -1 || lastDotIndex == fileName.length() - 1) {
|
||||
return null;
|
||||
}
|
||||
return fileName.substring(lastDotIndex + 1).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件名(不含扩展名)
|
||||
*
|
||||
* @param fileName 文件名
|
||||
* @return 文件名(不含扩展名)
|
||||
*/
|
||||
public static String getFileNameWithoutExtension(String fileName) {
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
int lastDotIndex = fileName.lastIndexOf('.');
|
||||
if (lastDotIndex == -1) {
|
||||
return fileName;
|
||||
}
|
||||
return fileName.substring(0, lastDotIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建目录
|
||||
*
|
||||
* @param directoryPath 目录路径
|
||||
* @return 是否创建成功
|
||||
*/
|
||||
public static boolean createDirectory(String directoryPath) {
|
||||
if (directoryPath == null || directoryPath.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
Path path = Paths.get(directoryPath);
|
||||
if (Files.exists(path)) {
|
||||
return Files.isDirectory(path);
|
||||
}
|
||||
try {
|
||||
Files.createDirectories(path);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制文件
|
||||
*
|
||||
* @param sourcePath 源文件路径
|
||||
* @param targetPath 目标文件路径
|
||||
* @return 是否复制成功
|
||||
*/
|
||||
public static boolean copyFile(String sourcePath, String targetPath) {
|
||||
if (sourcePath == null || targetPath == null) {
|
||||
return false;
|
||||
}
|
||||
Path source = Paths.get(sourcePath);
|
||||
Path target = Paths.get(targetPath);
|
||||
try {
|
||||
// 创建目标文件的父目录
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移动文件
|
||||
*
|
||||
* @param sourcePath 源文件路径
|
||||
* @param targetPath 目标文件路径
|
||||
* @return 是否移动成功
|
||||
*/
|
||||
public static boolean moveFile(String sourcePath, String targetPath) {
|
||||
if (sourcePath == null || targetPath == null) {
|
||||
return false;
|
||||
}
|
||||
Path source = Paths.get(sourcePath);
|
||||
Path target = Paths.get(targetPath);
|
||||
try {
|
||||
// 创建目标文件的父目录
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除文件
|
||||
*
|
||||
* @param filePath 文件路径
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
public static boolean deleteFile(String filePath) {
|
||||
if (filePath == null) {
|
||||
return false;
|
||||
}
|
||||
Path path = Paths.get(filePath);
|
||||
try {
|
||||
return Files.deleteIfExists(path);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除目录(递归删除)
|
||||
*
|
||||
* @param directoryPath 目录路径
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
public static boolean deleteDirectory(String directoryPath) {
|
||||
if (directoryPath == null) {
|
||||
return false;
|
||||
}
|
||||
Path path = Paths.get(directoryPath);
|
||||
if (!Files.exists(path) || !Files.isDirectory(path)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||
Files.delete(file);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
|
||||
Files.delete(dir);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件大小
|
||||
*
|
||||
* @param filePath 文件路径
|
||||
* @return 文件大小(字节)
|
||||
*/
|
||||
public static long getFileSize(String filePath) {
|
||||
if (filePath == null) {
|
||||
return 0;
|
||||
}
|
||||
Path path = Paths.get(filePath);
|
||||
try {
|
||||
return Files.size(path);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件是否存在
|
||||
*
|
||||
* @param filePath 文件路径
|
||||
* @return 是否存在
|
||||
*/
|
||||
public static boolean exists(String filePath) {
|
||||
if (filePath == null) {
|
||||
return false;
|
||||
}
|
||||
return Files.exists(Paths.get(filePath));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是目录
|
||||
*
|
||||
* @param path 路径
|
||||
* @return 是否是目录
|
||||
*/
|
||||
public static boolean isDirectory(String path) {
|
||||
if (path == null) {
|
||||
return false;
|
||||
}
|
||||
return Files.isDirectory(Paths.get(path));
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件内容
|
||||
*
|
||||
* @param filePath 文件路径
|
||||
* @return 文件内容
|
||||
*/
|
||||
public static String readFile(String filePath) {
|
||||
if (filePath == null) {
|
||||
return null;
|
||||
}
|
||||
Path path = Paths.get(filePath);
|
||||
try {
|
||||
return Files.readString(path, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取文件内容(按行读取)
|
||||
*
|
||||
* @param filePath 文件路径
|
||||
* @return 文件内容列表
|
||||
*/
|
||||
public static List<String> readFileLines(String filePath) {
|
||||
if (filePath == null) {
|
||||
return null;
|
||||
}
|
||||
Path path = Paths.get(filePath);
|
||||
try {
|
||||
return Files.readAllLines(path, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入文件内容
|
||||
*
|
||||
* @param filePath 文件路径
|
||||
* @param content 内容
|
||||
* @return 是否写入成功
|
||||
*/
|
||||
public static boolean writeFile(String filePath, String content) {
|
||||
if (filePath == null || content == null) {
|
||||
return false;
|
||||
}
|
||||
Path path = Paths.get(filePath);
|
||||
try {
|
||||
// 创建父目录
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, content, StandardCharsets.UTF_8);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加写入文件内容
|
||||
*
|
||||
* @param filePath 文件路径
|
||||
* @param content 内容
|
||||
* @return 是否写入成功
|
||||
*/
|
||||
public static boolean appendFile(String filePath, String content) {
|
||||
if (filePath == null || content == null) {
|
||||
return false;
|
||||
}
|
||||
Path path = Paths.get(filePath);
|
||||
try {
|
||||
// 创建父目录
|
||||
Files.createDirectories(path.getParent());
|
||||
Files.writeString(path, content, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出目录下的文件
|
||||
*
|
||||
* @param directoryPath 目录路径
|
||||
* @return 文件列表
|
||||
*/
|
||||
public static List<File> listFiles(String directoryPath) {
|
||||
if (directoryPath == null) {
|
||||
return null;
|
||||
}
|
||||
File directory = new File(directoryPath);
|
||||
if (!directory.exists() || !directory.isDirectory()) {
|
||||
return null;
|
||||
}
|
||||
File[] files = directory.listFiles();
|
||||
if (files == null) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<File> fileList = new ArrayList<>();
|
||||
for (File file : files) {
|
||||
fileList.add(file);
|
||||
}
|
||||
return fileList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化文件大小
|
||||
*
|
||||
* @param size 文件大小(字节)
|
||||
* @return 格式化后的文件大小
|
||||
*/
|
||||
public static String formatFileSize(long size) {
|
||||
if (size < 0) {
|
||||
return "-" + formatFileSize(-size);
|
||||
}
|
||||
if (size < 1024) {
|
||||
return size + " B";
|
||||
}
|
||||
if (size < 1024 * 1024) {
|
||||
return String.format("%.2f KB", size / 1024.0);
|
||||
}
|
||||
if (size < 1024 * 1024 * 1024) {
|
||||
return String.format("%.2f MB", size / (1024.0 * 1024.0));
|
||||
}
|
||||
if (size < 1024L * 1024L * 1024L * 1024L) {
|
||||
return String.format("%.2f GB", size / (1024.0 * 1024.0 * 1024.0));
|
||||
}
|
||||
return String.format("%.2f TB", size / (1024.0 * 1024.0 * 1024.0 * 1024.0));
|
||||
}
|
||||
}
|
||||
310
src/main/java/icu/sunway/ai_spring_example/Utils/HttpUtil.java
Normal file
310
src/main/java/icu/sunway/ai_spring_example/Utils/HttpUtil.java
Normal file
@@ -0,0 +1,310 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* HTTP工具类,用于发送HTTP请求
|
||||
*/
|
||||
public class HttpUtil {
|
||||
|
||||
private static final RestTemplate restTemplate;
|
||||
|
||||
static {
|
||||
// 配置RestTemplate
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10)); // 连接超时10秒
|
||||
factory.setReadTimeout((int) TimeUnit.SECONDS.toMillis(30)); // 读取超时30秒
|
||||
restTemplate = new RestTemplate(factory);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送GET请求
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String get(String url) {
|
||||
return get(url, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送GET请求
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param headers 请求头
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String get(String url, Map<String, String> headers) {
|
||||
return get(url, headers, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送GET请求
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param headers 请求头
|
||||
* @param params 请求参数
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String get(String url, Map<String, String> headers, Map<String, Object> params) {
|
||||
HttpHeaders httpHeaders = createHeaders(headers);
|
||||
HttpEntity<?> requestEntity = new HttpEntity<>(httpHeaders);
|
||||
|
||||
// 构建完整URL(添加查询参数)
|
||||
String fullUrl = buildUrlWithParams(url, params);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
fullUrl,
|
||||
HttpMethod.GET,
|
||||
requestEntity,
|
||||
String.class);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求(JSON格式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param body 请求体
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String post(String url, Object body) {
|
||||
return post(url, body, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求(JSON格式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param body 请求体
|
||||
* @param headers 请求头
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String post(String url, Object body, Map<String, String> headers) {
|
||||
HttpHeaders httpHeaders = createHeaders(headers);
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
HttpEntity<?> requestEntity = new HttpEntity<>(body, httpHeaders);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.POST,
|
||||
requestEntity,
|
||||
String.class);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求(表单格式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param params 表单参数
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String postForm(String url, Map<String, Object> params) {
|
||||
return postForm(url, params, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求(表单格式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param params 表单参数
|
||||
* @param headers 请求头
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String postForm(String url, Map<String, Object> params, Map<String, String> headers) {
|
||||
HttpHeaders httpHeaders = createHeaders(headers);
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
HttpEntity<?> requestEntity = new HttpEntity<>(params, httpHeaders);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.POST,
|
||||
requestEntity,
|
||||
String.class);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送PUT请求(JSON格式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param body 请求体
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String put(String url, Object body) {
|
||||
return put(url, body, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送PUT请求(JSON格式)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param body 请求体
|
||||
* @param headers 请求头
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String put(String url, Object body, Map<String, String> headers) {
|
||||
HttpHeaders httpHeaders = createHeaders(headers);
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
HttpEntity<?> requestEntity = new HttpEntity<>(body, httpHeaders);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.PUT,
|
||||
requestEntity,
|
||||
String.class);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送DELETE请求
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String delete(String url) {
|
||||
return delete(url, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送DELETE请求
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param headers 请求头
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static String delete(String url, Map<String, String> headers) {
|
||||
HttpHeaders httpHeaders = createHeaders(headers);
|
||||
HttpEntity<?> requestEntity = new HttpEntity<>(httpHeaders);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.DELETE,
|
||||
requestEntity,
|
||||
String.class);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建完整URL(添加查询参数)
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param params 查询参数
|
||||
* @return 完整URL
|
||||
*/
|
||||
private static String buildUrlWithParams(String url, Map<String, Object> params) {
|
||||
if (params == null || params.isEmpty()) {
|
||||
return url;
|
||||
}
|
||||
|
||||
StringBuilder fullUrl = new StringBuilder(url);
|
||||
if (!url.contains("?")) {
|
||||
fullUrl.append("?");
|
||||
} else if (!url.endsWith("?")) {
|
||||
fullUrl.append("&");
|
||||
}
|
||||
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
if (entry.getValue() != null) {
|
||||
fullUrl.append(entry.getKey())
|
||||
.append("=")
|
||||
.append(entry.getValue())
|
||||
.append("&");
|
||||
}
|
||||
}
|
||||
|
||||
// 移除最后一个"&"
|
||||
fullUrl.deleteCharAt(fullUrl.length() - 1);
|
||||
return fullUrl.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建请求头
|
||||
*
|
||||
* @param headers 请求头Map
|
||||
* @return HttpHeaders对象
|
||||
*/
|
||||
private static HttpHeaders createHeaders(Map<String, String> headers) {
|
||||
HttpHeaders httpHeaders = new HttpHeaders();
|
||||
if (headers != null && !headers.isEmpty()) {
|
||||
for (Map.Entry<String, String> entry : headers.entrySet()) {
|
||||
httpHeaders.set(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
return httpHeaders;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取RestTemplate实例
|
||||
*
|
||||
* @return RestTemplate实例
|
||||
*/
|
||||
public static RestTemplate getRestTemplate() {
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送GET请求,返回指定类型的对象
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param headers 请求头
|
||||
* @param params 请求参数
|
||||
* @param clazz 返回类型
|
||||
* @param <T> 泛型
|
||||
* @return 响应结果对象
|
||||
*/
|
||||
public static <T> T getForObject(String url, Map<String, String> headers, Map<String, Object> params,
|
||||
Class<T> clazz) {
|
||||
HttpHeaders httpHeaders = createHeaders(headers);
|
||||
HttpEntity<?> requestEntity = new HttpEntity<>(httpHeaders);
|
||||
|
||||
String fullUrl = buildUrlWithParams(url, params);
|
||||
|
||||
ResponseEntity<T> response = restTemplate.exchange(
|
||||
fullUrl,
|
||||
HttpMethod.GET,
|
||||
requestEntity,
|
||||
clazz);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送POST请求,返回指定类型的对象
|
||||
*
|
||||
* @param url 请求URL
|
||||
* @param body 请求体
|
||||
* @param headers 请求头
|
||||
* @param clazz 返回类型
|
||||
* @param <T> 泛型
|
||||
* @return 响应结果对象
|
||||
*/
|
||||
public static <T> T postForObject(String url, Object body, Map<String, String> headers, Class<T> clazz) {
|
||||
HttpHeaders httpHeaders = createHeaders(headers);
|
||||
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
HttpEntity<?> requestEntity = new HttpEntity<>(body, httpHeaders);
|
||||
|
||||
ResponseEntity<T> response = restTemplate.exchange(
|
||||
url,
|
||||
HttpMethod.POST,
|
||||
requestEntity,
|
||||
clazz);
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
}
|
||||
185
src/main/java/icu/sunway/ai_spring_example/Utils/IpUtils.java
Normal file
185
src/main/java/icu/sunway/ai_spring_example/Utils/IpUtils.java
Normal file
@@ -0,0 +1,185 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Enumeration;
|
||||
|
||||
/**
|
||||
* IP工具类
|
||||
*/
|
||||
public class IpUtils {
|
||||
|
||||
/**
|
||||
* 本地IP地址
|
||||
*/
|
||||
private static final String LOCAL_IP = "127.0.0.1";
|
||||
|
||||
/**
|
||||
* 未知IP地址
|
||||
*/
|
||||
private static final String UNKNOWN_IP = "unknown";
|
||||
|
||||
/**
|
||||
* 获取客户端IP地址
|
||||
*
|
||||
* @param request HTTP请求
|
||||
* @return IP地址
|
||||
*/
|
||||
public static String getClientIp(HttpServletRequest request) {
|
||||
if (request == null) {
|
||||
return UNKNOWN_IP;
|
||||
}
|
||||
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ip == null || ip.isEmpty() || UNKNOWN_IP.equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
|
||||
// 如果是IPv4,直接返回
|
||||
if (ip != null && ip.contains("0:0:0:0:0:0:0:1")) {
|
||||
ip = LOCAL_IP;
|
||||
}
|
||||
|
||||
// 如果通过了多级反向代理,X-Forwarded-For的值可能有多个,取第一个非unknown的IP
|
||||
if (ip != null && ip.contains(",")) {
|
||||
String[] ips = ip.split(",");
|
||||
for (String s : ips) {
|
||||
if (!UNKNOWN_IP.equalsIgnoreCase(s.trim())) {
|
||||
ip = s.trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ip;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本地IP地址
|
||||
*
|
||||
* @return 本地IP地址
|
||||
*/
|
||||
public static String getLocalIp() {
|
||||
try {
|
||||
// 优先获取非本地回环地址
|
||||
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
|
||||
while (networkInterfaces.hasMoreElements()) {
|
||||
NetworkInterface networkInterface = networkInterfaces.nextElement();
|
||||
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
|
||||
while (inetAddresses.hasMoreElements()) {
|
||||
InetAddress inetAddress = inetAddresses.nextElement();
|
||||
if (!inetAddress.isLoopbackAddress() && inetAddress.isSiteLocalAddress()) {
|
||||
return inetAddress.getHostAddress();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 如果没有找到,返回本地回环地址
|
||||
return InetAddress.getLocalHost().getHostAddress();
|
||||
} catch (SocketException | UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
return LOCAL_IP;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将IPv4地址转换为long类型
|
||||
*
|
||||
* @param ip IPv4地址
|
||||
* @return long类型IP
|
||||
*/
|
||||
public static long ipToLong(String ip) {
|
||||
if (ip == null || ip.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
String[] ipSegments = ip.split("\\.");
|
||||
if (ipSegments.length != 4) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
long result = 0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
result = (result << 8) | Integer.parseInt(ipSegments[i]);
|
||||
}
|
||||
return result;
|
||||
} catch (NumberFormatException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将long类型IP转换为IPv4地址
|
||||
*
|
||||
* @param ip long类型IP
|
||||
* @return IPv4地址
|
||||
*/
|
||||
public static String longToIp(long ip) {
|
||||
return ((ip >> 24) & 0xFF) + "." +
|
||||
((ip >> 16) & 0xFF) + "." +
|
||||
((ip >> 8) & 0xFF) + "." +
|
||||
(ip & 0xFF);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断IP是否为内网IP
|
||||
*
|
||||
* @param ip IP地址
|
||||
* @return 是否为内网IP
|
||||
*/
|
||||
public static boolean isInnerIp(String ip) {
|
||||
if (ip == null || ip.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 本地回环地址
|
||||
if (LOCAL_IP.equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
long ipLong = ipToLong(ip);
|
||||
if (ipLong == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// A类内网:10.0.0.0-10.255.255.255
|
||||
long aBegin = ipToLong("10.0.0.0");
|
||||
long aEnd = ipToLong("10.255.255.255");
|
||||
// B类内网:172.16.0.0-172.31.255.255
|
||||
long bBegin = ipToLong("172.16.0.0");
|
||||
long bEnd = ipToLong("172.31.255.255");
|
||||
// C类内网:192.168.0.0-192.168.255.255
|
||||
long cBegin = ipToLong("192.168.0.0");
|
||||
long cEnd = ipToLong("192.168.255.255");
|
||||
|
||||
return (ipLong >= aBegin && ipLong <= aEnd) ||
|
||||
(ipLong >= bBegin && ipLong <= bEnd) ||
|
||||
(ipLong >= cBegin && ipLong <= cEnd);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断IP是否为公网IP
|
||||
*
|
||||
* @param ip IP地址
|
||||
* @return 是否为公网IP
|
||||
*/
|
||||
public static boolean isPublicIp(String ip) {
|
||||
return !isInnerIp(ip) && ValidationUtils.isIpv4(ip);
|
||||
}
|
||||
}
|
||||
178
src/main/java/icu/sunway/ai_spring_example/Utils/JsonUtils.java
Normal file
178
src/main/java/icu/sunway/ai_spring_example/Utils/JsonUtils.java
Normal file
@@ -0,0 +1,178 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JavaType;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* JSON工具类,基于Jackson实现
|
||||
*/
|
||||
public class JsonUtils {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
static {
|
||||
// 注册Java 8时间模块
|
||||
JavaTimeModule javaTimeModule = new JavaTimeModule();
|
||||
// 自定义日期时间序列化格式
|
||||
javaTimeModule.addSerializer(LocalDateTime.class,
|
||||
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DateUtils.FORMAT_DATETIME)));
|
||||
objectMapper.registerModule(javaTimeModule);
|
||||
|
||||
// 配置序列化特性
|
||||
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false); // 默认不格式化输出
|
||||
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); // 日期不使用时间戳格式
|
||||
|
||||
// 配置反序列化特性
|
||||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略未知属性
|
||||
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); // 允许单个值作为数组
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象转换为JSON字符串
|
||||
*
|
||||
* @param obj 对象
|
||||
* @return JSON字符串
|
||||
*/
|
||||
public static String toJson(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(obj);
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象转换为格式化的JSON字符串
|
||||
*
|
||||
* @param obj 对象
|
||||
* @return 格式化的JSON字符串
|
||||
*/
|
||||
public static String toJsonPretty(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
ObjectMapper prettyMapper = new ObjectMapper();
|
||||
prettyMapper.registerModule(new JavaTimeModule());
|
||||
prettyMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
|
||||
prettyMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
|
||||
return prettyMapper.writeValueAsString(obj);
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串转换为对象
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param clazz 对象类型
|
||||
* @param <T> 泛型
|
||||
* @return 对象
|
||||
*/
|
||||
public static <T> T toObject(String json, Class<T> clazz) {
|
||||
if (json == null || json.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, clazz);
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串转换为指定类型的对象(支持泛型)
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param collectionClazz 集合类型
|
||||
* @param elementClazz 元素类型
|
||||
* @param <T> 泛型
|
||||
* @return 指定类型的对象
|
||||
*/
|
||||
public static <T> T toObject(String json, Class<?> collectionClazz, Class<?>... elementClazz) {
|
||||
if (json == null || json.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClazz, elementClazz);
|
||||
return objectMapper.readValue(json, javaType);
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串转换为List
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param clazz 元素类型
|
||||
* @param <T> 泛型
|
||||
* @return List
|
||||
*/
|
||||
public static <T> List<T> toList(String json, Class<T> clazz) {
|
||||
return toObject(json, List.class, clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON字符串转换为Map
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @param keyClazz 键类型
|
||||
* @param valueClazz 值类型
|
||||
* @param <K> 键泛型
|
||||
* @param <V> 值泛型
|
||||
* @return Map
|
||||
*/
|
||||
public static <K, V> Map<K, V> toMap(String json, Class<K> keyClazz, Class<V> valueClazz) {
|
||||
return toObject(json, Map.class, keyClazz, valueClazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象转换为Map
|
||||
*
|
||||
* @param obj 对象
|
||||
* @return Map
|
||||
*/
|
||||
public static Map<String, Object> toMap(Object obj) {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.convertValue(obj, Map.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证JSON字符串是否有效
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isValidJson(String json) {
|
||||
if (json == null || json.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
objectMapper.readTree(json);
|
||||
return true;
|
||||
} catch (JsonProcessingException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
453
src/main/java/icu/sunway/ai_spring_example/Utils/RedisUtils.java
Normal file
453
src/main/java/icu/sunway/ai_spring_example/Utils/RedisUtils.java
Normal file
@@ -0,0 +1,453 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.annotation.Resource;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
public class RedisUtils {
|
||||
|
||||
@Resource
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
// ========================== String 类型 ==========================
|
||||
|
||||
/**
|
||||
* 设置缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
*/
|
||||
public void set(String key, Object value) {
|
||||
redisTemplate.opsForValue().set(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置缓存并设置过期时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param timeout 过期时间
|
||||
* @param timeUnit 时间单位
|
||||
*/
|
||||
public void set(String key, Object value, long timeout, TimeUnit timeUnit) {
|
||||
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public Object get(String key) {
|
||||
return redisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缓存
|
||||
*
|
||||
* @param key 键
|
||||
* @return 是否成功
|
||||
*/
|
||||
public Boolean delete(String key) {
|
||||
return redisTemplate.delete(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除缓存
|
||||
*
|
||||
* @param keys 键集合
|
||||
* @return 删除的数量
|
||||
*/
|
||||
public Long delete(Collection<String> keys) {
|
||||
return redisTemplate.delete(keys);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断键是否存在
|
||||
*
|
||||
* @param key 键
|
||||
* @return 是否存在
|
||||
*/
|
||||
public Boolean hasKey(String key) {
|
||||
return redisTemplate.hasKey(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置过期时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param timeout 过期时间
|
||||
* @param timeUnit 时间单位
|
||||
* @return 是否成功
|
||||
*/
|
||||
public Boolean expire(String key, long timeout, TimeUnit timeUnit) {
|
||||
return redisTemplate.expire(key, timeout, timeUnit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取过期时间
|
||||
*
|
||||
* @param key 键
|
||||
* @return 过期时间(秒)
|
||||
*/
|
||||
public Long getExpire(String key) {
|
||||
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自增
|
||||
*
|
||||
* @param key 键
|
||||
* @return 自增后的值
|
||||
*/
|
||||
public Long increment(String key) {
|
||||
return redisTemplate.opsForValue().increment(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自增指定步长
|
||||
*
|
||||
* @param key 键
|
||||
* @param delta 步长
|
||||
* @return 自增后的值
|
||||
*/
|
||||
public Long increment(String key, long delta) {
|
||||
return redisTemplate.opsForValue().increment(key, delta);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自减
|
||||
*
|
||||
* @param key 键
|
||||
* @return 自减后的值
|
||||
*/
|
||||
public Long decrement(String key) {
|
||||
return redisTemplate.opsForValue().decrement(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自减指定步长
|
||||
*
|
||||
* @param key 键
|
||||
* @param delta 步长
|
||||
* @return 自减后的值
|
||||
*/
|
||||
public Long decrement(String key, long delta) {
|
||||
return redisTemplate.opsForValue().decrement(key, delta);
|
||||
}
|
||||
|
||||
// ========================== Hash 类型 ==========================
|
||||
|
||||
/**
|
||||
* 设置哈希值
|
||||
*
|
||||
* @param key 键
|
||||
* @param field 字段
|
||||
* @param value 值
|
||||
*/
|
||||
public void hSet(String key, String field, Object value) {
|
||||
redisTemplate.opsForHash().put(key, field, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置哈希值并设置过期时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param field 字段
|
||||
* @param value 值
|
||||
* @param timeout 过期时间
|
||||
* @param timeUnit 时间单位
|
||||
*/
|
||||
public void hSet(String key, String field, Object value, long timeout, TimeUnit timeUnit) {
|
||||
redisTemplate.opsForHash().put(key, field, value);
|
||||
redisTemplate.expire(key, timeout, timeUnit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取哈希值
|
||||
*
|
||||
* @param key 键
|
||||
* @param field 字段
|
||||
* @return 值
|
||||
*/
|
||||
public Object hGet(String key, String field) {
|
||||
return redisTemplate.opsForHash().get(key, field);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有哈希值
|
||||
*
|
||||
* @param key 键
|
||||
* @return 哈希值映射
|
||||
*/
|
||||
public Map<Object, Object> hGetAll(String key) {
|
||||
return redisTemplate.opsForHash().entries(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量设置哈希值
|
||||
*
|
||||
* @param key 键
|
||||
* @param map 哈希值映射
|
||||
*/
|
||||
public void hPutAll(String key, Map<String, Object> map) {
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量设置哈希值并设置过期时间
|
||||
*
|
||||
* @param key 键
|
||||
* @param map 哈希值映射
|
||||
* @param timeout 过期时间
|
||||
* @param timeUnit 时间单位
|
||||
*/
|
||||
public void hPutAll(String key, Map<String, Object> map, long timeout, TimeUnit timeUnit) {
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
redisTemplate.expire(key, timeout, timeUnit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除哈希字段
|
||||
*
|
||||
* @param key 键
|
||||
* @param fields 字段数组
|
||||
* @return 删除的数量
|
||||
*/
|
||||
public Long hDelete(String key, Object... fields) {
|
||||
return redisTemplate.opsForHash().delete(key, fields);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断哈希字段是否存在
|
||||
*
|
||||
* @param key 键
|
||||
* @param field 字段
|
||||
* @return 是否存在
|
||||
*/
|
||||
public Boolean hHasKey(String key, String field) {
|
||||
return redisTemplate.opsForHash().hasKey(key, field);
|
||||
}
|
||||
|
||||
// ========================== List 类型 ==========================
|
||||
|
||||
/**
|
||||
* 左侧添加元素
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return 列表长度
|
||||
*/
|
||||
public Long lLeftPush(String key, Object value) {
|
||||
return redisTemplate.opsForList().leftPush(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 左侧批量添加元素
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值集合
|
||||
* @return 列表长度
|
||||
*/
|
||||
public Long lLeftPushAll(String key, Collection<Object> values) {
|
||||
return redisTemplate.opsForList().leftPushAll(key, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* 右侧添加元素
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return 列表长度
|
||||
*/
|
||||
public Long lRightPush(String key, Object value) {
|
||||
return redisTemplate.opsForList().rightPush(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 右侧批量添加元素
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值集合
|
||||
* @return 列表长度
|
||||
*/
|
||||
public Long lRightPushAll(String key, Collection<Object> values) {
|
||||
return redisTemplate.opsForList().rightPushAll(key, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* 左侧弹出元素
|
||||
*
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public Object lLeftPop(String key) {
|
||||
return redisTemplate.opsForList().leftPop(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 右侧弹出元素
|
||||
*
|
||||
* @param key 键
|
||||
* @return 值
|
||||
*/
|
||||
public Object lRightPop(String key) {
|
||||
return redisTemplate.opsForList().rightPop(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取列表长度
|
||||
*
|
||||
* @param key 键
|
||||
* @return 列表长度
|
||||
*/
|
||||
public Long lSize(String key) {
|
||||
return redisTemplate.opsForList().size(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取列表元素
|
||||
*
|
||||
* @param key 键
|
||||
* @param start 开始索引
|
||||
* @param end 结束索引
|
||||
* @return 元素列表
|
||||
*/
|
||||
public List<Object> lRange(String key, long start, long end) {
|
||||
return redisTemplate.opsForList().range(key, start, end);
|
||||
}
|
||||
|
||||
// ========================== Set 类型 ==========================
|
||||
|
||||
/**
|
||||
* 添加元素到集合
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值集合
|
||||
* @return 添加的数量
|
||||
*/
|
||||
public Long sAdd(String key, Object... values) {
|
||||
return redisTemplate.opsForSet().add(key, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从集合中移除元素
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值集合
|
||||
* @return 移除的数量
|
||||
*/
|
||||
public Long sRemove(String key, Object... values) {
|
||||
return redisTemplate.opsForSet().remove(key, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取集合所有元素
|
||||
*
|
||||
* @param key 键
|
||||
* @return 元素集合
|
||||
*/
|
||||
public Set<Object> sMembers(String key) {
|
||||
return redisTemplate.opsForSet().members(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断元素是否在集合中
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return 是否存在
|
||||
*/
|
||||
public Boolean sIsMember(String key, Object value) {
|
||||
return redisTemplate.opsForSet().isMember(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取集合大小
|
||||
*
|
||||
* @param key 键
|
||||
* @return 集合大小
|
||||
*/
|
||||
public Long sSize(String key) {
|
||||
return redisTemplate.opsForSet().size(key);
|
||||
}
|
||||
|
||||
// ========================== ZSet 类型 ==========================
|
||||
|
||||
/**
|
||||
* 添加元素到有序集合
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @param score 分数
|
||||
* @return 是否成功
|
||||
*/
|
||||
public Boolean zAdd(String key, Object value, double score) {
|
||||
return redisTemplate.opsForZSet().add(key, value, score);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从有序集合中移除元素
|
||||
*
|
||||
* @param key 键
|
||||
* @param values 值集合
|
||||
* @return 移除的数量
|
||||
*/
|
||||
public Long zRemove(String key, Object... values) {
|
||||
return redisTemplate.opsForZSet().remove(key, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取有序集合元素(按分数升序)
|
||||
*
|
||||
* @param key 键
|
||||
* @param start 开始索引
|
||||
* @param end 结束索引
|
||||
* @return 元素集合
|
||||
*/
|
||||
public Set<Object> zRange(String key, long start, long end) {
|
||||
return redisTemplate.opsForZSet().range(key, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取有序集合元素(按分数降序)
|
||||
*
|
||||
* @param key 键
|
||||
* @param start 开始索引
|
||||
* @param end 结束索引
|
||||
* @return 元素集合
|
||||
*/
|
||||
public Set<Object> zReverseRange(String key, long start, long end) {
|
||||
return redisTemplate.opsForZSet().reverseRange(key, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取元素分数
|
||||
*
|
||||
* @param key 键
|
||||
* @param value 值
|
||||
* @return 分数
|
||||
*/
|
||||
public Double zScore(String key, Object value) {
|
||||
return redisTemplate.opsForZSet().score(key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取有序集合大小
|
||||
*
|
||||
* @param key 键
|
||||
* @return 集合大小
|
||||
*/
|
||||
public Long zSize(String key) {
|
||||
return redisTemplate.opsForZSet().size(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 响应结果工具类
|
||||
*/
|
||||
public class ResponseUtils {
|
||||
|
||||
/**
|
||||
* 响应状态码常量
|
||||
*/
|
||||
public static final int SUCCESS = 200; // 成功
|
||||
public static final int FAIL = 500; // 失败
|
||||
public static final int BAD_REQUEST = 400; // 请求参数错误
|
||||
public static final int UNAUTHORIZED = 401; // 未授权
|
||||
public static final int FORBIDDEN = 403; // 禁止访问
|
||||
public static final int NOT_FOUND = 404; // 资源不存在
|
||||
public static final int METHOD_NOT_ALLOWED = 405; // 方法不允许
|
||||
public static final int INTERNAL_SERVER_ERROR = 500;// 服务器内部错误
|
||||
|
||||
/**
|
||||
* 统一响应结果对象
|
||||
*/
|
||||
@Data
|
||||
public static class Response<T> {
|
||||
private int code; // 状态码
|
||||
private String message; // 消息
|
||||
private T data; // 数据
|
||||
private long timestamp; // 时间戳
|
||||
|
||||
public Response() {
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public Response(int code, String message) {
|
||||
this();
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public Response(int code, String message, T data) {
|
||||
this(code, message);
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功响应
|
||||
*
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> success() {
|
||||
return new Response<>(SUCCESS, "操作成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功响应
|
||||
*
|
||||
* @param data 数据
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> success(T data) {
|
||||
return new Response<>(SUCCESS, "操作成功", data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功响应
|
||||
*
|
||||
* @param message 消息
|
||||
* @param data 数据
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> success(String message, T data) {
|
||||
return new Response<>(SUCCESS, message, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败响应
|
||||
*
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> fail() {
|
||||
return new Response<>(FAIL, "操作失败");
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败响应
|
||||
*
|
||||
* @param message 消息
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> fail(String message) {
|
||||
return new Response<>(FAIL, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败响应
|
||||
*
|
||||
* @param code 状态码
|
||||
* @param message 消息
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> fail(int code, String message) {
|
||||
return new Response<>(code, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 参数错误响应
|
||||
*
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> badRequest() {
|
||||
return new Response<>(BAD_REQUEST, "参数错误");
|
||||
}
|
||||
|
||||
/**
|
||||
* 参数错误响应
|
||||
*
|
||||
* @param message 消息
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> badRequest(String message) {
|
||||
return new Response<>(BAD_REQUEST, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未授权响应
|
||||
*
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> unauthorized() {
|
||||
return new Response<>(UNAUTHORIZED, "未授权");
|
||||
}
|
||||
|
||||
/**
|
||||
* 未授权响应
|
||||
*
|
||||
* @param message 消息
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> unauthorized(String message) {
|
||||
return new Response<>(UNAUTHORIZED, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁止访问响应
|
||||
*
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> forbidden() {
|
||||
return new Response<>(FORBIDDEN, "禁止访问");
|
||||
}
|
||||
|
||||
/**
|
||||
* 资源不存在响应
|
||||
*
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> notFound() {
|
||||
return new Response<>(NOT_FOUND, "资源不存在");
|
||||
}
|
||||
|
||||
/**
|
||||
* 资源不存在响应
|
||||
*
|
||||
* @param message 消息
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> notFound(String message) {
|
||||
return new Response<>(NOT_FOUND, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务器内部错误响应
|
||||
*
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> internalServerError() {
|
||||
return new Response<>(INTERNAL_SERVER_ERROR, "服务器内部错误");
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务器内部错误响应
|
||||
*
|
||||
* @param message 消息
|
||||
* @return 响应结果
|
||||
*/
|
||||
public static <T> Response<T> internalServerError(String message) {
|
||||
return new Response<>(INTERNAL_SERVER_ERROR, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package icu.sunway.ai_spring_example.Utils;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 验证工具类
|
||||
*/
|
||||
public class ValidationUtils {
|
||||
|
||||
/**
|
||||
* 正则表达式:邮箱
|
||||
*/
|
||||
private static final String REGEX_EMAIL = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
|
||||
|
||||
/**
|
||||
* 正则表达式:手机号(中国大陆)
|
||||
*/
|
||||
private static final String REGEX_PHONE = "^1[3-9]\\d{9}$";
|
||||
|
||||
/**
|
||||
* 正则表达式:身份证号(18位)
|
||||
*/
|
||||
private static final String REGEX_ID_CARD = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[\\dXx]$";
|
||||
|
||||
/**
|
||||
* 正则表达式:URL
|
||||
*/
|
||||
private static final String REGEX_URL = "^(https?|ftp):\\/\\/[^\\s/$.?#].[^\\s]*$";
|
||||
|
||||
/**
|
||||
* 正则表达式:IPv4
|
||||
*/
|
||||
private static final String REGEX_IPV4 = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
|
||||
|
||||
/**
|
||||
* 正则表达式:密码(至少8位,包含字母和数字)
|
||||
*/
|
||||
private static final String REGEX_PASSWORD = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$";
|
||||
|
||||
/**
|
||||
* 正则表达式:强密码(至少8位,包含大写字母、小写字母和数字)
|
||||
*/
|
||||
private static final String REGEX_STRONG_PASSWORD = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$";
|
||||
|
||||
/**
|
||||
* 正则表达式:用户名(4-20位字母、数字、下划线)
|
||||
*/
|
||||
private static final String REGEX_USERNAME = "^[a-zA-Z0-9_]{4,20}$";
|
||||
|
||||
/**
|
||||
* 正则表达式:中文字符
|
||||
*/
|
||||
private static final String REGEX_CHINESE = "^[\\u4e00-\\u9fa5]+$";
|
||||
|
||||
/**
|
||||
* 验证邮箱
|
||||
*
|
||||
* @param email 邮箱
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isEmail(String email) {
|
||||
if (email == null || email.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(REGEX_EMAIL, email);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证手机号(中国大陆)
|
||||
*
|
||||
* @param phone 手机号
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isPhone(String phone) {
|
||||
if (phone == null || phone.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(REGEX_PHONE, phone);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证身份证号(18位)
|
||||
*
|
||||
* @param idCard 身份证号
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isIdCard(String idCard) {
|
||||
if (idCard == null || idCard.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
// 基本格式验证
|
||||
if (!Pattern.matches(REGEX_ID_CARD, idCard)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 校验码验证
|
||||
int[] weights = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
|
||||
char[] checkCodes = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
|
||||
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 17; i++) {
|
||||
sum += (idCard.charAt(i) - '0') * weights[i];
|
||||
}
|
||||
|
||||
char checkCode = checkCodes[sum % 11];
|
||||
return Character.toUpperCase(idCard.charAt(17)) == checkCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证URL
|
||||
*
|
||||
* @param url URL
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isUrl(String url) {
|
||||
if (url == null || url.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(REGEX_URL, url);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证IPv4
|
||||
*
|
||||
* @param ip IPv4地址
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isIpv4(String ip) {
|
||||
if (ip == null || ip.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(REGEX_IPV4, ip);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证密码(至少8位,包含字母和数字)
|
||||
*
|
||||
* @param password 密码
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isPassword(String password) {
|
||||
if (password == null || password.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(REGEX_PASSWORD, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证强密码(至少8位,包含大写字母、小写字母和数字)
|
||||
*
|
||||
* @param password 密码
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isStrongPassword(String password) {
|
||||
if (password == null || password.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(REGEX_STRONG_PASSWORD, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证用户名(4-20位字母、数字、下划线)
|
||||
*
|
||||
* @param username 用户名
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isUsername(String username) {
|
||||
if (username == null || username.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(REGEX_USERNAME, username);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证中文字符
|
||||
*
|
||||
* @param str 字符串
|
||||
* @return 是否有效
|
||||
*/
|
||||
public static boolean isChinese(String str) {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return Pattern.matches(REGEX_CHINESE, str);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证字符串是否为空
|
||||
*
|
||||
* @param str 字符串
|
||||
* @return 是否为空
|
||||
*/
|
||||
public static boolean isEmpty(String str) {
|
||||
return str == null || str.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证字符串是否不为空
|
||||
*
|
||||
* @param str 字符串
|
||||
* @return 是否不为空
|
||||
*/
|
||||
public static boolean isNotEmpty(String str) {
|
||||
return !isEmpty(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证字符串长度是否在指定范围内
|
||||
*
|
||||
* @param str 字符串
|
||||
* @param min 最小长度
|
||||
* @param max 最大长度
|
||||
* @return 是否在指定范围内
|
||||
*/
|
||||
public static boolean isLengthBetween(String str, int min, int max) {
|
||||
if (str == null) {
|
||||
return false;
|
||||
}
|
||||
int length = str.length();
|
||||
return length >= min && length <= max;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证数字是否在指定范围内
|
||||
*
|
||||
* @param num 数字
|
||||
* @param min 最小值
|
||||
* @param max 最大值
|
||||
* @return 是否在指定范围内
|
||||
*/
|
||||
public static boolean isNumberBetween(int num, int min, int max) {
|
||||
return num >= min && num <= max;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证数字是否在指定范围内
|
||||
*
|
||||
* @param num 数字
|
||||
* @param min 最小值
|
||||
* @param max 最大值
|
||||
* @return 是否在指定范围内
|
||||
*/
|
||||
public static boolean isNumberBetween(long num, long min, long max) {
|
||||
return num >= min && num <= max;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证数字是否为正数
|
||||
*
|
||||
* @param num 数字
|
||||
* @return 是否为正数
|
||||
*/
|
||||
public static boolean isPositiveNumber(Number num) {
|
||||
if (num == null) {
|
||||
return false;
|
||||
}
|
||||
return num.doubleValue() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证数字是否为非负数
|
||||
*
|
||||
* @param num 数字
|
||||
* @return 是否为非负数
|
||||
*/
|
||||
public static boolean isNonNegativeNumber(Number num) {
|
||||
if (num == null) {
|
||||
return false;
|
||||
}
|
||||
return num.doubleValue() >= 0;
|
||||
}
|
||||
}
|
||||
24
src/main/resources/application-example.yaml
Normal file
24
src/main/resources/application-example.yaml
Normal file
@@ -0,0 +1,24 @@
|
||||
spring:
|
||||
application:
|
||||
name: ai-spring-example
|
||||
# 动态多数据源配置
|
||||
datasource:
|
||||
dynamic:
|
||||
primary: master
|
||||
strict: false
|
||||
datasource:
|
||||
master:
|
||||
url: # 请替换为您的数据库URL
|
||||
username: # 请替换为您的数据库用户名
|
||||
password: # 请替换为您的数据库密码
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
# Redis配置
|
||||
data:
|
||||
redis:
|
||||
host: # 请替换为您的Redis主机
|
||||
port: 6379
|
||||
password: # 请替换为您的Redis密码
|
||||
database: 0
|
||||
|
||||
server:
|
||||
port: 8080
|
||||
Reference in New Issue
Block a user