commit 1225e87dc983f4a865541aec0d2b57aab1903317 Author: Silence_Lurker Date: Sat Jan 17 08:59:21 2026 +0800 init diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..c0bcafe --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -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 diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/mvnw @@ -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-,maven-mvnd--}/ +[ -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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/mvnw.cmd @@ -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-,maven-mvnd--}/ +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" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..e06d014 --- /dev/null +++ b/pom.xml @@ -0,0 +1,184 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.9 + + + cc.amily49.api + module-template + 1.0.0-SNAPSHOT + module-template + Demo project for Spring Boot + + + + + + + + + + + + + + + 17 + 2.8.5 + 0.13.0 + + + + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-websocket + + + + + com.mysql + mysql-connector-j + 8.4.0 + runtime + + + + org.postgresql + postgresql + runtime + + + + org.flywaydb + flyway-mysql + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${springdoc.version} + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + io.jsonwebtoken + jjwt-api + ${jjwt.version} + + + io.jsonwebtoken + jjwt-impl + ${jjwt.version} + runtime + + + io.jsonwebtoken + jjwt-jackson + ${jjwt.version} + runtime + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework.boot + spring-boot-starter-quartz + + + + org.springframework.boot + spring-boot-starter-aop + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.flywaydb + flyway-maven-plugin + + + + + + + diff --git a/src/main/java/cc/amily49/api/module/ModuleApplication.java b/src/main/java/cc/amily49/api/module/ModuleApplication.java new file mode 100644 index 0000000..f577823 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/ModuleApplication.java @@ -0,0 +1,23 @@ +package cc.amily49.api.module; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; +import org.springframework.data.web.config.EnableSpringDataWebSupport; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication(scanBasePackages = "cc.amily49.api.module") +@EnableAsync +@EnableScheduling +@EnableSpringDataWebSupport(pageSerializationMode = EnableSpringDataWebSupport.PageSerializationMode.VIA_DTO) +@EnableRedisRepositories(basePackages = { + // Add your redis repositories here +}) +public class ModuleApplication { + + public static void main(String[] args) { + SpringApplication.run(ModuleApplication.class, args); + } + +} \ No newline at end of file diff --git a/src/main/java/cc/amily49/api/module/auth/filter/JwtAuthenticationFilter.java b/src/main/java/cc/amily49/api/module/auth/filter/JwtAuthenticationFilter.java new file mode 100644 index 0000000..50dc64c --- /dev/null +++ b/src/main/java/cc/amily49/api/module/auth/filter/JwtAuthenticationFilter.java @@ -0,0 +1,82 @@ +package cc.amily49.api.module.auth.filter; + +import io.jsonwebtoken.ExpiredJwtException; +import jakarta.annotation.Resource; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +import cc.amily49.api.module.auth.model.JwtUser; +import cc.amily49.api.module.auth.util.JwtUtil; + +import java.io.IOException; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Stateless JWT Filter for Module Template + * + * @author Silence_Lurker by Gemini + */ +@Component +public class JwtAuthenticationFilter extends OncePerRequestFilter { + + @Resource + private JwtUtil jwtUtil; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + + final String requestTokenHeader = request.getHeader("Authorization"); + + String username = null; + String jwtToken = null; + + if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) { + jwtToken = requestTokenHeader.substring(7); + try { + username = jwtUtil.getUsernameFromToken(jwtToken); + } catch (IllegalArgumentException e) { + logger.warn("Unable to get JWT Token"); + } catch (ExpiredJwtException e) { + logger.warn("JWT Token has expired"); + } + } + + if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { + + // Validate token signature and expiration ONLY (Stateless) + if (jwtUtil.validateToken(jwtToken)) { + + // Extract roles from token + List roles = jwtUtil.getRolesFromToken(jwtToken); + Set authorities = null; + + if (roles != null) { + authorities = roles.stream() + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toSet()); + } + + // Create stateless user details + JwtUser userDetails = new JwtUser(username, authorities); + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities()); + + auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(auth); + } + } + chain.doFilter(request, response); + } +} diff --git a/src/main/java/cc/amily49/api/module/auth/model/JwtUser.java b/src/main/java/cc/amily49/api/module/auth/model/JwtUser.java new file mode 100644 index 0000000..67fbf2a --- /dev/null +++ b/src/main/java/cc/amily49/api/module/auth/model/JwtUser.java @@ -0,0 +1,53 @@ +package cc.amily49.api.module.auth.model; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Collection; +import java.util.Set; + +public class JwtUser implements UserDetails { + + private final String username; + private final Set authorities; + + public JwtUser(String username, Set authorities) { + this.username = username; + this.authorities = authorities; + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public String getPassword() { + return null; // No password in token-based auth + } + + @Override + public String getUsername() { + return username; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } +} diff --git a/src/main/java/cc/amily49/api/module/auth/util/JwtUtil.java b/src/main/java/cc/amily49/api/module/auth/util/JwtUtil.java new file mode 100644 index 0000000..2d33627 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/auth/util/JwtUtil.java @@ -0,0 +1,85 @@ +package cc.amily49.api.module.auth.util; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import jakarta.annotation.PostConstruct; +import javax.crypto.SecretKey; +import java.io.Serializable; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.List; +import java.util.function.Function; + +/** + * Utility class for handling JWT tokens. + * Generation, validation, etc. + * + * @author Silence_Lurker by Gemini + */ +@Component +public class JwtUtil implements Serializable { + + private static final long serialVersionUID = -2550185165626007488L; + + // Token validity in milliseconds (e.g., 10 hours) + public static final long JWT_TOKEN_VALIDITY = 10 * 60 * 60 * 1000; + + @Value("${amily.jwt.secret}") + private String secretString; + + private SecretKey secretKey; + + @PostConstruct + public void init() { + byte[] decodedKey = Base64.getDecoder().decode(secretString); + this.secretKey = Keys.hmacShaKeyFor(decodedKey); + } + + public String getUsernameFromToken(String token) { + return getClaimFromToken(token, Claims::getSubject); + } + + public Date getExpirationDateFromToken(String token) { + return getClaimFromToken(token, Claims::getExpiration); + } + + public String getIpFromToken(String token) { + return getClaimFromToken(token, claims -> claims.get("ip", String.class)); + } + + public List getRolesFromToken(String token) { + return getClaimFromToken(token, claims -> claims.get("roles", List.class)); + } + + public T getClaimFromToken(String token, Function claimsResolver) { + final Claims claims = getAllClaimsFromToken(token); + return claimsResolver.apply(claims); + } + + private Claims getAllClaimsFromToken(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload(); + } + + private Boolean isTokenExpired(String token) { + final Date expiration = getExpirationDateFromToken(token); + return expiration.before(new Date()); + } + + /** + * Validate token (Stateless) + * Checks signature (implicit in getAllClaimsFromToken) and expiration. + */ + public Boolean validateToken(String token) { + try { + return !isTokenExpired(token); + } catch (Exception e) { + return false; + } + } +} \ No newline at end of file diff --git a/src/main/java/cc/amily49/api/module/common/controller/SystemConfigController.java b/src/main/java/cc/amily49/api/module/common/controller/SystemConfigController.java new file mode 100644 index 0000000..5bff399 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/common/controller/SystemConfigController.java @@ -0,0 +1,29 @@ +package cc.amily49.api.module.common.controller; + +import cc.amily49.api.module.common.service.SystemConfigService; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import jakarta.annotation.Resource; +import java.util.Map; + +@RestController +@RequestMapping("/admin/config") +@PreAuthorize("hasRole('ADMIN')") +public class SystemConfigController { + + @Resource + private SystemConfigService systemConfigService; + + @GetMapping + public ResponseEntity getAllConfigs() { + return ResponseEntity.ok(systemConfigService.getAllConfigs()); + } + + @PostMapping + public ResponseEntity updateConfigs(@RequestBody Map configs) { + systemConfigService.updateConfigs(configs); + return ResponseEntity.ok("Configuration updated successfully."); + } +} diff --git a/src/main/java/cc/amily49/api/module/common/entity/po/SystemConfig.java b/src/main/java/cc/amily49/api/module/common/entity/po/SystemConfig.java new file mode 100644 index 0000000..0f38efb --- /dev/null +++ b/src/main/java/cc/amily49/api/module/common/entity/po/SystemConfig.java @@ -0,0 +1,19 @@ +package cc.amily49.api.module.common.entity.po; + +import jakarta.persistence.*; +import lombok.Data; + +@Data +@Entity +@Table(name = "system_config") +public class SystemConfig { + @Id + @Column(name = "config_key", nullable = false) + private String key; + + @Column(name = "config_value") + private String value; + + @Column(name = "description") + private String description; +} diff --git a/src/main/java/cc/amily49/api/module/common/exception/GlobalExceptionHandler.java b/src/main/java/cc/amily49/api/module/common/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..134a3c0 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/common/exception/GlobalExceptionHandler.java @@ -0,0 +1,30 @@ +package cc.amily49.api.module.common.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.Map; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException e) { + return ResponseEntity.badRequest().body(Map.of("success", false, "message", e.getMessage())); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity handleIllegalStateException(IllegalStateException e) { + // Return 400 for business logic errors (like limit exceeded) or 409 Conflict if more appropriate + // Here 400 is fine for client errors. + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("success", false, "message", e.getMessage())); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleException(Exception e) { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) + .body(Map.of("success", false, "message", "服务器内部错? " + e.getMessage())); + } +} diff --git a/src/main/java/cc/amily49/api/module/common/repository/jpa/SystemConfigRepository.java b/src/main/java/cc/amily49/api/module/common/repository/jpa/SystemConfigRepository.java new file mode 100644 index 0000000..5110d9e --- /dev/null +++ b/src/main/java/cc/amily49/api/module/common/repository/jpa/SystemConfigRepository.java @@ -0,0 +1,9 @@ +package cc.amily49.api.module.common.repository.jpa; + +import cc.amily49.api.module.common.entity.po.SystemConfig; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SystemConfigRepository extends JpaRepository { +} diff --git a/src/main/java/cc/amily49/api/module/common/service/SystemConfigService.java b/src/main/java/cc/amily49/api/module/common/service/SystemConfigService.java new file mode 100644 index 0000000..b1012af --- /dev/null +++ b/src/main/java/cc/amily49/api/module/common/service/SystemConfigService.java @@ -0,0 +1,11 @@ +package cc.amily49.api.module.common.service; + +import java.util.Map; + +public interface SystemConfigService { + String getConfig(String key, String defaultValue); + int getConfigInt(String key, int defaultValue); + void setConfig(String key, String value); + Map getAllConfigs(); + void updateConfigs(Map configs); +} diff --git a/src/main/java/cc/amily49/api/module/common/service/impl/SystemConfigServiceImpl.java b/src/main/java/cc/amily49/api/module/common/service/impl/SystemConfigServiceImpl.java new file mode 100644 index 0000000..3eaf5df --- /dev/null +++ b/src/main/java/cc/amily49/api/module/common/service/impl/SystemConfigServiceImpl.java @@ -0,0 +1,57 @@ +package cc.amily49.api.module.common.service.impl; + +import cc.amily49.api.module.common.entity.po.SystemConfig; +import cc.amily49.api.module.common.repository.jpa.SystemConfigRepository; +import cc.amily49.api.module.common.service.SystemConfigService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import jakarta.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@Service +public class SystemConfigServiceImpl implements SystemConfigService { + + @Resource + private SystemConfigRepository systemConfigRepository; + + @Override + public String getConfig(String key, String defaultValue) { + return systemConfigRepository.findById(key).map(SystemConfig::getValue).orElse(defaultValue); + } + + @Override + public int getConfigInt(String key, int defaultValue) { + try { + return Integer.parseInt(getConfig(key, String.valueOf(defaultValue))); + } catch (NumberFormatException e) { + return defaultValue; + } + } + + @Override + @Transactional + public void setConfig(String key, String value) { + SystemConfig config = systemConfigRepository.findById(key).orElse(new SystemConfig()); + config.setKey(key); + config.setValue(value); + systemConfigRepository.save(config); + } + + @Override + public Map getAllConfigs() { + return systemConfigRepository.findAll().stream() + .collect(Collectors.toMap(SystemConfig::getKey, SystemConfig::getValue)); + } + + @Override + @Transactional + public void updateConfigs(Map configs) { + for (Map.Entry entry : configs.entrySet()) { + setConfig(entry.getKey(), entry.getValue()); + } + } +} diff --git a/src/main/java/cc/amily49/api/module/config/OpenApiConfig.java b/src/main/java/cc/amily49/api/module/config/OpenApiConfig.java new file mode 100644 index 0000000..4619f6f --- /dev/null +++ b/src/main/java/cc/amily49/api/module/config/OpenApiConfig.java @@ -0,0 +1,31 @@ +package cc.amily49.api.module.config; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class OpenApiConfig { + + @Bean + public OpenAPI customOpenAPI() { + final String securitySchemeName = "bearerAuth"; + + return new OpenAPI() + .addSecurityItem(new SecurityRequirement().addList(securitySchemeName)) + .components( + new Components() + .addSecuritySchemes(securitySchemeName, + new SecurityScheme() + .name(securitySchemeName) + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT"))) + .info(new Info().title("Amily API").version("v1.0") + .description("API documentation for Amily project.")); + } +} diff --git a/src/main/java/cc/amily49/api/module/config/QuartzConfig.java b/src/main/java/cc/amily49/api/module/config/QuartzConfig.java new file mode 100644 index 0000000..e77021d --- /dev/null +++ b/src/main/java/cc/amily49/api/module/config/QuartzConfig.java @@ -0,0 +1,17 @@ +package cc.amily49.api.module.config; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.quartz.QuartzDataSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import javax.sql.DataSource; + +@Configuration +public class QuartzConfig { + + @Bean + @QuartzDataSource + public DataSource quartzDataSource(@Qualifier("primaryDataSource") DataSource primaryDataSource) { + return primaryDataSource; + } +} diff --git a/src/main/java/cc/amily49/api/module/config/SecurityConfig.java b/src/main/java/cc/amily49/api/module/config/SecurityConfig.java new file mode 100644 index 0000000..dab75a4 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/config/SecurityConfig.java @@ -0,0 +1,71 @@ +package cc.amily49.api.module.config; + +import java.util.Arrays; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +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; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import cc.amily49.api.module.auth.filter.JwtAuthenticationFilter; +import jakarta.annotation.Resource; + +/** + * Security Configuration for Modules (Stateless, No Login) + * + * @author Silence_Lurker by Gemini + */ +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +public class SecurityConfig { + + @Resource + private JwtAuthenticationFilter jwtAuthenticationFilter; + + @Bean + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .csrf(csrf -> csrf.disable()) + .headers(headers -> headers.frameOptions(frame -> frame.sameOrigin())) + .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(authz -> authz + // Swagger UI + .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-ui.html").permitAll() + // Public endpoints (if any) + .requestMatchers("/public/**").permitAll() + // All other endpoints require authentication + .anyRequest().authenticated()); + + return http.build(); + } + + @Bean + CorsConfigurationSource corsConfigurationSource() { + CorsConfiguration strictConfig = new CorsConfiguration(); + strictConfig.setAllowedOriginPatterns(Arrays.asList( + "http://localhost:*", + "http://127.0.0.1:*", + "http://*.amily49.cc", + "https://*.amily49.cc", + "https://amily49.cc" + )); + strictConfig.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); + strictConfig.setAllowCredentials(true); + strictConfig.setAllowedHeaders(Arrays.asList("*")); + strictConfig.setExposedHeaders(Arrays.asList("Authorization")); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", strictConfig); + return source; + } +} \ No newline at end of file diff --git a/src/main/java/cc/amily49/api/module/config/datasource/DataSourceWarmupRunner.java b/src/main/java/cc/amily49/api/module/config/datasource/DataSourceWarmupRunner.java new file mode 100644 index 0000000..c2edcb8 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/config/datasource/DataSourceWarmupRunner.java @@ -0,0 +1,39 @@ +package cc.amily49.api.module.config.datasource; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; +import org.springframework.beans.factory.annotation.Qualifier; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; + +@Component +public class DataSourceWarmupRunner implements CommandLineRunner { + + private final DataSource primaryDataSource; + + public DataSourceWarmupRunner(@Qualifier("primaryDataSource") DataSource primaryDataSource) { + this.primaryDataSource = primaryDataSource; + } + + @Override + public void run(String... args) { + System.out.println("Wait for database connection warmup..."); + long start = System.currentTimeMillis(); + try (Connection conn = primaryDataSource.getConnection(); + PreparedStatement ps = conn.prepareStatement("SELECT 1")) { + try (ResultSet rs = ps.executeQuery()) { + while(rs.next()) { + // Just consume result + } + } + long end = System.currentTimeMillis(); + System.out.println("Database connection warmup completed in " + (end - start) + "ms."); + } catch (Exception e) { + System.err.println("Database warmup failed: " + e.getMessage()); + // We don't throw exception here to allow app startup even if warmup fails, + // though it might fail later on actual requests. + } + } +} diff --git a/src/main/java/cc/amily49/api/module/config/datasource/PrimaryDataSourceConfig.java b/src/main/java/cc/amily49/api/module/config/datasource/PrimaryDataSourceConfig.java new file mode 100644 index 0000000..4e1e19c --- /dev/null +++ b/src/main/java/cc/amily49/api/module/config/datasource/PrimaryDataSourceConfig.java @@ -0,0 +1,63 @@ +package cc.amily49.api.module.config.datasource; + +import jakarta.persistence.EntityManagerFactory; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories( + basePackages = { + "cc.amily49.api.module.auth.repository.jpa", + "cc.amily49.api.module.common.repository.jpa" + }, + entityManagerFactoryRef = "entityManagerFactoryPrimary", + transactionManagerRef = "transactionManagerPrimary" +) +public class PrimaryDataSourceConfig { + + @Bean + @Primary + @ConfigurationProperties("spring.datasource.primary") + public DataSourceProperties primaryDataSourceProperties() { + return new DataSourceProperties(); + } + + @Bean(name = "primaryDataSource") + @Primary + @ConfigurationProperties("spring.datasource.primary.hikari") + public DataSource primaryDataSource() { + return primaryDataSourceProperties().initializeDataSourceBuilder().build(); + } + + @Bean(name = "entityManagerFactoryPrimary") + @Primary + public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary( + EntityManagerFactoryBuilder builder, + @Qualifier("primaryDataSource") DataSource dataSource) { + return builder + .dataSource(dataSource) + .packages("cc.amily49.api.module.auth", "cc.amily49.api.module.common") // Explicitly scan business modules + .persistenceUnit("primary") + .build(); + } + + @Bean(name = "transactionManagerPrimary") + @Primary + public PlatformTransactionManager transactionManagerPrimary( + @Qualifier("entityManagerFactoryPrimary") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } +} diff --git a/src/main/java/cc/amily49/api/module/config/datasource/SecondaryDataSourceConfig.java b/src/main/java/cc/amily49/api/module/config/datasource/SecondaryDataSourceConfig.java new file mode 100644 index 0000000..48ad853 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/config/datasource/SecondaryDataSourceConfig.java @@ -0,0 +1,63 @@ +package cc.amily49.api.module.config.datasource; + +import jakarta.persistence.EntityManagerFactory; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; + +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories( + basePackages = "cc.amily49.api.module.warehouse", + entityManagerFactoryRef = "entityManagerFactorySecondary", + transactionManagerRef = "transactionManagerSecondary" +) +public class SecondaryDataSourceConfig { + + @Bean + @ConfigurationProperties("spring.datasource.secondary") + public DataSourceProperties secondaryDataSourceProperties() { + return new DataSourceProperties(); + } + + @Bean(name = "secondaryDataSource") + @ConfigurationProperties("spring.datasource.secondary.hikari") + public DataSource secondaryDataSource() { + return secondaryDataSourceProperties().initializeDataSourceBuilder().build(); + } + + @Bean(name = "entityManagerFactorySecondary") + public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary( + EntityManagerFactoryBuilder builder, + @Qualifier("secondaryDataSource") DataSource dataSource) { + + Map properties = new HashMap<>(); + properties.put("hibernate.hbm2ddl.auto", "update"); // Auto-create tables for warehouse + properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); + + return builder + .dataSource(dataSource) + .packages("cc.amily49.api.module.warehouse") + .persistenceUnit("secondary") + .properties(properties) + .build(); + } + + @Bean(name = "transactionManagerSecondary") + public PlatformTransactionManager transactionManagerSecondary( + @Qualifier("entityManagerFactorySecondary") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } +} diff --git a/src/main/java/cc/amily49/api/module/filter/FullApiFilter.java b/src/main/java/cc/amily49/api/module/filter/FullApiFilter.java new file mode 100644 index 0000000..114835a --- /dev/null +++ b/src/main/java/cc/amily49/api/module/filter/FullApiFilter.java @@ -0,0 +1,146 @@ +package cc.amily49.api.module.filter; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.time.ZoneId; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.util.ContentCachingRequestWrapper; + +import cc.amily49.api.module.warehouse.entity.OperationLog; +import cc.amily49.api.module.warehouse.service.LogService; +import jakarta.annotation.Resource; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.annotation.WebFilter; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Component +public class FullApiFilter implements Filter { + + @Resource + private LogService logService; + + @Value("${app.time-zone:Asia/Shanghai}") + private String appTimeZone; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + // Wrap the request to cache the body content for logging + ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(req); + long startTime = System.currentTimeMillis(); + + try { + // Use the wrapped request for the filter chain + chain.doFilter(wrappedRequest, response); + } catch (Exception e) { + req.setAttribute("filter_exception", e.getMessage()); + throw e; + } finally { + try { + HttpServletResponse httpRes = (HttpServletResponse) response; + String servletPath = wrappedRequest.getServletPath(); + String uri = wrappedRequest.getRequestURI(); + + // 跳过高频接口日志 + if ("/message/newest".equals(servletPath)) { + return; + } + + long duration = System.currentTimeMillis() - startTime; + String clientIp = getClientIp(wrappedRequest); + String method = wrappedRequest.getMethod(); + String params; + + // 登录接口登录成功(状态码 2xx)时不记录参数,仅记录失败日? + if ("/access/login".equals(servletPath) && httpRes.getStatus() >= 200 && httpRes.getStatus() < 300) { + params = "[PROTECTED]"; + } else { + params = getParams(wrappedRequest); + } + + OperationLog opLog = new OperationLog(); + opLog.setIp(clientIp); + opLog.setUrl(uri); + opLog.setMethod(method); + opLog.setParams(params); + opLog.setDuration(duration); + opLog.setCreateTime(LocalDateTime.now(ZoneId.of(appTimeZone))); + opLog.setDescription("API Access Log"); + + // 获取当前登录用户 + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getPrincipal())) { + opLog.setUsername(auth.getName()); + } + + // 记录可能的异常信? + Object exception = req.getAttribute("filter_exception"); + if (exception != null) { + opLog.setException(exception.toString()); + } + + logService.saveLog(opLog); + + } catch (Exception ex) { + System.err.println("Failed to save access log: " + ex.getMessage()); + } + } + } + + private String getParams(ContentCachingRequestWrapper request) { + StringBuilder params = new StringBuilder(); + + // Query String + String queryString = request.getQueryString(); + if (queryString != null && !queryString.isEmpty()) { + params.append("Query: ").append(queryString); + } + + // Body + // Note: ContentCachingRequestWrapper only caches content after it has been read. + // If the controller didn't read the body (e.g. GET request or error before reading), this will be empty. + byte[] content = request.getContentAsByteArray(); + if (content.length > 0) { + if (params.length() > 0) { + params.append("; "); + } + try { + String body = new String(content, StandardCharsets.UTF_8); + // Simple truncation or formatting could be added here if needed + params.append("Body: ").append(body); + } catch (Exception e) { + params.append("Body: [Error reading body]"); + } + } + + return params.toString(); + } + + private String getClientIp(HttpServletRequest request) { + String ip = request.getHeader("X-Forwarded-For"); + if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Real-IP"); + } + if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + + if (ip != null && ip.contains(",")) { + ip = ip.split(",")[0].trim(); + } + + return ip; + } + +} diff --git a/src/main/java/cc/amily49/api/module/util/BaseEncoder.java b/src/main/java/cc/amily49/api/module/util/BaseEncoder.java new file mode 100644 index 0000000..f75c6b5 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/util/BaseEncoder.java @@ -0,0 +1,98 @@ +package cc.amily49.api.module.util; + +import java.util.Base64; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** + * @author Silence_Lurker + */ +public class BaseEncoder { + + public static enum Algorithm { + BASE64, + BASE64_URL, + HEX, + MD5, + SHA256, + SHA1, + REMOVE_SPECIAL_CHARS, // 你原来的功能 + URL_ENCODE + } + + private BaseEncoder() { + } + + public static String encodeByTarget(String target, Algorithm algorithm) { + if (target == null) { + return null; + } + + try { + return switch (algorithm) { + case BASE64 -> encodeBase64(target); + case BASE64_URL -> encodeBase64Url(target); + case HEX -> encodeHex(target); + case MD5 -> encodeMD5(target); + case SHA256 -> encodeSHA256(target); + case SHA1 -> encodeSHA1(target); + case REMOVE_SPECIAL_CHARS -> removeSpecialChars(target); + case URL_ENCODE -> urlEncode(target); + }; + } catch (Exception e) { + throw new RuntimeException("编码失败: " + e.getMessage(), e); + } + } + + private static String encodeBase64(String target) { + return Base64.getEncoder().encodeToString(target.getBytes(StandardCharsets.UTF_8)); + } + + private static String encodeBase64Url(String target) { + return Base64.getUrlEncoder().encodeToString(target.getBytes(StandardCharsets.UTF_8)); + } + + private static String encodeHex(String target) { + byte[] bytes = target.getBytes(StandardCharsets.UTF_8); + return HexFormat.of().formatHex(bytes); + } + + private static String encodeMD5(String target) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("MD5"); + byte[] digest = md.digest(target.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } + + private static String encodeSHA256(String target) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-256"); + byte[] digest = md.digest(target.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } + + private static String encodeSHA1(String target) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] digest = md.digest(target.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } + + private static String removeSpecialChars(String target) { + return target.replaceAll("[^a-zA-Z0-9]", ""); + } + + private static String urlEncode(String target) { + return java.net.URLEncoder.encode(target, StandardCharsets.UTF_8); + } + + // 重载方法,保持向后兼? + public static String encodeByTarget(String target) { + return encodeByTarget(target, Algorithm.REMOVE_SPECIAL_CHARS); + } + + // 工具方法:验证编码结? + public static boolean verify(String original, String encoded, Algorithm algorithm) { + String newEncoded = encodeByTarget(original, algorithm); + return newEncoded.equals(encoded); + } +} diff --git a/src/main/java/cc/amily49/api/module/util/UUIDGenerater.java b/src/main/java/cc/amily49/api/module/util/UUIDGenerater.java new file mode 100644 index 0000000..acac48c --- /dev/null +++ b/src/main/java/cc/amily49/api/module/util/UUIDGenerater.java @@ -0,0 +1,17 @@ +package cc.amily49.api.module.util; + +/** + * @author Silence_Lurker + */ +public class UUIDGenerater { + private UUIDGenerater() { + } + + public static String generate() { + return java.util.UUID.randomUUID().toString(); + } + + public static String generateWithSalt(byte[] salt) { + return java.util.UUID.nameUUIDFromBytes(salt).toString(); + } +} diff --git a/src/main/java/cc/amily49/api/module/warehouse/annotation/Log.java b/src/main/java/cc/amily49/api/module/warehouse/annotation/Log.java new file mode 100644 index 0000000..e2c71fc --- /dev/null +++ b/src/main/java/cc/amily49/api/module/warehouse/annotation/Log.java @@ -0,0 +1,15 @@ +package cc.amily49.api.module.warehouse.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Log { + /** + * Operation description + */ + String value() default ""; +} diff --git a/src/main/java/cc/amily49/api/module/warehouse/aspect/LogAspect.java b/src/main/java/cc/amily49/api/module/warehouse/aspect/LogAspect.java new file mode 100644 index 0000000..bd42fa5 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/warehouse/aspect/LogAspect.java @@ -0,0 +1,137 @@ +package cc.amily49.api.module.warehouse.aspect; + +import cc.amily49.api.module.warehouse.annotation.Log; +import cc.amily49.api.module.warehouse.entity.OperationLog; +import cc.amily49.api.module.warehouse.service.LogService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.time.LocalDateTime; +import java.time.ZoneId; +import org.springframework.beans.factory.annotation.Value; + +@Aspect +@Component +@Slf4j +@RequiredArgsConstructor +public class LogAspect { + + private final LogService logService; + private final ObjectMapper objectMapper; + + @Value("${app.time-zone:Asia/Shanghai}") + private String appTimeZone; + + @Around("@annotation(logAnnotation)") + public Object around(ProceedingJoinPoint point, Log logAnnotation) throws Throwable { + long startTime = System.currentTimeMillis(); + Object result = null; + String exceptionMsg = null; + + try { + result = point.proceed(); + } catch (Throwable e) { + exceptionMsg = e.getMessage(); + throw e; + } finally { + long duration = System.currentTimeMillis() - startTime; + recordLog(point, logAnnotation, duration, exceptionMsg); + } + return result; + } + + private void recordLog(ProceedingJoinPoint point, Log logAnnotation, long duration, String exceptionMsg) { + try { + MethodSignature signature = (MethodSignature) point.getSignature(); + + OperationLog operationLog = new OperationLog(); + if (logAnnotation != null) { + operationLog.setDescription(logAnnotation.value()); + } + + // Method info + String className = point.getTarget().getClass().getName(); + String methodName = signature.getName(); + operationLog.setClassMethod(className + "." + methodName + "()"); + + // Request info + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes != null) { + HttpServletRequest request = attributes.getRequest(); + operationLog.setUrl(request.getRequestURL().toString()); + operationLog.setMethod(request.getMethod()); + operationLog.setIp(getClientIp(request)); + } + + // Args (simplify params to avoid huge logs) + // 如果是登录成功,脱敏参数 + if ("User Login".equals(logAnnotation.value()) && exceptionMsg == null) { + operationLog.setParams("[PROTECTED]"); + } else { + try { + Object[] args = point.getArgs(); + // Filter out non-serializable objects like HttpServletRequest, + // HttpServletResponse + Object[] filteredArgs = Arrays.stream(args) + .filter(arg -> !(arg instanceof jakarta.servlet.http.HttpServletRequest) + && !(arg instanceof jakarta.servlet.http.HttpServletResponse) + && !(arg instanceof org.springframework.web.multipart.MultipartFile)) + .toArray(); + + String params = objectMapper.writeValueAsString(filteredArgs); + // Truncate if too long + if (params.length() > 2000) { + params = params.substring(0, 2000) + "..."; + } + operationLog.setParams(params); + } catch (Exception e) { + operationLog.setParams("Failed to serialize args: " + e.getMessage()); + } + } + + // User info + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.isAuthenticated() && !"anonymousUser".equals(authentication.getPrincipal())) { + operationLog.setUsername(authentication.getName()); + } else { + operationLog.setUsername("Anonymous"); + } + + operationLog.setException(exceptionMsg); + operationLog.setDuration(duration); + operationLog.setCreateTime(LocalDateTime.now(ZoneId.of(appTimeZone))); + + logService.saveLog(operationLog); + + } catch (Exception e) { + log.error("LogAspect error", e); + } + } + + private String getClientIp(HttpServletRequest request) { + String ip = request.getHeader("X-Forwarded-For"); + if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip; + } +} diff --git a/src/main/java/cc/amily49/api/module/warehouse/controller/LogController.java b/src/main/java/cc/amily49/api/module/warehouse/controller/LogController.java new file mode 100644 index 0000000..d9d4499 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/warehouse/controller/LogController.java @@ -0,0 +1,42 @@ +package cc.amily49.api.module.warehouse.controller; + +import cc.amily49.api.module.warehouse.entity.OperationLog; +import cc.amily49.api.module.warehouse.repository.OperationLogRepository; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/logs") +@RequiredArgsConstructor +@Tag(name = "System Logs", description = "Operations for querying system logs") +public class LogController { + + private final OperationLogRepository operationLogRepository; + + @Operation(summary = "Get operation logs", description = "Retrieve paginated operation logs") + @PreAuthorize("hasRole('ADMIN')") + @GetMapping + public ResponseEntity> getLogs( + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size, + @RequestParam(defaultValue = "createTime") String sortBy, + @RequestParam(defaultValue = "desc") String direction) { + + Sort sort = Sort.by(Sort.Direction.fromString(direction), sortBy); + Pageable pageable = PageRequest.of(page, size, sort); + + Page logs = operationLogRepository.findAll(pageable); + return ResponseEntity.ok(logs); + } +} diff --git a/src/main/java/cc/amily49/api/module/warehouse/entity/OperationLog.java b/src/main/java/cc/amily49/api/module/warehouse/entity/OperationLog.java new file mode 100644 index 0000000..c1563e0 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/warehouse/entity/OperationLog.java @@ -0,0 +1,76 @@ +package cc.amily49.api.module.warehouse.entity; + +import jakarta.persistence.*; +import lombok.Data; +import org.hibernate.annotations.CreationTimestamp; + +import java.time.LocalDateTime; + +@Data +@Entity +@Table(name = "operation_log") +public class OperationLog { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + /** + * Operator username + */ + @Column(length = 50) + private String username; + + /** + * Operation description (from annotation) + */ + @Column(length = 255) + private String description; + + /** + * Request URL + */ + @Column(length = 500) + private String url; + + /** + * HTTP Method (GET, POST, etc.) + */ + @Column(length = 10) + private String method; + + /** + * Class and Method name called + */ + @Column(length = 255) + private String classMethod; + + /** + * Client IP Address + */ + @Column(length = 50) + private String ip; + + /** + * Request Parameters (JSON string, truncated if necessary) + */ + @Column(columnDefinition = "TEXT") + private String params; + + /** + * Exception message if failed + */ + @Column(columnDefinition = "TEXT") + private String exception; + + /** + * Execution duration in milliseconds + */ + private Long duration; + + /** + * Operation time + */ + @Column(updatable = false) + private LocalDateTime createTime; +} diff --git a/src/main/java/cc/amily49/api/module/warehouse/repository/OperationLogRepository.java b/src/main/java/cc/amily49/api/module/warehouse/repository/OperationLogRepository.java new file mode 100644 index 0000000..32b0223 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/warehouse/repository/OperationLogRepository.java @@ -0,0 +1,9 @@ +package cc.amily49.api.module.warehouse.repository; + +import cc.amily49.api.module.warehouse.entity.OperationLog; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface OperationLogRepository extends JpaRepository { +} diff --git a/src/main/java/cc/amily49/api/module/warehouse/service/LogService.java b/src/main/java/cc/amily49/api/module/warehouse/service/LogService.java new file mode 100644 index 0000000..f5469f4 --- /dev/null +++ b/src/main/java/cc/amily49/api/module/warehouse/service/LogService.java @@ -0,0 +1,28 @@ +package cc.amily49.api.module.warehouse.service; + +import cc.amily49.api.module.warehouse.entity.OperationLog; +import cc.amily49.api.module.warehouse.repository.OperationLogRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +@Slf4j +public class LogService { + + private final OperationLogRepository operationLogRepository; + + /** + * Save log asynchronously + */ + @Async + public void saveLog(OperationLog logEntry) { + try { + operationLogRepository.save(logEntry); + } catch (Exception e) { + log.error("Failed to save operation log", e); + } + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..72d5018 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,81 @@ +spring.application.name=template-service + +server.port=${SERVER_PORT:8080} +server.forward-headers-strategy=framework + +# =================================================================== +# Primary DataSource (MySQL) - Business Data +# =================================================================== +spring.datasource.primary.hikari.connection-timeout=30000 +spring.datasource.primary.hikari.maximum-pool-size=50 +spring.datasource.primary.hikari.minimum-idle=10 +spring.datasource.primary.hikari.idle-timeout=300000 +spring.datasource.primary.hikari.max-lifetime=600000 +spring.datasource.primary.hikari.keepalive-time=60000 +spring.datasource.primary.hikari.connection-test-query=SELECT 1 +spring.datasource.primary.hikari.validation-timeout=5000 +spring.datasource.primary.hikari.leak-detection-threshold=60000 + +# 数据库配置 +spring.datasource.primary.url=${DB_URL:jdbc:mysql://127.0.0.1:3306/template_db?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai} +spring.datasource.primary.username=${DB_USERNAME:root} +spring.datasource.primary.password=${DB_PASSWORD:} +spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver + +# Flyway +spring.jpa.hibernate.ddl-auto=validate + +# =================================================================== +# Secondary DataSource (PostgreSQL) - Warehouse / Logs +# =================================================================== +spring.datasource.secondary.url=${WAREHOUSE_DB_URL:jdbc:postgresql://127.0.0.1:5432/template_warehouse} +spring.datasource.secondary.username=${WAREHOUSE_DB_USERNAME:postgres} +spring.datasource.secondary.password=${WAREHOUSE_DB_PASSWORD:postgres} +spring.datasource.secondary.driver-class-name=org.postgresql.Driver + +spring.datasource.secondary.hikari.connection-timeout=30000 +spring.datasource.secondary.hikari.maximum-pool-size=20 +spring.datasource.secondary.hikari.minimum-idle=5 +spring.datasource.secondary.hikari.keepalive-time=60000 + +# OpenAPI / Swagger +springdoc.swagger-ui.enabled=true +springdoc.api-docs.path=/v3/api-docs +springdoc.swagger-ui.path=/swagger-ui.html +springdoc.swagger-ui.operationsSorter=alpha +springdoc.swagger-ui.tagsSorter=alpha +springdoc.swagger-ui.display-request-duration=true + +# Redis +spring.data.redis.host=${REDIS_HOST:localhost} +spring.data.redis.port=6379 +spring.data.redis.password=${REDIS_PWD:} + +# JWT Secret Key Configuration +# IMPORTANT: Replace this in production! +amily.jwt.secret=${AMILY_JWT_SECRET:YyNTIzL1snXG0oISVeKFNeJWUhXSpVLSpALXtNWyNeOXIgWyZePShNVHlYPl0uPnZDJV45UnIuWyZeIChNUHlYPl0uPnZD} + +# Mail Configuration +spring.mail.host=${MAIL_HOST:smtp.example.com} +spring.mail.port=${MAIL_PORT:587} +spring.mail.username=${MAIL_USERNAME:} +spring.mail.password=${MAIL_PASSWORD:} +spring.mail.properties.mail.smtp.auth=true +spring.mail.properties.mail.smtp.starttls.enable=true +spring.mail.properties.mail.smtp.starttls.required=true +spring.mail.properties.mail.debug=false +spring.mail.default-encoding=UTF-8 + +# Timezone +app.time-zone=${APP_TIMEZONE:Asia/Shanghai} +spring.jackson.time-zone=${app.time-zone} +spring.jackson.date-format=yyyy-MM-dd HH:mm:ss + +# Quartz Scheduler +spring.quartz.job-store-type=jdbc +spring.quartz.jdbc.initialize-schema=never +spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate +spring.quartz.properties.org.quartz.jobStore.tablePrefix=QRTZ_ +spring.quartz.properties.org.quartz.jobStore.isClustered=false +spring.quartz.properties.org.quartz.scheduler.instanceName=TemplateScheduler +spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO diff --git a/src/main/resources/db/migration/V1__Init_Template_Schema.sql b/src/main/resources/db/migration/V1__Init_Template_Schema.sql new file mode 100644 index 0000000..0e70482 --- /dev/null +++ b/src/main/resources/db/migration/V1__Init_Template_Schema.sql @@ -0,0 +1,258 @@ +-- V1__Init_Template_Schema.sql + +-- ==================================================================================== +-- Auth Module +-- ==================================================================================== + +-- Create user_account_login_info table +CREATE TABLE IF NOT EXISTS user_account_login_info ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + username VARCHAR(255) UNIQUE, + nickname VARCHAR(255), + email VARCHAR(255) UNIQUE, + access_code VARCHAR(255), + salt VARCHAR(255), + allow_ip_change BIT(1) NOT NULL, + last_login_ip VARCHAR(255) +); + +-- Create role table +CREATE TABLE IF NOT EXISTS role ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(255) UNIQUE +); + +-- Create user_roles join table +CREATE TABLE IF NOT EXISTS user_roles ( + user_id BIGINT NOT NULL, + role_id INT NOT NULL, + PRIMARY KEY (user_id, role_id), + FOREIGN KEY (user_id) REFERENCES user_account_login_info(id), + FOREIGN KEY (role_id) REFERENCES role(id) +); + +-- Create user_access_info table +CREATE TABLE IF NOT EXISTS user_access_info ( + uuid VARCHAR(36) PRIMARY KEY, + user_id BIGINT UNIQUE, + FOREIGN KEY (user_id) REFERENCES user_account_login_info(id) +); + +-- Create api_access_info table +CREATE TABLE IF NOT EXISTS api_access_info ( + id VARCHAR(36) PRIMARY KEY, + access_code VARCHAR(255), + access_name VARCHAR(255), + access_uri VARCHAR(255), + access_uri_regex VARCHAR(255), + access_token VARCHAR(255), + user_access_info_id VARCHAR(36), + FOREIGN KEY (user_access_info_id) REFERENCES user_access_info(uuid) +); + +-- Insert default roles +INSERT INTO role (name) SELECT 'ADMIN' WHERE NOT EXISTS (SELECT 1 FROM role WHERE name = 'ADMIN'); +INSERT INTO role (name) SELECT 'USER' WHERE NOT EXISTS (SELECT 1 FROM role WHERE name = 'USER'); + +-- ==================================================================================== +-- Common / Config Module +-- ==================================================================================== + +-- Create system_config table for dynamic settings +CREATE TABLE IF NOT EXISTS system_config ( + config_key VARCHAR(100) NOT NULL PRIMARY KEY, + config_value VARCHAR(500), + description VARCHAR(255) +); + +-- ==================================================================================== +-- Warehouse / Log Module +-- ==================================================================================== + +CREATE TABLE IF NOT EXISTS operation_log ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + username VARCHAR(50), + description VARCHAR(255), + url VARCHAR(500), + method VARCHAR(10), + class_method VARCHAR(255), + ip VARCHAR(50), + params TEXT, + exception TEXT, + duration BIGINT, + create_time DATETIME +); + +-- ==================================================================================== +-- Quartz Scheduler Module +-- ==================================================================================== + +DROP TABLE IF EXISTS QRTZ_FIRED_TRIGGERS; +DROP TABLE IF EXISTS QRTZ_PAUSED_TRIGGER_GRPS; +DROP TABLE IF EXISTS QRTZ_SCHEDULER_STATE; +DROP TABLE IF EXISTS QRTZ_LOCKS; +DROP TABLE IF EXISTS QRTZ_SIMPLE_TRIGGERS; +DROP TABLE IF EXISTS QRTZ_SIMPROP_TRIGGERS; +DROP TABLE IF EXISTS QRTZ_CRON_TRIGGERS; +DROP TABLE IF EXISTS QRTZ_BLOB_TRIGGERS; +DROP TABLE IF EXISTS QRTZ_TRIGGERS; +DROP TABLE IF EXISTS QRTZ_JOB_DETAILS; +DROP TABLE IF EXISTS QRTZ_CALENDARS; + +CREATE TABLE QRTZ_JOB_DETAILS( +SCHED_NAME VARCHAR(120) NOT NULL, +JOB_NAME VARCHAR(200) NOT NULL, +JOB_GROUP VARCHAR(200) NOT NULL, +DESCRIPTION VARCHAR(250) NULL, +JOB_CLASS_NAME VARCHAR(250) NOT NULL, +IS_DURABLE VARCHAR(1) NOT NULL, +IS_NONCONCURRENT VARCHAR(1) NOT NULL, +IS_UPDATE_DATA VARCHAR(1) NOT NULL, +REQUESTS_RECOVERY VARCHAR(1) NOT NULL, +JOB_DATA BLOB NULL, +PRIMARY KEY (SCHED_NAME,JOB_NAME,JOB_GROUP)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_TRIGGERS ( +SCHED_NAME VARCHAR(120) NOT NULL, +TRIGGER_NAME VARCHAR(200) NOT NULL, +TRIGGER_GROUP VARCHAR(200) NOT NULL, +JOB_NAME VARCHAR(200) NOT NULL, +JOB_GROUP VARCHAR(200) NOT NULL, +DESCRIPTION VARCHAR(250) NULL, +NEXT_FIRE_TIME BIGINT(13) NULL, +PREV_FIRE_TIME BIGINT(13) NULL, +PRIORITY INTEGER NULL, +TRIGGER_STATE VARCHAR(16) NOT NULL, +TRIGGER_TYPE VARCHAR(8) NOT NULL, +START_TIME BIGINT(13) NOT NULL, +END_TIME BIGINT(13) NULL, +CALENDAR_NAME VARCHAR(200) NULL, +MISFIRE_INSTR SMALLINT(2) NULL, +JOB_DATA BLOB NULL, +PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), +FOREIGN KEY (SCHED_NAME,JOB_NAME,JOB_GROUP) +REFERENCES QRTZ_JOB_DETAILS(SCHED_NAME,JOB_NAME,JOB_GROUP)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_SIMPLE_TRIGGERS ( +SCHED_NAME VARCHAR(120) NOT NULL, +TRIGGER_NAME VARCHAR(200) NOT NULL, +TRIGGER_GROUP VARCHAR(200) NOT NULL, +REPEAT_COUNT BIGINT(7) NOT NULL, +REPEAT_INTERVAL BIGINT(12) NOT NULL, +TIMES_TRIGGERED BIGINT(10) NOT NULL, +PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), +FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) +REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_CRON_TRIGGERS ( +SCHED_NAME VARCHAR(120) NOT NULL, +TRIGGER_NAME VARCHAR(200) NOT NULL, +TRIGGER_GROUP VARCHAR(200) NOT NULL, +CRON_EXPRESSION VARCHAR(120) NOT NULL, +TIME_ZONE_ID VARCHAR(80), +PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), +FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) +REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_SIMPROP_TRIGGERS ( +SCHED_NAME VARCHAR(120) NOT NULL, +TRIGGER_NAME VARCHAR(200) NOT NULL, +TRIGGER_GROUP VARCHAR(200) NOT NULL, +STR_PROP_1 VARCHAR(512) NULL, +STR_PROP_2 VARCHAR(512) NULL, +STR_PROP_3 VARCHAR(512) NULL, +INT_PROP_1 INT NULL, +INT_PROP_2 INT NULL, +LONG_PROP_1 BIGINT NULL, +LONG_PROP_2 BIGINT NULL, +DEC_PROP_1 NUMERIC(13,4) NULL, +DEC_PROP_2 NUMERIC(13,4) NULL, +BOOL_PROP_1 VARCHAR(1) NULL, +BOOL_PROP_2 VARCHAR(1) NULL, +PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), +FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) +REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_BLOB_TRIGGERS ( +SCHED_NAME VARCHAR(120) NOT NULL, +TRIGGER_NAME VARCHAR(200) NOT NULL, +TRIGGER_GROUP VARCHAR(200) NOT NULL, +BLOB_DATA BLOB NULL, +PRIMARY KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP), +INDEX (SCHED_NAME,TRIGGER_NAME, TRIGGER_GROUP), +FOREIGN KEY (SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP) +REFERENCES QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_CALENDARS ( +SCHED_NAME VARCHAR(120) NOT NULL, +CALENDAR_NAME VARCHAR(200) NOT NULL, +CALENDAR BLOB NOT NULL, +PRIMARY KEY (SCHED_NAME,CALENDAR_NAME)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_PAUSED_TRIGGER_GRPS ( +SCHED_NAME VARCHAR(120) NOT NULL, +TRIGGER_GROUP VARCHAR(200) NOT NULL, +PRIMARY KEY (SCHED_NAME,TRIGGER_GROUP)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_FIRED_TRIGGERS ( +SCHED_NAME VARCHAR(120) NOT NULL, +ENTRY_ID VARCHAR(95) NOT NULL, +TRIGGER_NAME VARCHAR(200) NOT NULL, +TRIGGER_GROUP VARCHAR(200) NOT NULL, +INSTANCE_NAME VARCHAR(200) NOT NULL, +FIRED_TIME BIGINT(13) NOT NULL, +SCHED_TIME BIGINT(13) NOT NULL, +PRIORITY INTEGER NOT NULL, +STATE VARCHAR(16) NOT NULL, +JOB_NAME VARCHAR(200) NULL, +JOB_GROUP VARCHAR(200) NULL, +IS_NONCONCURRENT VARCHAR(1) NULL, +REQUESTS_RECOVERY VARCHAR(1) NULL, +PRIMARY KEY (SCHED_NAME,ENTRY_ID)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_SCHEDULER_STATE ( +SCHED_NAME VARCHAR(120) NOT NULL, +INSTANCE_NAME VARCHAR(200) NOT NULL, +LAST_CHECKIN_TIME BIGINT(13) NOT NULL, +CHECKIN_INTERVAL BIGINT(13) NOT NULL, +PRIMARY KEY (SCHED_NAME,INSTANCE_NAME)) +ENGINE=InnoDB; + +CREATE TABLE QRTZ_LOCKS ( +SCHED_NAME VARCHAR(120) NOT NULL, +LOCK_NAME VARCHAR(40) NOT NULL, +PRIMARY KEY (SCHED_NAME,LOCK_NAME)) +ENGINE=InnoDB; + +CREATE INDEX IDX_QRTZ_J_REQ_RECOVERY ON QRTZ_JOB_DETAILS(SCHED_NAME,REQUESTS_RECOVERY); +CREATE INDEX IDX_QRTZ_J_GRP ON QRTZ_JOB_DETAILS(SCHED_NAME,JOB_GROUP); + +CREATE INDEX IDX_QRTZ_T_J ON QRTZ_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP); +CREATE INDEX IDX_QRTZ_T_JG ON QRTZ_TRIGGERS(SCHED_NAME,JOB_GROUP); +CREATE INDEX IDX_QRTZ_T_C ON QRTZ_TRIGGERS(SCHED_NAME,CALENDAR_NAME); +CREATE INDEX IDX_QRTZ_T_G ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_GROUP); +CREATE INDEX IDX_QRTZ_T_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE); +CREATE INDEX IDX_QRTZ_T_N_STATE ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP,TRIGGER_STATE); +CREATE INDEX IDX_QRTZ_T_NEXT_FIRE_TIME ON QRTZ_TRIGGERS(SCHED_NAME,NEXT_FIRE_TIME); +CREATE INDEX IDX_QRTZ_T_NFT_ST ON QRTZ_TRIGGERS(SCHED_NAME,TRIGGER_STATE,NEXT_FIRE_TIME); +CREATE INDEX IDX_QRTZ_T_NFT_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME); +CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_STATE); +CREATE INDEX IDX_QRTZ_T_NFT_ST_MISFIRE_GRP ON QRTZ_TRIGGERS(SCHED_NAME,MISFIRE_INSTR,NEXT_FIRE_TIME,TRIGGER_GROUP,TRIGGER_STATE); + +CREATE INDEX IDX_QRTZ_FT_TRIG_INST_NAME ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME); +CREATE INDEX IDX_QRTZ_FT_INST_JOB_REQ_RCVRY ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,INSTANCE_NAME,REQUESTS_RECOVERY); +CREATE INDEX IDX_QRTZ_FT_J_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_NAME,JOB_GROUP); +CREATE INDEX IDX_QRTZ_FT_JG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,JOB_GROUP); +CREATE INDEX IDX_QRTZ_FT_T_G ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_NAME,TRIGGER_GROUP); +CREATE INDEX IDX_QRTZ_FT_TG ON QRTZ_FIRED_TRIGGERS(SCHED_NAME,TRIGGER_GROUP); + +commit;