commit
e7184d4d19
13 changed files with 1271 additions and 0 deletions
@ -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 "$@" |
||||
@ -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" |
||||
@ -0,0 +1,94 @@ |
|||||
|
<?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.5.11</version> |
||||
|
<relativePath/> <!-- lookup parent from repository --> |
||||
|
</parent> |
||||
|
<groupId>com.aeon</groupId> |
||||
|
<artifactId>aeon-tcp</artifactId> |
||||
|
<version>0.0.1-SNAPSHOT</version> |
||||
|
<name>tcp</name> |
||||
|
<description>tcp server</description> |
||||
|
<url/> |
||||
|
<licenses> |
||||
|
<license/> |
||||
|
</licenses> |
||||
|
<developers> |
||||
|
<developer/> |
||||
|
</developers> |
||||
|
<scm> |
||||
|
<connection/> |
||||
|
<developerConnection/> |
||||
|
<tag/> |
||||
|
<url/> |
||||
|
</scm> |
||||
|
<properties> |
||||
|
<java.version>17</java.version> |
||||
|
</properties> |
||||
|
<dependencies> |
||||
|
<dependency> |
||||
|
<groupId>org.springframework.boot</groupId> |
||||
|
<artifactId>spring-boot-starter</artifactId> |
||||
|
</dependency> |
||||
|
|
||||
|
<dependency> |
||||
|
<groupId>org.springframework.boot</groupId> |
||||
|
<artifactId>spring-boot-starter-web</artifactId> |
||||
|
</dependency> |
||||
|
|
||||
|
<dependency> |
||||
|
<groupId>org.springframework.boot</groupId> |
||||
|
<artifactId>spring-boot-starter-test</artifactId> |
||||
|
<scope>test</scope> |
||||
|
</dependency> |
||||
|
|
||||
|
<dependency> |
||||
|
<groupId>org.projectlombok</groupId> |
||||
|
<artifactId>lombok</artifactId> |
||||
|
</dependency> |
||||
|
|
||||
|
<!-- Source: https://mvnrepository.com/artifact/io.netty/netty-all --> |
||||
|
<dependency> |
||||
|
<groupId>io.netty</groupId> |
||||
|
<artifactId>netty-all</artifactId> |
||||
|
<version>4.2.10.Final</version> |
||||
|
<scope>compile</scope> |
||||
|
</dependency> |
||||
|
</dependencies> |
||||
|
|
||||
|
<build> |
||||
|
<plugins> |
||||
|
<plugin> |
||||
|
<groupId>org.springframework.boot</groupId> |
||||
|
<artifactId>spring-boot-maven-plugin</artifactId> |
||||
|
</plugin> |
||||
|
|
||||
|
<plugin> |
||||
|
<groupId>io.fabric8</groupId> |
||||
|
<artifactId>docker-maven-plugin</artifactId> |
||||
|
<version>0.38.1</version> |
||||
|
<configuration> |
||||
|
<authConfig> |
||||
|
<username>AKIAQNYBBSGDVT3VF4ON</username> |
||||
|
<password>DEhPMTHAIsKK7L2klURQrmMe3r2Tqgbaa6z2FYQu</password> |
||||
|
</authConfig> |
||||
|
<images> |
||||
|
<image> |
||||
|
<name>${aws.ecr.registryTest}/aeon/${aws.ecr.repositoryTest}:latest</name> |
||||
|
<registry>${aws.ecr.registry}</registry> |
||||
|
<build> |
||||
|
<dockerFile>${project.basedir}/Dockerfile</dockerFile> |
||||
|
</build> |
||||
|
</image> |
||||
|
</images> |
||||
|
</configuration> |
||||
|
</plugin> |
||||
|
|
||||
|
</plugins> |
||||
|
</build> |
||||
|
|
||||
|
</project> |
||||
@ -0,0 +1,13 @@ |
|||||
|
package com.aeon.tcp; |
||||
|
|
||||
|
import org.springframework.boot.SpringApplication; |
||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication; |
||||
|
|
||||
|
@SpringBootApplication |
||||
|
public class TcpApplication { |
||||
|
|
||||
|
public static void main(String[] args) { |
||||
|
SpringApplication.run(TcpApplication.class, args); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,68 @@ |
|||||
|
package com.aeon.tcp.f10; |
||||
|
|
||||
|
import com.aeon.tcp.f10.hander.TcpMessageHandler; |
||||
|
import io.netty.bootstrap.ServerBootstrap; |
||||
|
import io.netty.channel.ChannelFuture; |
||||
|
import io.netty.channel.ChannelInitializer; |
||||
|
import io.netty.channel.EventLoopGroup; |
||||
|
import io.netty.channel.nio.NioEventLoopGroup; |
||||
|
import io.netty.channel.socket.SocketChannel; |
||||
|
import io.netty.channel.socket.nio.NioServerSocketChannel; |
||||
|
import jakarta.annotation.PostConstruct; |
||||
|
import jakarta.annotation.PreDestroy; |
||||
|
import jakarta.annotation.Resource; |
||||
|
import org.slf4j.Logger; |
||||
|
import org.slf4j.LoggerFactory; |
||||
|
import org.springframework.beans.factory.annotation.Value; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
|
||||
|
@Component |
||||
|
public class NettyTcpServer { |
||||
|
|
||||
|
private static final Logger logger = LoggerFactory.getLogger(NettyTcpServer.class); |
||||
|
|
||||
|
@Value("${gateway.tcp.port}") |
||||
|
private int port; |
||||
|
|
||||
|
@Resource |
||||
|
private TcpMessageHandler tcpMessageHandler; |
||||
|
|
||||
|
private EventLoopGroup bossGroup; |
||||
|
private EventLoopGroup workerGroup; |
||||
|
|
||||
|
@PostConstruct |
||||
|
public void start() { |
||||
|
new Thread(() -> { |
||||
|
try { |
||||
|
bossGroup = new NioEventLoopGroup(1); |
||||
|
workerGroup = new NioEventLoopGroup(); |
||||
|
|
||||
|
ServerBootstrap b = new ServerBootstrap(); |
||||
|
b.group(bossGroup, workerGroup) |
||||
|
.channel(NioServerSocketChannel.class) |
||||
|
.childHandler(new ChannelInitializer<SocketChannel>() { |
||||
|
@Override |
||||
|
protected void initChannel(SocketChannel ch) { |
||||
|
ch.pipeline() |
||||
|
.addLast(new StxEtxFrameDecoder()) |
||||
|
.addLast(tcpMessageHandler); |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
ChannelFuture f = b.bind(port).sync(); |
||||
|
logger.info("Netty TCP Server started on port {}", port); |
||||
|
f.channel().closeFuture().sync(); |
||||
|
} catch (InterruptedException e) { |
||||
|
Thread.currentThread().interrupt(); |
||||
|
} |
||||
|
}, "netty-server-thread").start(); |
||||
|
} |
||||
|
|
||||
|
@PreDestroy |
||||
|
public void shutdown() { |
||||
|
if (bossGroup != null) bossGroup.shutdownGracefully(); |
||||
|
if (workerGroup != null) workerGroup.shutdownGracefully(); |
||||
|
logger.info("Netty TCP Server stopped....."); |
||||
|
} |
||||
|
} |
||||
|
|
||||
@ -0,0 +1,46 @@ |
|||||
|
package com.aeon.tcp.f10; |
||||
|
|
||||
|
import io.netty.buffer.ByteBuf; |
||||
|
import io.netty.channel.ChannelHandlerContext; |
||||
|
import io.netty.handler.codec.ByteToMessageDecoder; |
||||
|
|
||||
|
import java.util.List; |
||||
|
|
||||
|
public class StxEtxFrameDecoder extends ByteToMessageDecoder { |
||||
|
|
||||
|
public static final byte STX = 0x02; |
||||
|
public static final byte ETX = 0x03; |
||||
|
private static final int MAX_FRAME_LENGTH = 1024; |
||||
|
|
||||
|
@Override |
||||
|
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { |
||||
|
while (true) { |
||||
|
int readable = in.readableBytes(); |
||||
|
if (readable < 2) { |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
int stxIndex = in.indexOf(in.readerIndex(), in.writerIndex(), STX); |
||||
|
if (stxIndex < 0) { |
||||
|
in.skipBytes(readable); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
int etxIndex = in.indexOf(stxIndex + 1, in.writerIndex(), ETX); |
||||
|
if (etxIndex < 0) { |
||||
|
if (in.writerIndex() - stxIndex > MAX_FRAME_LENGTH) { |
||||
|
ctx.close(); |
||||
|
} |
||||
|
in.readerIndex(stxIndex); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
int frameLength = etxIndex - stxIndex + 1; |
||||
|
ByteBuf frame = in.retainedSlice(stxIndex, frameLength); |
||||
|
in.readerIndex(etxIndex + 1); |
||||
|
|
||||
|
out.add(frame); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
@ -0,0 +1,33 @@ |
|||||
|
package com.aeon.tcp.f10.config; |
||||
|
|
||||
|
import lombok.Data; |
||||
|
|
||||
|
/** |
||||
|
* 网关服务器配置类 |
||||
|
*/ |
||||
|
@Data |
||||
|
public class GatewayProperties { |
||||
|
|
||||
|
// 数据格式配置
|
||||
|
public static char stx = 0x02; // STX字符
|
||||
|
public static char etx = 0x03; // ETX字符
|
||||
|
public static int sequenceLength = 4; // 序列号长度
|
||||
|
public static int modeLength = 2; // 模式标识长度
|
||||
|
public static int stxEtxLength = 1; |
||||
|
|
||||
|
// 启动的序列号
|
||||
|
public static String startSequence = "0000"; |
||||
|
|
||||
|
// 模式标识常量
|
||||
|
public static String modeUnsent = "02"; // 未发送数据模式
|
||||
|
public static String modeSystemStart = "01"; // 系统开始指示模式
|
||||
|
|
||||
|
// 响应标识常量
|
||||
|
public static String responseMode = "00"; |
||||
|
public static String responseOk = "00"; // 肯定响应
|
||||
|
public static String responseNg = "11"; // 否定响应
|
||||
|
|
||||
|
public static final int MIN_SEQUENCE = 0; |
||||
|
public static final int MAX_SEQUENCE = 9999; |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,110 @@ |
|||||
|
package com.aeon.tcp.f10.hander; |
||||
|
|
||||
|
import com.aeon.tcp.f10.config.GatewayProperties; |
||||
|
import io.netty.buffer.ByteBuf; |
||||
|
import io.netty.channel.ChannelFutureListener; |
||||
|
import io.netty.channel.ChannelHandlerContext; |
||||
|
import org.slf4j.Logger; |
||||
|
import org.slf4j.LoggerFactory; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
|
||||
|
import java.nio.charset.StandardCharsets; |
||||
|
|
||||
|
/** |
||||
|
* 客户端处理器类 |
||||
|
* 负责处理单个网关客户端的连接和通信 |
||||
|
*/ |
||||
|
@Component |
||||
|
public class ClientHandler { |
||||
|
|
||||
|
private static final Logger logger = LoggerFactory.getLogger(ClientHandler.class); |
||||
|
|
||||
|
private final MessageHandler messageHandler; |
||||
|
|
||||
|
public ClientHandler(MessageHandler messageHandler) { |
||||
|
this.messageHandler = messageHandler; |
||||
|
} |
||||
|
|
||||
|
|
||||
|
public void handle(String message, ChannelHandlerContext ctx, ByteBuf msg) { |
||||
|
try { |
||||
|
// 解析消息
|
||||
|
MessageHandler.Message parsedMessage = messageHandler.parseMessage(message); |
||||
|
logger.info("消息模式: {}", parsedMessage.getMode()); |
||||
|
|
||||
|
// 检查序列号是否有效
|
||||
|
MessageHandler.SequenceJudgement sequenceJudgement = messageHandler.isValidSequence(ctx, parsedMessage.getSequence()); |
||||
|
|
||||
|
// 检查是否是通信异常(包括重发5次序列号)
|
||||
|
if (!sequenceJudgement.isValid()) { |
||||
|
// 1.当接收到与前次数据序列号相同的信号时,接收端系统将直接返回“确认响应”而不进行处理.这是因为系统会将已接收的数据视为重复传输的信号
|
||||
|
// 2.若连续5次出现重复传输,接收端系统将判定为“通信异常”并停止发送响应。此后系统将切换至“系统启动指令”数据接收待机状态。(虽然这种情况通常不会在迁移过程中发生,但作为发送系统异常时的防失控处理措施)当发送端系统被判定为无响应状态,且在重发5次后仍未收到响应时,系统将判定通信异常。此时会关闭连接套接字,重新建立连接后,系统将切换至“系统启动指令”数据传输模式。
|
||||
|
if (sequenceJudgement.isDuplicate()) { |
||||
|
logger.info("客户端[{}]收到重复消息,序列号: {}", ctx.channel().remoteAddress(), parsedMessage.getSequence()); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
logger.error("客户端[{}]通信异常", ctx.channel().remoteAddress()); |
||||
|
String response = messageHandler.createErrorMessage(parsedMessage.getSequence()); |
||||
|
sendMessage(ctx, response); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
// 仅是不足重发5次序列号处理:不处理数据,但返回肯定响应
|
||||
|
if (sequenceJudgement.isDuplicate()) { |
||||
|
logger.info("客户端[{}]收到重复消息,序列号: {}", ctx.channel().remoteAddress(), parsedMessage.getSequence()); |
||||
|
String response = messageHandler.formatResponse(parsedMessage.getSequence(), GatewayProperties.responseOk); |
||||
|
sendMessage(ctx, response); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
// 正常消息处理:根据消息模式进行处理
|
||||
|
String response; |
||||
|
if (GatewayProperties.modeSystemStart.equals(parsedMessage.getMode())) { |
||||
|
// 处理系统开始指示
|
||||
|
response = messageHandler.handleSystemStartMessage(parsedMessage, ctx); |
||||
|
} else if (GatewayProperties.modeUnsent.equals(parsedMessage.getMode())) { |
||||
|
// 处理未发送数据
|
||||
|
response = messageHandler.handleUnsentDataMessage(parsedMessage, ctx); |
||||
|
} else { |
||||
|
// 处理其他数据
|
||||
|
response = messageHandler.handleOtherDataMessage(parsedMessage, ctx); |
||||
|
} |
||||
|
|
||||
|
// 发送响应
|
||||
|
if (response != null) { |
||||
|
sendMessage(ctx, response); |
||||
|
} |
||||
|
|
||||
|
} catch (Exception e) { |
||||
|
logger.error("处理客户端[{}]消息时发生错误", ctx.channel().remoteAddress(), e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private void sendMessage(ChannelHandlerContext ctx, String response) { |
||||
|
ByteBuf down = buildDownMessage(ctx, response); |
||||
|
ctx.writeAndFlush(down).addListener((ChannelFutureListener) future -> { |
||||
|
if (future.isSuccess()) { |
||||
|
logger.info("下行发送成功,data={}, channel={}", response, ctx.channel().id()); |
||||
|
} else { |
||||
|
logger.error("下行发送失败", future.cause()); |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
} |
||||
|
|
||||
|
public static ByteBuf buildDownMessage( |
||||
|
ChannelHandlerContext ctx, |
||||
|
String payload |
||||
|
) { |
||||
|
byte[] body = payload.getBytes(StandardCharsets.US_ASCII); |
||||
|
|
||||
|
ByteBuf buf = ctx.alloc().buffer(body.length); |
||||
|
buf.writeBytes(body);// 数据
|
||||
|
return buf; |
||||
|
} |
||||
|
|
||||
|
public void nettyClose(ChannelHandlerContext ctx) { |
||||
|
ctx.close(); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,255 @@ |
|||||
|
package com.aeon.tcp.f10.hander; |
||||
|
|
||||
|
import com.aeon.tcp.f10.config.GatewayProperties; |
||||
|
import io.netty.channel.ChannelHandlerContext; |
||||
|
import org.slf4j.Logger; |
||||
|
import org.slf4j.LoggerFactory; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
|
||||
|
/** |
||||
|
* 消息处理器类 |
||||
|
* 负责处理网关消息的解析、验证和响应生成 |
||||
|
*/ |
||||
|
@Component |
||||
|
public class MessageHandler { |
||||
|
|
||||
|
private static final Logger logger = LoggerFactory.getLogger(MessageHandler.class); |
||||
|
|
||||
|
/** |
||||
|
* 消息内部类 |
||||
|
*/ |
||||
|
public static class Message { |
||||
|
private String sequence; |
||||
|
private String mode; |
||||
|
private String data; |
||||
|
|
||||
|
public String getSequence() { |
||||
|
return sequence; |
||||
|
} |
||||
|
|
||||
|
public void setSequence(String sequence) { |
||||
|
this.sequence = sequence; |
||||
|
} |
||||
|
|
||||
|
public String getMode() { |
||||
|
return mode; |
||||
|
} |
||||
|
|
||||
|
public void setMode(String mode) { |
||||
|
this.mode = mode; |
||||
|
} |
||||
|
|
||||
|
public String getData() { |
||||
|
return data; |
||||
|
} |
||||
|
|
||||
|
public void setData(String data) { |
||||
|
this.data = data; |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public String toString() { |
||||
|
return "Message{" + |
||||
|
"sequence='" + sequence + '\'' + |
||||
|
", mode='" + mode + '\'' + |
||||
|
", data='" + data + '\'' + |
||||
|
'}'; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
public static class SequenceJudgement { |
||||
|
|
||||
|
private boolean valid; |
||||
|
private boolean duplicate ; |
||||
|
|
||||
|
public boolean isValid() { |
||||
|
return valid; |
||||
|
} |
||||
|
public void setValid(boolean valid) { |
||||
|
this.valid = valid; |
||||
|
} |
||||
|
|
||||
|
public boolean isDuplicate() { |
||||
|
return duplicate; |
||||
|
} |
||||
|
public void setDuplicate(boolean duplicate) { |
||||
|
this.duplicate = duplicate; |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public String toString() { |
||||
|
return "Message{" + |
||||
|
"valid='" + valid + '\'' + |
||||
|
", duplicate='" + duplicate + '\'' + |
||||
|
'}'; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 解析接收到的消息 |
||||
|
*/ |
||||
|
public Message parseMessage(String content) { |
||||
|
// 验证内容长度
|
||||
|
if (content.length() < GatewayProperties.sequenceLength + GatewayProperties.modeLength) { |
||||
|
throw new IllegalArgumentException("消息内容长度不足"); |
||||
|
} |
||||
|
|
||||
|
// 提取序列号
|
||||
|
String sequence = content.substring(0, GatewayProperties.sequenceLength); |
||||
|
if (!sequence.matches("\\d{" + GatewayProperties.sequenceLength + "}")) { |
||||
|
throw new IllegalArgumentException("序列号必须为" + GatewayProperties.sequenceLength+ "位数字"); |
||||
|
} |
||||
|
|
||||
|
// 提取模式标识
|
||||
|
String mode = content.substring(GatewayProperties.sequenceLength, |
||||
|
GatewayProperties.sequenceLength + GatewayProperties.modeLength); |
||||
|
// if (!isValidMode(mode)) {
|
||||
|
// throw new IllegalArgumentException("无效的模式标识: " + mode);
|
||||
|
// }
|
||||
|
|
||||
|
// 提取数据部分(如果有)
|
||||
|
String data = null; |
||||
|
if (content.length() > GatewayProperties.sequenceLength + GatewayProperties.modeLength) { |
||||
|
data = content.substring(GatewayProperties.sequenceLength + GatewayProperties.modeLength); |
||||
|
} |
||||
|
|
||||
|
// 创建并返回消息对象
|
||||
|
Message message = new Message(); |
||||
|
message.setSequence(sequence); |
||||
|
message.setMode(mode); |
||||
|
message.setData(data); |
||||
|
|
||||
|
return message; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 验证模式标识是否有效 |
||||
|
* @param mode 模式标识 |
||||
|
* @return 是否有效 |
||||
|
*/ |
||||
|
private boolean isValidMode(String mode) { |
||||
|
return GatewayProperties.modeUnsent.equals(mode) || |
||||
|
GatewayProperties.modeSystemStart.equals(mode); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 创建错误响应消息 |
||||
|
* @param sequence 原始请求的序列号 |
||||
|
* @return 错误响应消息 |
||||
|
*/ |
||||
|
public String createErrorMessage(String sequence) { |
||||
|
return formatResponse(sequence, GatewayProperties.responseNg); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 格式化响应消息 |
||||
|
* @param sequence 序列号 |
||||
|
* @param responseCode 响应代码 |
||||
|
* @return 格式化后的响应消息 |
||||
|
*/ |
||||
|
public String formatResponse(String sequence, String responseCode) { |
||||
|
StringBuilder sb = new StringBuilder(); |
||||
|
|
||||
|
// 添加STX
|
||||
|
sb.append(GatewayProperties.stx); |
||||
|
|
||||
|
// 添加序列号
|
||||
|
sb.append(sequence); |
||||
|
|
||||
|
//响应模式
|
||||
|
sb.append(GatewayProperties.responseMode); |
||||
|
|
||||
|
// 添加响应代码
|
||||
|
sb.append(responseCode); |
||||
|
|
||||
|
// 添加ETX
|
||||
|
sb.append(GatewayProperties.etx); |
||||
|
|
||||
|
return sb.toString(); |
||||
|
} |
||||
|
|
||||
|
public SequenceJudgement isValidSequence( |
||||
|
ChannelHandlerContext ctx, |
||||
|
String sequence |
||||
|
) { |
||||
|
|
||||
|
SequenceState state = ctx.channel().attr(TcpMessageHandler.SEQ_STATE).get(); |
||||
|
|
||||
|
if (state == null) { |
||||
|
state = new SequenceState(); |
||||
|
ctx.channel().attr(TcpMessageHandler.SEQ_STATE).set(state); |
||||
|
} |
||||
|
|
||||
|
return state.check(sequence); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 处理系统开始指示消息 |
||||
|
* @param message 消息对象 |
||||
|
* @param ctx 客户端 |
||||
|
* @return 响应消息 |
||||
|
*/ |
||||
|
public String handleSystemStartMessage(Message message, ChannelHandlerContext ctx) { |
||||
|
logger.info("客户端[{}]发送系统开始指示,序列号: {}", ctx.channel().remoteAddress(), message.getSequence()); |
||||
|
// 创建成功响应
|
||||
|
return formatResponse(message.getSequence(), GatewayProperties.responseOk); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* 处理正常数据消息 |
||||
|
* @param message 消息对象 |
||||
|
* @param ctx 客户端 |
||||
|
* @return 响应消息 |
||||
|
*/ |
||||
|
public String handleNormalDataMessage(Message message, ChannelHandlerContext ctx) { |
||||
|
logger.info("客户端[{}]发送正常数据,序列号: {}, 数据长度: {}", |
||||
|
ctx.channel().remoteAddress(), message.getSequence(), |
||||
|
message.getData() != null ? message.getData().length() : 0); |
||||
|
try { |
||||
|
// 这里可以添加实际的数据处理逻辑
|
||||
|
// 例如:保存到数据库、转发到其他服务等
|
||||
|
|
||||
|
// 假设数据处理成功
|
||||
|
return formatResponse(message.getSequence(), GatewayProperties.responseOk); |
||||
|
} catch (Exception e) { |
||||
|
logger.error("处理客户端[{}]正常数据时发生错误", ctx.channel().remoteAddress(), e); |
||||
|
return createErrorMessage(message.getSequence()); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public String handleUnsentDataMessage(Message message, ChannelHandlerContext ctx) { |
||||
|
logger.info("客户端[{}]发送未发送数据,序列号: {}, 数据长度: {}", |
||||
|
ctx.channel().remoteAddress(), message.getSequence(), |
||||
|
message.getData() != null ? message.getData().length() : 0); |
||||
|
|
||||
|
try { |
||||
|
// 处理未发送数据(通常需要特殊处理以避免重复处理)
|
||||
|
// 例如:检查数据是否已经存在,如果不存在则处理,否则直接返回成功
|
||||
|
|
||||
|
return formatResponse(message.getSequence(), GatewayProperties.responseOk); |
||||
|
} catch (Exception e) { |
||||
|
logger.error("处理客户端[{}]未发送数据时发生错误", ctx.channel().remoteAddress(), e); |
||||
|
return createErrorMessage(message.getSequence()); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
|
||||
|
public String handleOtherDataMessage(Message message, ChannelHandlerContext ctx) { |
||||
|
logger.info("客户端[{}]发送其他数据,序列号: {}, 数据长度: {}", |
||||
|
ctx.channel().remoteAddress(), message.getSequence(), |
||||
|
message.getData() != null ? message.getData().length() : 0); |
||||
|
|
||||
|
try { |
||||
|
// 处理未发送数据(通常需要特殊处理以避免重复处理)
|
||||
|
// 例如:检查数据是否已经存在,如果不存在则处理,否则直接返回成功
|
||||
|
|
||||
|
return formatResponse(message.getSequence(), GatewayProperties.responseOk); |
||||
|
} catch (Exception e) { |
||||
|
logger.error("处理客户端[{}]未发送数据时发生错误", ctx.channel().remoteAddress(), e); |
||||
|
return createErrorMessage(message.getSequence()); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,76 @@ |
|||||
|
package com.aeon.tcp.f10.hander; |
||||
|
|
||||
|
import com.aeon.tcp.f10.config.GatewayProperties; |
||||
|
|
||||
|
public class SequenceState { |
||||
|
|
||||
|
private String lastSeq; |
||||
|
private int duplicateCount; |
||||
|
|
||||
|
|
||||
|
|
||||
|
public MessageHandler.SequenceJudgement check(String sequence) { |
||||
|
MessageHandler.SequenceJudgement result = new MessageHandler.SequenceJudgement(); |
||||
|
result.setValid(true); |
||||
|
result.setDuplicate(false); |
||||
|
|
||||
|
//系统启动指令直接通过
|
||||
|
if (GatewayProperties.startSequence.equals(sequence)){ |
||||
|
return result; |
||||
|
} |
||||
|
|
||||
|
// 第一次上报
|
||||
|
if (lastSeq == null) { |
||||
|
lastSeq = sequence; |
||||
|
duplicateCount = 0; |
||||
|
return result; |
||||
|
} |
||||
|
|
||||
|
// 重复序号
|
||||
|
if (lastSeq.equals(sequence)) { |
||||
|
duplicateCount++; |
||||
|
result.setDuplicate(true); |
||||
|
|
||||
|
if (duplicateCount >= 5) { |
||||
|
result.setValid(false); |
||||
|
} |
||||
|
return result; |
||||
|
} |
||||
|
|
||||
|
// 校验递增 / 循环
|
||||
|
boolean valid = isSequenceValid(lastSeq, sequence); |
||||
|
result.setValid(valid); |
||||
|
|
||||
|
if (valid) { |
||||
|
lastSeq = sequence; |
||||
|
duplicateCount = 0; |
||||
|
} |
||||
|
|
||||
|
return result; |
||||
|
} |
||||
|
|
||||
|
public boolean isSequenceValid(String lastSequence, String newSequence) { |
||||
|
try { |
||||
|
// 将序列号转换为整数
|
||||
|
int last = Integer.parseInt(lastSequence); |
||||
|
int current = Integer.parseInt(newSequence); |
||||
|
|
||||
|
// 正常情况:序列号递增1
|
||||
|
if (current == last + 1) { |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
// 循环情况:序列号从9999变为0000
|
||||
|
if (last == GatewayProperties.MAX_SEQUENCE && current == GatewayProperties.MIN_SEQUENCE) { |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
// 其他情况(包括跳号、重复等)都视为无效
|
||||
|
return false; |
||||
|
} catch (NumberFormatException e) { |
||||
|
// 序列号不是有效的数字
|
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
@ -0,0 +1,75 @@ |
|||||
|
package com.aeon.tcp.f10.hander; |
||||
|
|
||||
|
import io.netty.buffer.ByteBuf; |
||||
|
import io.netty.channel.ChannelHandler; |
||||
|
import io.netty.channel.ChannelHandlerContext; |
||||
|
import io.netty.channel.SimpleChannelInboundHandler; |
||||
|
import io.netty.util.AttributeKey; |
||||
|
import org.slf4j.Logger; |
||||
|
import org.slf4j.LoggerFactory; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
|
||||
|
import java.nio.charset.StandardCharsets; |
||||
|
import java.util.Arrays; |
||||
|
|
||||
|
@Component |
||||
|
@ChannelHandler.Sharable |
||||
|
public class TcpMessageHandler extends SimpleChannelInboundHandler<ByteBuf> { |
||||
|
|
||||
|
private static final Logger logger = LoggerFactory.getLogger(TcpMessageHandler.class); |
||||
|
|
||||
|
public static final AttributeKey<SequenceState> SEQ_STATE = |
||||
|
AttributeKey.valueOf("sequence_state"); |
||||
|
|
||||
|
|
||||
|
private final ClientHandler clientHandler; |
||||
|
|
||||
|
public TcpMessageHandler(ClientHandler clientHandler) { |
||||
|
this.clientHandler = clientHandler; |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@Override |
||||
|
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { |
||||
|
byte[] bytes = new byte[msg.readableBytes()]; |
||||
|
msg.readBytes(bytes); |
||||
|
|
||||
|
logger.info("收到消息 HEX: {}", bytesToHex(bytes)); |
||||
|
|
||||
|
// 去掉 STX / ETX
|
||||
|
byte[] payload = Arrays.copyOfRange(bytes, 1, bytes.length - 1); |
||||
|
String content = new String(payload, StandardCharsets.US_ASCII); |
||||
|
|
||||
|
logger.info("收到消息正文内容: [{}]", content); |
||||
|
|
||||
|
// TODO 业务处理
|
||||
|
clientHandler.handle(content, ctx, msg); |
||||
|
|
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void channelActive(ChannelHandlerContext ctx) { |
||||
|
ctx.channel().attr(SEQ_STATE).set(new SequenceState()); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@Override |
||||
|
public void channelInactive(ChannelHandlerContext ctx) { |
||||
|
logger.info("客户端断开: {}", ctx.channel().remoteAddress()); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { |
||||
|
logger.error("连接异常", cause); |
||||
|
ctx.close(); |
||||
|
} |
||||
|
|
||||
|
private String bytesToHex(byte[] bytes) { |
||||
|
StringBuilder sb = new StringBuilder(); |
||||
|
for (byte b : bytes) { |
||||
|
sb.append(String.format("%02X ", b)); |
||||
|
} |
||||
|
return sb.toString().trim(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
@ -0,0 +1,4 @@ |
|||||
|
spring.application.name=aeon_tcp |
||||
|
server.port=30004 |
||||
|
|
||||
|
gateway.tcp.port = 18084 |
||||
@ -0,0 +1,13 @@ |
|||||
|
package com.aeon.tcp; |
||||
|
|
||||
|
import org.junit.jupiter.api.Test; |
||||
|
import org.springframework.boot.test.context.SpringBootTest; |
||||
|
|
||||
|
@SpringBootTest |
||||
|
class TcpApplicationTests { |
||||
|
|
||||
|
@Test |
||||
|
void contextLoads() { |
||||
|
} |
||||
|
|
||||
|
} |
||||
Loading…
Reference in new issue