Browse Source

first commit

zhangwl 1 month ago
commit
91b1ad3574

+ 31 - 0
HELP.md

@@ -0,0 +1,31 @@
+# Getting Started
+
+### Reference Documentation
+
+For further reference, please consider the following sections:
+
+* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
+* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/3.5.11/maven-plugin)
+* [Create an OCI image](https://docs.spring.io/spring-boot/3.5.11/maven-plugin/build-image.html)
+* [JDBC API](https://docs.spring.io/spring-boot/3.5.11/reference/data/sql.html)
+* [Spring Web](https://docs.spring.io/spring-boot/3.5.11/reference/web/servlet.html)
+
+### Guides
+
+The following guides illustrate how to use some features concretely:
+
+* [Accessing Relational Data using JDBC with Spring](https://spring.io/guides/gs/relational-data-access/)
+* [Managing Transactions](https://spring.io/guides/gs/managing-transactions/)
+* [Accessing data with MySQL](https://spring.io/guides/gs/accessing-data-mysql/)
+* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/)
+* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/)
+* [Building REST services with Spring](https://spring.io/guides/tutorials/rest/)
+
+### Maven Parent overrides
+
+Due to Maven's design, elements are inherited from the parent POM to the project POM.
+While most of the inheritance is fine, it also inherits unwanted elements like `<license>` and `<developers>` from the
+parent.
+To prevent this, the project POM contains empty overrides for these elements.
+If you manually switch to a different parent and actually want the inheritance, you need to remove those overrides.
+

+ 295 - 0
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-<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 - 0
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-<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"

+ 129 - 0
pom.xml

@@ -0,0 +1,129 @@
+<?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.5</version>
+        <relativePath/>
+    </parent>
+    <groupId>com.zhongsou</groupId>
+    <artifactId>db-ai</artifactId>
+    <version>0.0.1-SNAPSHOT</version>
+    <name>db-ai</name>
+    <description>对接火山豆包助手API的新项目</description>
+
+    <properties>
+        <java.version>17</java.version>
+        <!-- 显式指定 Jackson 版本,修复 DoS 漏洞 -->
+        <jackson.version>2.15.7</jackson.version>
+        <!-- MyBatis-Plus 版本(适配 Spring Boot 3.2.x) -->
+        <mybatis-plus.version>3.5.5</mybatis-plus.version>
+    </properties>
+
+    <dependencies>
+        <!-- 核心:Spring Web(自带RestTemplate、Jackson) -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <!-- 仅需这一行,包含Redis核心+自动配置,无需额外依赖 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-data-redis</artifactId>
+        </dependency>
+
+        <!-- 数据库:JDBC + MySQL(按需保留) -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-jdbc</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.mysql</groupId>
+            <artifactId>mysql-connector-j</artifactId>
+            <scope>runtime</scope>
+        </dependency>
+
+        <!-- MyBatis-Plus 核心依赖(适配 Spring Boot 3.x) -->
+        <dependency>
+            <groupId>com.baomidou</groupId>
+            <artifactId>mybatis-plus-boot-starter</artifactId>
+            <version>${mybatis-plus.version}</version>
+        </dependency>
+
+        <!-- Lombok(简化代码) -->
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <optional>true</optional>
+        </dependency>
+
+        <!-- 测试依赖 -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+        <!-- FastJson2 核心依赖 -->
+        <dependency>
+            <groupId>com.alibaba.fastjson2</groupId>
+            <artifactId>fastjson2</artifactId>
+            <version>2.0.45</version>
+        </dependency>
+
+        <!-- FastJson2 与 Spring 6 整合 -->
+        <dependency>
+            <groupId>com.alibaba.fastjson2</groupId>
+            <artifactId>fastjson2-extension-spring6</artifactId>
+            <version>2.0.45</version>
+        </dependency>
+
+        <!-- SpringDoc OpenAPI(Swagger UI),测试接口超方便 -->
+        <dependency>
+            <groupId>org.springdoc</groupId>
+            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
+            <version>2.3.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.jetbrains</groupId>
+            <artifactId>annotations</artifactId>
+            <version>24.0.0</version>
+            <scope>compile</scope>
+        </dependency>
+
+        <!-- Spring WebFlux(包含 WebClient) -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-webflux</artifactId>
+            <!-- 锁定稳定版本,和你的 Spring Boot 版本保持一致 -->
+            <version>3.2.4</version>
+        </dependency>
+
+        <!-- 可选:如果需要更灵活的响应式处理 -->
+        <dependency>
+            <groupId>io.projectreactor</groupId>
+            <artifactId>reactor-core</artifactId>
+            <version>3.6.4</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>

+ 13 - 0
src/main/java/com/zhongsou/dbai/DbAiApplication.java

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

+ 113 - 0
src/main/java/com/zhongsou/dbai/controller/AiChatController.java

@@ -0,0 +1,113 @@
+package com.zhongsou.dbai.controller;
+
+import com.zhongsou.dbai.service.DouBaoAgentService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.responses.ApiResponses;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
+import reactor.core.publisher.Flux;
+
+import java.io.IOException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+@Slf4j
+@RestController
+@RequiredArgsConstructor
+@Tag(name = "AI聊天接口", description = "支持SSE流式响应")
+public class AiChatController {
+
+    private final DouBaoAgentService douBaoAgentService;
+    private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool();
+
+    @GetMapping(value = "/chat/stream/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
+    @Operation(summary = "AI流式问答", description = "用户提问,AI逐字返回回答(对接火山引擎+原路径)")
+    @ApiResponses(value = {
+            @ApiResponse(
+                    responseCode = "200",
+                    description = "成功返回流式响应",
+                    content = @Content(
+                            mediaType = MediaType.TEXT_EVENT_STREAM_VALUE,
+                            schema = @Schema(implementation = String.class)
+                    )
+            ),
+            @ApiResponse(responseCode = "400", description = "参数错误(userId/ask不能为空)"),
+            @ApiResponse(responseCode = "500", description = "服务器内部错误")
+    })
+    public SseEmitter chatAiStream(
+            @Parameter(description = "用户唯一标识", required = true, example = "6535668")
+            @PathVariable String userId,
+            @Parameter(description = "用户提问内容", required = true, example = "云悦AI是什么?")
+            @RequestParam String ask) {
+
+        // 超时时间30秒,与 Service 层超时配合,确保前端不会无限等待
+        SseEmitter emitter = new SseEmitter(30000L);
+        emitter.onTimeout(() -> {
+            log.warn("用户{} SSE连接超时", userId);
+            emitter.complete();
+        });
+        emitter.onCompletion(() -> log.info("用户{} SSE连接正常关闭", userId));
+        emitter.onError(throwable -> {
+            // 仅当是未关闭的异常时才记录,避免日志刷屏
+            if (!(throwable instanceof IllegalStateException && throwable.getMessage().contains("already completed"))) {
+                log.error("用户{} SSE连接异常", userId, throwable);
+            }
+            emitter.completeWithError(throwable);
+        });
+
+        EXECUTOR.execute(() -> {
+            try {
+                Flux<String> textFlux = douBaoAgentService.stream(userId, ask);
+
+                textFlux.subscribe(
+                        text -> {
+                            try {
+                                emitter.send(SseEmitter.event().data(text, MediaType.TEXT_PLAIN));
+                            } catch (IOException e) {
+                                // 如果 emitter 已经关闭,忽略此异常
+                                if (!(e.getMessage() != null && e.getMessage().contains("already completed"))) {
+                                    log.warn("用户{} 推送文本失败", userId, e);
+                                }
+                            }
+                        },
+                        e -> {
+                            // 如果异常是 IllegalStateException 且消息包含 "already completed",说明 emitter 已关闭,无需再调 completeWithError
+                            if (e instanceof IllegalStateException && e.getMessage().contains("already completed")) {
+                                log.debug("用户{} SSE已关闭,忽略后续异常", userId);
+                            } else {
+                                log.error("用户{} 流式处理异常", userId, e);
+                                try {
+                                    emitter.send(SseEmitter.event().data("process:服务处理异常,请稍后再试"));
+                                } catch (IOException ex) {
+                                    // 忽略
+                                }
+                                emitter.completeWithError(e);
+                            }
+                        },
+                        () -> {
+                            log.info("用户{} 流式响应推送完成", userId);
+                            emitter.complete();
+                        }
+                );
+            } catch (Exception e) {
+                log.error("用户{} 流式请求初始化失败", userId, e);
+                try {
+                    emitter.send(SseEmitter.event().data("抱歉,请求处理失败,请稍后再试~"));
+                } catch (IOException ex) {
+                    // 忽略
+                }
+                emitter.completeWithError(e);
+            }
+        });
+
+        return emitter;
+    }
+}

+ 169 - 0
src/main/java/com/zhongsou/dbai/service/DouBaoAgentService.java

@@ -0,0 +1,169 @@
+package com.zhongsou.dbai.service;
+
+import com.alibaba.fastjson2.JSONArray;
+import com.alibaba.fastjson2.JSONObject;
+import com.baomidou.mybatisplus.core.toolkit.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.jetbrains.annotations.NotNull;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Service;
+import org.springframework.web.reactive.function.client.WebClient;
+import org.springframework.web.reactive.function.client.WebClientResponseException;
+import reactor.core.publisher.Flux;
+import reactor.util.retry.Retry;
+
+import java.time.Duration;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+@Service
+@Slf4j
+public class DouBaoAgentService {
+
+    private final Map<String, String> userLastResponseIdMap = new ConcurrentHashMap<>();
+    private static final String API_URL = "https://ark.cn-beijing.volces.com/api/v3/responses";
+    private static final String MODEL = "doubao-seed-1-8-251228";
+
+    @Value("${doubao.agent.api-key}")
+    private String apiKey;
+
+    @Value("${yunyue.ai.role-description}")
+    private String roleDescription;
+
+    private final WebClient webClient = WebClient.builder()
+            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+            .build();
+
+    public Flux<String> stream(String userId, String question) {
+        String lastResponseId = userLastResponseIdMap.get(userId);
+        log.info("用户{} lastResponseId:{}", userId, lastResponseId);
+        JSONObject body = buildRequest(userId, question, lastResponseId);
+        log.info("用户{} 请求体: {}", userId, body.toJSONString());
+
+        return webClient.post()
+                .uri(API_URL)
+                .header("Authorization", "Bearer " + apiKey)
+                .header("ark-beta-doubao-app", "true")
+                .bodyValue(body.toString())
+                .retrieve()
+                .bodyToFlux(String.class)
+                .timeout(Duration.ofSeconds(25))   // 整体超时25秒,避免无响应
+                .retryWhen(Retry.backoff(1, Duration.ofSeconds(2))
+                        .filter(throwable -> throwable instanceof java.util.concurrent.TimeoutException)
+                        .doBeforeRetry(rs -> log.warn("用户{} 火山API超时,正在进行第{}次重试", userId, rs.totalRetries() + 1))
+                )
+                .doOnNext(line -> {
+                    String cleanLine = cleanSseLine(line);
+                    if (StringUtils.isBlank(cleanLine)) {
+                        return;
+                    }
+                    updateLastResponseIdOnCompleted(userId, cleanLine);
+                })
+                .onErrorResume(throwable -> {
+                    log.error("用户{} 调用火山失败", userId, throwable);
+
+                    // 1. 处理400错误:PreviousResponseNotFound -> 清除本地ID并降级
+                    if (throwable instanceof WebClientResponseException) {
+                        WebClientResponseException ex = (WebClientResponseException) throwable;
+                        String errorBody = ex.getResponseBodyAsString();
+                        log.error("火山错误详情 - 状态码: {}, 错误体: {}", ex.getStatusCode(), errorBody);
+
+                        // 上下文ID无效:清除本地存储,并返回新对话提示(前端可重试)
+                        if (ex.getStatusCode() == HttpStatus.BAD_REQUEST && errorBody != null && errorBody.contains("PreviousResponseNotFound")) {
+                            userLastResponseIdMap.remove(userId);
+                            log.warn("用户{} 上下文ID已失效,已清除,本次将作为新对话处理", userId);
+                            // 返回一个特殊标记,让前端可以自动重试(或直接返回友好提示)
+                            return Flux.just("process:检测到会话已过期,请稍后重试(已自动开启新会话)");
+                        }
+
+                        // 2. 处理429限流:返回友好提示
+                        if (ex.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS) {
+                            return Flux.just("process:当前提问人数较多,请稍后再试~");
+                        }
+                    }
+
+                    // 3. 其他异常(包括超时后重试仍然失败)统一返回友好提示
+                    return Flux.just("process:服务暂时无法响应,请稍后再试~");
+                });
+    }
+
+    @NotNull
+    private JSONObject buildRequest(String userId, String question, String lastResponseId) {
+        // 严格按照官方文档构造 input
+        JSONObject inputMsg = new JSONObject();
+        inputMsg.put("type", "message");
+        inputMsg.put("role", "user");
+        JSONObject contentItem = new JSONObject();
+        contentItem.put("type", "input_text");
+        contentItem.put("text", question);
+        inputMsg.put("content", JSONArray.of(contentItem));
+
+        // 构造 tools
+        JSONObject feature = new JSONObject();
+        feature.put("ai_search", JSONObject.of(
+                "type", "enabled",
+                "role_description", roleDescription
+        ));
+        feature.put("chat", JSONObject.of("type", "disabled"));
+        feature.put("deep_chat", JSONObject.of("type", "disabled"));
+        feature.put("reasoning_search", JSONObject.of("type", "disabled"));
+
+        JSONObject tool = new JSONObject();
+        tool.put("type", "doubao_app");
+        tool.put("feature", feature);
+
+        // 最终请求体
+        JSONObject request = new JSONObject();
+        request.put("model", MODEL);
+        request.put("stream", true);
+        request.put("input", JSONArray.of(inputMsg));
+        request.put("tools", JSONArray.of(tool));
+        request.put("store", true);      // 必须开启存储
+
+        if (StringUtils.isNotBlank(lastResponseId)) {
+            request.put("previous_response_id", lastResponseId);
+            log.info("用户{} 携带上下文ID: {}", userId, lastResponseId);
+        }
+
+        return request;
+    }
+
+    private @NotNull String cleanSseLine(String line) {
+        if (StringUtils.isBlank(line)) return "";
+        String clean = line.trim().replaceFirst("^data:\\s*", "");
+        return "[DONE]".equals(clean) || clean.isEmpty() ? "" : clean;
+    }
+
+    /**
+     * 仅在 response.completed 事件中更新ID,确保持久化完成
+     */
+    private void updateLastResponseIdOnCompleted(String userId, String cleanLine) {
+        try {
+            JSONObject respObj = JSONObject.parseObject(cleanLine);
+            String type = respObj.getString("type");
+            if (!"response.completed".equals(type)) {
+                return;
+            }
+            JSONObject response = respObj.getJSONObject("response");
+            if (response == null) return;
+
+            String newResponseId = response.getString("id");
+            if (StringUtils.isBlank(newResponseId)) return;
+
+            String oldResponseId = userLastResponseIdMap.get(userId);
+            if (!newResponseId.equals(oldResponseId)) {
+                userLastResponseIdMap.put(userId, newResponseId);
+                log.info("用户{} 对话完成,更新上下文ID: {} -> {}",
+                        userId,
+                        oldResponseId == null ? "null" : oldResponseId.substring(0, 20),
+                        newResponseId.substring(0, 20));
+            }
+        } catch (Exception e) {
+            // 解析失败不影响主流程
+            log.debug("用户{} 解析response.id失败(非核心事件)", userId);
+        }
+    }
+}

+ 173 - 0
src/main/java/com/zhongsou/dbai/service/DouBaoAgentServiceBak.java

@@ -0,0 +1,173 @@
+package com.zhongsou.dbai.service;
+
+import com.alibaba.fastjson2.JSONArray;
+import com.alibaba.fastjson2.JSONObject;
+import com.baomidou.mybatisplus.core.toolkit.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.jetbrains.annotations.NotNull;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Service;
+import org.springframework.web.reactive.function.client.WebClient;
+import reactor.core.publisher.Flux;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+@Service
+@Slf4j
+public class DouBaoAgentServiceBak {
+
+    private static final String API_URL = "https://ark.cn-beijing.volces.com/api/v3/responses";
+    private static final String MODEL = "doubao-seed-1-8-251228";
+
+    @Value("${doubao.agent.api-key}")
+    private String apiKey;
+
+    @Value("${yunyue.ai.role-description}")
+    private String roleDescription;
+
+    // 保留你原有的WebClient初始化
+    private final WebClient webClient = WebClient.builder()
+            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
+            .build();
+
+    // 保留你原有的stream方法结构,核心修复convertToUnifiedFormat逻辑
+    public Flux<String> stream(String userId, String question) {
+        JSONObject body = buildBody(question);
+        // 新增:原子布尔值确保只输出一次结束符
+        AtomicBoolean isDoneEmitted = new AtomicBoolean(false);
+
+        return webClient.post()
+                .uri(API_URL)
+                .header("Authorization", "Bearer " + apiKey)
+                .header("ark-beta-doubao-app", "true")
+                .bodyValue(body.toString())
+                .retrieve()
+                .bodyToFlux(String.class)
+                .doOnNext(line -> log.debug("[火山原始行] {}", line))
+                .map(line -> convertToUnifiedFormat(line, isDoneEmitted)) // 传入结束符标记
+                .filter(StringUtils::isNotBlank) // 过滤所有空行
+                .onErrorResume(e -> {
+                    log.error("调用火山引擎失败", e);
+                    return Flux.just("process:服务暂时无法响应,请稍后再试~");
+                });
+    }
+
+    /**
+     * 彻底修复版:
+     * 1. 过滤所有空delta/空searching_state
+     * 2. 确保[DONE]只输出一次
+     * 3. 过滤所有冗余结构化行
+     * 4. 统一输出格式为 process:xxx / text:xxx
+     */
+    private @NotNull String convertToUnifiedFormat(String line, AtomicBoolean isDoneEmitted) {
+        if (StringUtils.isBlank(line)) {
+            return "";
+        }
+
+        // 处理纯文本[DONE]行(避免双结束符)
+        String trimLine = line.trim();
+        if ("[DONE]".equals(trimLine)) {
+            // 只有未输出过结束符时才处理
+            if (isDoneEmitted.compareAndSet(false, true)) {
+                return "[DONE]";
+            }
+            return "";
+        }
+
+        try {
+            JSONObject obj = JSONObject.parseObject(line);
+            String type = obj.getString("type");
+
+            // ========== 1. 进度消息处理:过滤空状态 ==========
+            String processText = null;
+            if ("response.created".equals(type)) {
+                processText = "云悦AI思索中...";
+            } else if ("response.in_progress".equals(type)) {
+                processText = "正在处理中,请稍候...";
+            } else if ("response.doubao_app_call_search.in_progress".equals(type)) {
+                processText = "开始搜索相关资料...";
+            } else if ("response.doubao_app_call_search.searching".equals(type)) {
+                processText = obj.getString("searching_state");
+                // 过滤空的searching_state
+                if (StringUtils.isBlank(processText)) {
+                    return "";
+                }
+            } else if ("response.doubao_app_call_search.completed".equals(type)) {
+                processText = obj.getString("summary");
+            } else if ("response.doubao_app_call_start".equals(type)
+                    || "response.doubao_app_call_progress".equals(type)) {
+                processText = "正在调用工具处理你的问题...";
+            }
+
+            // 输出进度消息(确保非空)
+            if (StringUtils.isNotBlank(processText)) {
+                return "process:" + processText;
+            }
+
+            // ========== 2. 文本内容处理:严格过滤空delta ==========
+            if ("response.doubao_app_call_output_text.delta".equals(type)) {
+                String delta = obj.getString("delta");
+                // 核心修复:过滤所有空delta(包括全空格)
+                if (StringUtils.isBlank(delta)) {
+                    return "";
+                }
+                return  delta;
+            }
+
+            // ========== 3. 结束符处理:只输出一次 ==========
+            if ("response.completed".equals(type)) {
+                if (isDoneEmitted.compareAndSet(false, true)) {
+                    return "text:[DONE]";
+                }
+                return "";
+            }
+
+            // ========== 4. 过滤所有冗余结构化行 ==========
+            // 覆盖日志中出现的所有冗余类型,确保无遗漏
+            if ("response.output_item.added".equals(type)
+                    || "response.output_item.done".equals(type)
+                    || "response.doubao_app_call_block.added".equals(type)
+                    || "response.doubao_app_call_block.done".equals(type)
+                    || "response.doubao_app_call_output_text.done".equals(type)
+                    || "response.doubao_app_call.completed".equals(type)
+                    || "response.doubao_app_call.in_progress".equals(type)) {
+                return "";
+            }
+
+            // 其他未匹配的JSON行返回空
+            return "";
+
+        } catch (Exception e) {
+            log.debug("非JSON行且非结束符,过滤: {}", line, e);
+            return "";
+        }
+    }
+
+    /**
+     * 保留原有请求体构建逻辑,无修改
+     */
+    private @NotNull JSONObject buildBody(String question) {
+        JSONObject input = new JSONObject();
+        input.put("type", "message");
+        input.put("role", "user");
+        input.put("content", JSONArray.of(
+                JSONObject.of("type", "input_text", "text", question)
+        ));
+
+        JSONObject feature = new JSONObject();
+        feature.put("ai_search", JSONObject.of("type", "enabled", "role_description", roleDescription));
+        feature.put("chat", JSONObject.of("type", "disabled"));
+        feature.put("deep_chat", JSONObject.of("type", "disabled"));
+        feature.put("reasoning_search", JSONObject.of("type", "disabled"));
+
+        return JSONObject.of(
+                "model", MODEL,
+                "stream", true,
+                "input", JSONArray.of(input),
+                "tools", JSONArray.of(JSONObject.of("type", "doubao_app", "feature", feature)),
+                "store", true
+        );
+    }
+}

+ 68 - 0
src/main/resources/application.yml

@@ -0,0 +1,68 @@
+# 服务器基础配置
+server:
+  port: 8081
+  servlet:
+    encoding:
+      charset: UTF-8
+      force: true
+      enabled: true
+
+# Spring核心配置
+spring:
+  application:
+    name: db-ai
+  messages:
+    encoding: UTF-8
+  # 单数据源配置(仅保留online库)
+  datasource:
+    driver-class-name: com.mysql.cj.jdbc.Driver
+    url: jdbc:mysql://rm-2zelpi3n5442058bq.mysql.rds.aliyuncs.com:3306/moblie_cloud_online?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
+    username: mob_on
+    password: "Mo11@BL7i!@"
+
+# 日志配置(顶级配置,和spring平级)
+logging:
+  level:
+    root: INFO
+    com.zhongsou.dbai: DEBUG
+    org.springframework.web: INFO
+    com.baomidou.mybatisplus: INFO
+  file:
+    path: ./log
+    name: ./log/db-ai.log
+  pattern:
+    console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"
+    file: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"
+  logback:
+    rollingpolicy:
+      max-file-size: 100MB
+      max-history: 7
+      total-size-cap: 1GB
+      clean-history-on-start: false
+
+# MyBatis-Plus极简配置
+mybatis-plus:
+  configuration:
+    map-underscore-to-camel-case: true
+    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
+  global-config:
+    db-config:
+      logic-delete-field: isDeleted
+      logic-delete-value: 1
+      logic-not-delete-value: 0
+  type-aliases-package: com.zhongsou.dbai.entity
+
+# 火山豆包助手API配置(极致精简版)
+doubao:
+  agent:
+    api-key: dfd84b63-d520-484e-a3db-effc2067287b  # 唯一可配置:API密钥
+
+# 云悦AI唯一角色描述(整合所有规则,无多余配置)
+yunyue:
+  ai:
+    role-description: |
+      你的专属名字是云悦AI,禁止自称豆包或其他名称。
+      回答风格:超级亲切自然、口语化,像和师兄师姐聊天一样,专业又不生硬,缺关键信息时主动友好反问(比如问天气先问城市),语气活泼不刻板。
+      核心规则:你可以调用web_search工具获取实时信息(如天气、新闻等),调用工具后需基于搜索结果回答用户问题;
+      所有涉及实时数据、时间计算、最新事件的问题(如冲突天数、天气、新闻、赛事),必须先通过实时联网搜索获取当前最新数据,禁止使用内置旧数据;
+      回答时优先用中文,避免生僻术语,必要时举例说明,保证易懂。

+ 13 - 0
src/test/java/com/zhongsou/dbai/DbAiApplicationTests.java

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