commit 750570fdf2a211bf32e4c53618cc4ff3ce6eef58 Author: NiuZiYuan Date: Thu Apr 17 09:30:19 2025 +0800 dev diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..d58dfb7 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# 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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/dbhelper.bat b/dbhelper.bat new file mode 100644 index 0000000..a04e9ec --- /dev/null +++ b/dbhelper.bat @@ -0,0 +1 @@ +java -jar dbhelper.jar %* \ No newline at end of file diff --git a/dbhelper.jar b/dbhelper.jar new file mode 100644 index 0000000..e4be32b Binary files /dev/null and b/dbhelper.jar differ diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..19529dd --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/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.2 +# +# 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:]' +} + +# 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 <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.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${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..249bdf3 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : 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.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/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_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::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 +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..cffd89f --- /dev/null +++ b/pom.xml @@ -0,0 +1,117 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.4 + + + com.syjiaer.pharmacy.proxy + server + 0.0.1-SNAPSHOT + server + server + + + + + + + + + + + + + + + 17 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-aop + + + + com.baomidou + mybatis-plus-spring-boot3-starter + 3.5.10.1 + + + com.baomidou + mybatis-plus-jsqlparser + 3.5.10.1 + + + org.postgresql + postgresql + runtime + + + + io.jsonwebtoken + jjwt-api + 0.12.3 + + + io.jsonwebtoken + jjwt-impl + 0.12.3 + runtime + + + io.jsonwebtoken + jjwt-jackson + 0.12.3 + runtime + + + + + + org.projectlombok + lombok + 1.18.32 + provided + + + com.alibaba + fastjson + 2.0.38 + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/com/syjiaer/pharmacy/server/ServerApplication.java b/src/main/java/com/syjiaer/pharmacy/server/ServerApplication.java new file mode 100644 index 0000000..263cb4e --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/ServerApplication.java @@ -0,0 +1,15 @@ +package com.syjiaer.pharmacy.server; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@MapperScan("com.syjiaer.pharmacy.server.modules.*.mapper") +public class ServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ServerApplication.class, args); + } + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/config/Config.java b/src/main/java/com/syjiaer/pharmacy/server/common/config/Config.java new file mode 100644 index 0000000..8784c37 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/config/Config.java @@ -0,0 +1,35 @@ +package com.syjiaer.pharmacy.server.common.config; + +import com.syjiaer.pharmacy.server.modules.base.entity.CommonConfig; +import com.syjiaer.pharmacy.server.modules.base.service.ICommonConfigService; +import jakarta.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Component +public class Config { + private Map config_map; + @Autowired + private ICommonConfigService iCommonConfigService; + + @PostConstruct + private void init() { + config_map = new HashMap<>(); + List list = iCommonConfigService.list(); + for (CommonConfig commonConfig : list) { + config_map.put(commonConfig.getK(), commonConfig.getVal()); + } + } + + public String get(String group, String key) { + return config_map.get(group + "_" + key); + } + + public Map list() { + return config_map; + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/config/ControllerAspect.java b/src/main/java/com/syjiaer/pharmacy/server/common/config/ControllerAspect.java new file mode 100644 index 0000000..a65fac6 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/config/ControllerAspect.java @@ -0,0 +1,39 @@ +package com.syjiaer.pharmacy.server.common.config; + +import com.syjiaer.pharmacy.server.common.exception.MessageException; +import com.syjiaer.pharmacy.server.common.exception.VerifyException; +import com.syjiaer.pharmacy.server.common.vo.Result; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.stereotype.Component; + +@Component // 将当前类交给spring管理 +@Aspect // 声明这是一个AOP类 +public class ControllerAspect { + @Pointcut("execution(public * *(..)) && within(com.syjiaer.pharmacy.server.modules.*.controller.*+) && within(com.syjiaer.pharmacy.server.modules.base.controller.BaseController+)") + public void controllerPointcut() { + } + + @Around("controllerPointcut()") + public Object messageExceptionAop(ProceedingJoinPoint joinPoint) throws Throwable { + try { + Object result = joinPoint.proceed(); + return result; + } catch (MessageException e) { + Result result = new Result(); + result.setMessage(e.getMessage()); + result.setData(null); + result.setCode(101); + return result; + } catch (VerifyException e) { + Result result = new Result(); + result.setMessage(e.getMessage()); + result.setData(null); + result.setCode(301); + return result; + } + + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/config/CorsConfig.java b/src/main/java/com/syjiaer/pharmacy/server/common/config/CorsConfig.java new file mode 100644 index 0000000..31c5d52 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/config/CorsConfig.java @@ -0,0 +1,32 @@ +package com.syjiaer.pharmacy.server.common.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +@Configuration +public class CorsConfig { + + @Bean + public CorsFilter corsFilter() { + // 1. 添加 CORS 配置信息 + CorsConfiguration config = new CorsConfiguration(); + // 允许的域名,可使用 * 表示允许所有域名 + config.addAllowedOriginPattern("*"); + // 允许的请求头 + config.addAllowedHeader("*"); + // 允许的请求方法 + config.addAllowedMethod("*"); + // 允许携带凭证(如 cookie) + config.setAllowCredentials(true); + + // 2. 为 URL 路径添加 CORS 配置 + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", config); + + // 3. 返回 CorsFilter 实例 + return new CorsFilter(source); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/config/SpringMvcConfig.java b/src/main/java/com/syjiaer/pharmacy/server/common/config/SpringMvcConfig.java new file mode 100644 index 0000000..a004bed --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/config/SpringMvcConfig.java @@ -0,0 +1,16 @@ +package com.syjiaer.pharmacy.server.common.config; + +import com.syjiaer.pharmacy.server.common.inteceptor.MvcInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class SpringMvcConfig implements WebMvcConfigurer { + @Autowired + private MvcInterceptor mvcInterceptor; + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(mvcInterceptor).addPathPatterns("/**"); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/constants/Constants.java b/src/main/java/com/syjiaer/pharmacy/server/common/constants/Constants.java new file mode 100644 index 0000000..bd74934 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/constants/Constants.java @@ -0,0 +1,18 @@ +package com.syjiaer.pharmacy.server.common.constants; + +public class Constants { + public static final String IPurchaseCodePrefix = "IP"; + public static final String IInitCodePrefix = "II"; + public static final String RetailFeedetlSn = "FFLS"; + public static final Integer DetailPageSize = 20; + + public static final String InitInventory = "初始化库存"; + public static final String PurchaseInventory = "采购入库"; + public static final String Sold = "售出"; + public static final String Apply = "领用"; + public static final String Social = "医保"; + + public static final Integer numberWarningLimit = 10; + public static final Integer expiryDateWarningLimit = 20; + public static final Integer OneDaySecond= 24*60*60; +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/exception/MessageException.java b/src/main/java/com/syjiaer/pharmacy/server/common/exception/MessageException.java new file mode 100644 index 0000000..1873677 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/exception/MessageException.java @@ -0,0 +1,39 @@ +package com.syjiaer.pharmacy.server.common.exception; + +public class MessageException extends RuntimeException { + /** + * 无参构造方法 + */ + public MessageException() { + super(); + } + + /** + * 带有错误信息的构造方法 + * + * @param message 错误信息 + */ + public MessageException(String message) { + super(message); + } + + /** + * 带有错误信息和原始异常的构造方法 + * + * @param message 错误信息 + * @param cause 原始异常 + */ + public MessageException(String message, Throwable cause) { + super(message, cause); + } + + /** + * 带有原始异常的构造方法 + * + * @param cause 原始异常 + */ + public MessageException(Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/exception/VerifyException.java b/src/main/java/com/syjiaer/pharmacy/server/common/exception/VerifyException.java new file mode 100644 index 0000000..0135f59 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/exception/VerifyException.java @@ -0,0 +1,39 @@ +package com.syjiaer.pharmacy.server.common.exception; + +public class VerifyException extends RuntimeException { + /** + * 无参构造方法 + */ + public VerifyException() { + super(); + } + + /** + * 带有错误信息的构造方法 + * + * @param message 错误信息 + */ + public VerifyException(String message) { + super(message); + } + + /** + * 带有错误信息和原始异常的构造方法 + * + * @param message 错误信息 + * @param cause 原始异常 + */ + public VerifyException(String message, Throwable cause) { + super(message, cause); + } + + /** + * 带有原始异常的构造方法 + * + * @param cause 原始异常 + */ + public VerifyException(Throwable cause) { + super(cause); + } + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/inteceptor/MvcInterceptor.java b/src/main/java/com/syjiaer/pharmacy/server/common/inteceptor/MvcInterceptor.java new file mode 100644 index 0000000..f36a5ff --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/inteceptor/MvcInterceptor.java @@ -0,0 +1,136 @@ +package com.syjiaer.pharmacy.server.common.inteceptor; + +import com.alibaba.fastjson2.JSON; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.syjiaer.pharmacy.server.common.util.HeadersUtil; +import com.syjiaer.pharmacy.server.common.util.InfoUtil; +import com.syjiaer.pharmacy.server.common.util.ParmsUtil; +import com.syjiaer.pharmacy.server.common.vo.Result; +import com.syjiaer.pharmacy.server.modules.base.entity.ManagerUser; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +@Component +public class MvcInterceptor implements HandlerInterceptor { + private final ObjectMapper objectMapper = new ObjectMapper(); + @Value("${jwt.secret}") + protected String jwtSecret; + @Autowired + private ParmsUtil parmsUtil; + + @Autowired + private HeadersUtil headersUtil; + @Autowired + private InfoUtil infoUtil; + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + setParms(request); + setHeaders(request); + + // 排除 /user/login 接口的校验 + if (!request.getRequestURI().endsWith("/manager/user/login")) { + return checkManage(response); + } + + return true; + } + private Boolean checkManage(HttpServletResponse response) throws IOException { + Map headers =headersUtil.getMap(); + String token = headers.get("authorization"); + if (token == null || token.isEmpty()) { + setErrorResult(response,"登陆令牌不存在,请重新登陆",301); + return false; + } + Jws claimsJws = null; + try { + claimsJws = Jwts.parser() + .verifyWith(Keys.hmacShaKeyFor(jwtSecret.getBytes())) + .build() + .parseSignedClaims(token); + } catch (JwtException e) { + setErrorResult(response,"登录令牌已失效,请重新登陆",301); + return false; + } catch (Exception e) { + setErrorResult(response,"登录令牌已失效,请重新登陆",301); + return false; + } + + if (claimsJws == null) { + setErrorResult(response,"登录令牌已失效,请重新登陆",301); + return false; + } + Claims claims = claimsJws.getPayload(); + ManagerUser managerUser = new ManagerUser(); + managerUser.setId(Integer.parseInt(claims.getSubject())); + managerUser.setUsername(claims.get("username", String.class)); + managerUser.setName(claims.get("name", String.class)); + return true; + } + + private void setHeaders(HttpServletRequest request){ + Map headers = new HashMap<>(); + Enumeration headerNames = request.getHeaderNames(); + if (headerNames != null) { + while (headerNames.hasMoreElements()) { + String key = headerNames.nextElement(); + String value = request.getHeader(key); + headers.put(key, value); + } + } + headersUtil.setMap(headers); + + } + private void setParms(HttpServletRequest request) { + Map map=null; + try { + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream())); + String line; + while ((line = bufferedReader.readLine()) != null) { + stringBuilder.append(line); + } + String input_str = stringBuilder.toString(); + map = JSON.parseObject(input_str, Map.class); + } catch (Exception e) { + map=new HashMap(); + } + if(map==null){ + map=new HashMap(); + } + parmsUtil.setMap(map); + + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + parmsUtil.remove(); + headersUtil.remove(); + } + private void setErrorResult(HttpServletResponse response, String msg,int code) throws IOException { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + Result result = new Result(); + result.setCode(code); + result.setMessage(msg); + response.getWriter().write(objectMapper.writeValueAsString(result)); + } + + private void setErrorResult(HttpServletResponse response, String msg) throws IOException { + setErrorResult(response, msg,101); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/DateUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/DateUtil.java new file mode 100644 index 0000000..46f7f1c --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/DateUtil.java @@ -0,0 +1,66 @@ +package com.syjiaer.pharmacy.server.common.util; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +public class DateUtil { + public static final String DATE_FORMAT = "yyyy-MM-dd"; + public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + public LocalDateTime now() { + return LocalDateTime.now(); + } + + public static String getDateStr(LocalDateTime dateTime) { + return dateTime.format(DateTimeFormatter.ofPattern(DATE_FORMAT)); + } + + public static String getDateTimeStr(LocalDateTime dateTime) { + return dateTime.format(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)); + } + + public static LocalDateTime getDate(String dateStr) { + return LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern(DATE_FORMAT)); + } + + public static LocalDateTime getDateTime(String dateTimeStr) { + //如果传入dateStr + if (dateTimeStr.length() == 10) { + dateTimeStr = dateTimeStr + " 00:00:00"; + } + return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)); + } + + //加一天 + public static LocalDateTime addDay(LocalDateTime dateTime) { + return dateTime.plusDays(1); + } + + public static LocalDateTime addDay(LocalDateTime dateTime, int day) { + return dateTime.plusDays(day); + } + + //减一天 + public static LocalDateTime subDay(LocalDateTime dateTime) { + return dateTime.minusDays(1); + } + + public static LocalDateTime subDay(LocalDateTime dateTime, int day) { + return dateTime.minusDays(day); + } + + // 新增方法:获取两个日期之间所有的日期 + public static List getDatesBetween(LocalDateTime startDateTime, LocalDateTime endDateTime) { + List dates = new ArrayList<>(); + LocalDate startDate = startDateTime.toLocalDate(); + LocalDate endDate = endDateTime.toLocalDate(); + while (!startDate.isAfter(endDate)) { + dates.add(startDate); + startDate = startDate.plusDays(1); + } + return dates; + } +} \ No newline at end of file diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/DictoryUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/DictoryUtil.java new file mode 100644 index 0000000..74e149c --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/DictoryUtil.java @@ -0,0 +1,76 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; +import org.springframework.stereotype.Component; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +@Component +public class DictoryUtil { + private Logger logger = Logger.getLogger(this.getClass().getName()); + + public List getColumnList(int type) { + List result_list = new ArrayList(); + JSONArray list = FileToJsonList(String.valueOf(type)); + for (int i = 0; i < list.size(); i++) { + JSONObject obj = list.getJSONObject(i); + String key = null; + for (String _key : obj.keySet()) { + key = _key; + } + JSONObject field_obj = obj.getJSONObject(key); + + if (field_obj.containsKey("column_width") && field_obj.getInteger("column_width") != 0) { + logger.info(field_obj + ""); + result_list.add(field_obj); + + } + } + return result_list; + } + + public Map getTitleMap(String no) { + JSONArray list = FileToJsonList(no); + Map map = new HashMap(); + for (int i = 0; i < list.size(); i++) { + JSONObject obj = list.getJSONObject(i); + for (String key : obj.keySet()) { + map.put(key, obj.getJSONObject(key).getString("en")); + } + } + return map; + } + + private JSONArray FileToJsonList(String no) { + List titleList = new ArrayList<>(); + ClassLoader classLoader = getClass().getClassLoader(); + // 资源文件的路径 + String resourceName = "doc_title/" + no + ".json"; + StringBuilder content = new StringBuilder(); + try (InputStream inputStream = classLoader.getResourceAsStream(resourceName); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + if (inputStream != null) { + String line; + while ((line = reader.readLine()) != null) { + content.append(line); + } + } else { + logger.info("未找到资源文件: " + resourceName); + } + } catch (IOException e) { + e.printStackTrace(); + } + JSONArray list = JSON.parseArray(content.toString()); + return list; + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1312.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1312.java new file mode 100644 index 0000000..53a59cd --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1312.java @@ -0,0 +1,151 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.alibaba.fastjson.JSONObject; +import com.syjiaer.pharmacy.server.modules.social.api.input.IM1312; +import com.syjiaer.pharmacy.server.modules.social.api.output.OM1312; +import com.syjiaer.pharmacy.server.modules.social.api.request.SocialRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +@Component +public class Download1312 { + @Autowired + private SocialRequest socialRequest; + private Instant startTime; + private int totalPages = 3575; + private AtomicInteger processedPages = new AtomicInteger(0); // 使用 AtomicInteger + + public void download() throws InterruptedException { + startTime = Instant.now(); + + // 创建一个队列来存储页码 + ConcurrentLinkedQueue pageQueue = new ConcurrentLinkedQueue<>(); + for (int i = 1; i <= totalPages; i++) { + pageQueue.add(i); + } + + // 创建并启动4个线程 + Thread[] threads = new Thread[8]; + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread(new PageProcessor(pageQueue)); + threads[i].start(); + } + + // 等待所有线程完成 + for (Thread thread : threads) { + thread.join(); + } + + System.out.println("所有页面处理完成"); + } + + private void processPage(int page) { + File file = new File("D:/1312/" + page + ".json"); + if (file.exists()) { +// System.out.println("第" + page + "页文件已存在,跳过处理"); + return; + } + IM1312 im1312 = new IM1312(); + System.out.println("正在处理第" + page + "页"); + String dateTimeString = "2020-01-01 00:00:00"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + im1312.setUpdtTime(LocalDateTime.parse(dateTimeString, formatter)); + im1312.setValiFlag("1"); + im1312.setPageNum(page); + im1312.setPageSize(1000); + OM1312 om1312 = socialRequest.call1312(im1312); + System.out.println(page + "/" + om1312.getPages()); + List> data = om1312.getData(); + saveDataToFile(data, "D:/1312/" + page + ".json"); + processedPages.incrementAndGet(); // 增加已处理的页面数 + printEstimatedRemainingTime(); // 打印剩余时间估计 + } + + private void printEstimatedRemainingTime() { + Instant now = Instant.now(); + Duration elapsedTime = Duration.between(startTime, now); + int currentProcessedPages = processedPages.get(); // 使用 get 方法获取当前处理的页面数 + if (currentProcessedPages == 0) { + return; // 避免除以零 + } + double averageTimePerPage = elapsedTime.toMillis() / (double) currentProcessedPages; + int remainingPages = totalPages - currentProcessedPages; + long estimatedRemainingTimeInMillis = (long) (averageTimePerPage * remainingPages); + Duration estimatedRemainingTime = Duration.ofMillis(estimatedRemainingTimeInMillis); + + System.out.println("Estimated remaining time: " + estimatedRemainingTime.toHoursPart() + " hours, " + + estimatedRemainingTime.toMinutesPart() + " minutes, " + + estimatedRemainingTime.getSeconds() + " seconds"); + } + + private void saveDataToFile(List> data, String filePath) { + try { + if (data == null || data.isEmpty()) { + return; + } + + // 将 data 转换为 JSON 字符串 + String jsonString = JSONObject.toJSONString(data); + + // 创建文件夹(如果不存在) + File folder = new File("D:/1312"); + if (!folder.exists()) { + folder.mkdirs(); + } + + // 写入文件 + File file = new File(filePath); + if (file.exists()) { + file.delete(); + } + + try (FileWriter writer = new FileWriter(file)) { + writer.write(jsonString); + } + + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Failed to save data to file", e); + } + } + + // 定义一个内部类来处理页码 + private class PageProcessor implements Runnable { + private final ConcurrentLinkedQueue pageQueue; + + public PageProcessor(ConcurrentLinkedQueue pageQueue) { + this.pageQueue = pageQueue; + } + + @Override + public void run() { + while (true) { + Integer page = pageQueue.poll(); + if (page == null) { + // 队列为空,退出循环 + break; + } + try{ + processPage(page); + }catch (Exception e){ + System.out.println("第"+page+"页出错"); + e.printStackTrace(); + } + + + } + } + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1318.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1318.java new file mode 100644 index 0000000..0157c28 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1318.java @@ -0,0 +1,151 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.alibaba.fastjson.JSONObject; +import com.syjiaer.pharmacy.server.modules.social.api.input.IM1318; +import com.syjiaer.pharmacy.server.modules.social.api.output.OM1318; +import com.syjiaer.pharmacy.server.modules.social.api.request.SocialRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +@Component +public class Download1318 { + @Autowired + private SocialRequest socialRequest; + private Instant startTime; + private int totalPages = 1719; + private AtomicInteger processedPages = new AtomicInteger(0); // 使用 AtomicInteger + + public void download() throws InterruptedException { + startTime = Instant.now(); + + // 创建一个队列来存储页码 + ConcurrentLinkedQueue pageQueue = new ConcurrentLinkedQueue<>(); + for (int i = 1; i <= totalPages; i++) { + pageQueue.add(i); + } + + // 创建并启动4个线程 + Thread[] threads = new Thread[8]; + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread(new PageProcessor(pageQueue)); + threads[i].start(); + } + + // 等待所有线程完成 + for (Thread thread : threads) { + thread.join(); + } + + System.out.println("所有页面处理完成"); + } + + private void processPage(int page) { + File file = new File("D:/1318/" + page + ".json"); + if (file.exists()) { +// System.out.println("第" + page + "页文件已存在,跳过处理"); + return; + } + IM1318 im1318 = new IM1318(); + System.out.println("正在处理第" + page + "页"); + String dateTimeString = "2020-01-01 00:00:00"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + im1318.setUpdtTime(LocalDateTime.parse(dateTimeString, formatter)); + im1318.setValiFlag("1"); + im1318.setPageNum(page); + im1318.setPageSize(1000); + OM1318 om1318 = socialRequest.call1318(im1318); + System.out.println(page + "/" + om1318.getPages()); + List> data = om1318.getData(); + saveDataToFile(data, "D:/1318/" + page + ".json"); + processedPages.incrementAndGet(); // 增加已处理的页面数 + printEstimatedRemainingTime(); // 打印剩余时间估计 + } + + private void printEstimatedRemainingTime() { + Instant now = Instant.now(); + Duration elapsedTime = Duration.between(startTime, now); + int currentProcessedPages = processedPages.get(); // 使用 get 方法获取当前处理的页面数 + if (currentProcessedPages == 0) { + return; // 避免除以零 + } + double averageTimePerPage = elapsedTime.toMillis() / (double) currentProcessedPages; + int remainingPages = totalPages - currentProcessedPages; + long estimatedRemainingTimeInMillis = (long) (averageTimePerPage * remainingPages); + Duration estimatedRemainingTime = Duration.ofMillis(estimatedRemainingTimeInMillis); + + System.out.println("Estimated remaining time: " + estimatedRemainingTime.toHoursPart() + " hours, " + + estimatedRemainingTime.toMinutesPart() + " minutes, " + + estimatedRemainingTime.getSeconds() + " seconds"); + } + + private void saveDataToFile(List> data, String filePath) { + try { + if (data == null || data.isEmpty()) { + return; + } + + // 将 data 转换为 JSON 字符串 + String jsonString = JSONObject.toJSONString(data); + + // 创建文件夹(如果不存在) + File folder = new File("D:/1318"); + if (!folder.exists()) { + folder.mkdirs(); + } + + // 写入文件 + File file = new File(filePath); + if (file.exists()) { + file.delete(); + } + + try (FileWriter writer = new FileWriter(file)) { + writer.write(jsonString); + } + + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Failed to save data to file", e); + } + } + + // 定义一个内部类来处理页码 + private class PageProcessor implements Runnable { + private final ConcurrentLinkedQueue pageQueue; + + public PageProcessor(ConcurrentLinkedQueue pageQueue) { + this.pageQueue = pageQueue; + } + + @Override + public void run() { + while (true) { + Integer page = pageQueue.poll(); + if (page == null) { + // 队列为空,退出循环 + break; + } + try{ + processPage(page); + }catch (Exception e){ + System.out.println("第"+page+"页出错"); + e.printStackTrace(); + } + + + } + } + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1319.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1319.java new file mode 100644 index 0000000..db10eac --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/Download1319.java @@ -0,0 +1,151 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.alibaba.fastjson.JSONObject; +import com.syjiaer.pharmacy.server.modules.social.api.input.IM1319; +import com.syjiaer.pharmacy.server.modules.social.api.output.OM1319; +import com.syjiaer.pharmacy.server.modules.social.api.request.SocialRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; +@Component +public class Download1319 { + @Autowired + private SocialRequest socialRequest; + private Instant startTime; + private int totalPages = 3547; + private AtomicInteger processedPages = new AtomicInteger(0); // 使用 AtomicInteger + + public void download() throws InterruptedException { + startTime = Instant.now(); + + // 创建一个队列来存储页码 + ConcurrentLinkedQueue pageQueue = new ConcurrentLinkedQueue<>(); + for (int i = 1; i <= totalPages; i++) { + pageQueue.add(i); + } + + // 创建并启动4个线程 + Thread[] threads = new Thread[8]; + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread(new PageProcessor(pageQueue)); + threads[i].start(); + } + + // 等待所有线程完成 + for (Thread thread : threads) { + thread.join(); + } + + System.out.println("所有页面处理完成"); + } + + private void processPage(int page) { + File file = new File("D:/1319/" + page + ".json"); + if (file.exists()) { +// System.out.println("第" + page + "页文件已存在,跳过处理"); + return; + } + IM1319 im1319 = new IM1319(); + System.out.println("正在处理第" + page + "页"); + String dateTimeString = "2020-01-01 00:00:00"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + im1319.setUpdtTime(LocalDateTime.parse(dateTimeString, formatter)); + im1319.setSelfpayPropPsnType("310"); + im1319.setValiFlag("1"); + im1319.setPageNum(page); + im1319.setPageSize(1000); + OM1319 om1319 = socialRequest.call1319(im1319); + System.out.println(page + "/" + om1319.getPages()); + List> data = om1319.getData(); + saveDataToFile(data, "D:/1319/" + page + ".json"); + processedPages.incrementAndGet(); // 增加已处理的页面数 + printEstimatedRemainingTime(); // 打印剩余时间估计 + } + + private void printEstimatedRemainingTime() { + Instant now = Instant.now(); + Duration elapsedTime = Duration.between(startTime, now); + int currentProcessedPages = processedPages.get(); // 使用 get 方法获取当前处理的页面数 + if (currentProcessedPages == 0) { + return; // 避免除以零 + } + double averageTimePerPage = elapsedTime.toMillis() / (double) currentProcessedPages; + int remainingPages = totalPages - currentProcessedPages; + long estimatedRemainingTimeInMillis = (long) (averageTimePerPage * remainingPages); + Duration estimatedRemainingTime = Duration.ofMillis(estimatedRemainingTimeInMillis); + + System.out.println("Estimated remaining time: " + estimatedRemainingTime.toHoursPart() + " hours, " + + estimatedRemainingTime.toMinutesPart() + " minutes, " + + estimatedRemainingTime.getSeconds() + " seconds"); + } + + private void saveDataToFile(List> data, String filePath) { + try { + if (data == null || data.isEmpty()) { + return; + } + + // 将 data 转换为 JSON 字符串 + String jsonString = JSONObject.toJSONString(data); + + // 创建文件夹(如果不存在) + File folder = new File("D:/1319"); + if (!folder.exists()) { + folder.mkdirs(); + } + + // 写入文件 + File file = new File(filePath); + if (file.exists()) { + file.delete(); + } + + try (FileWriter writer = new FileWriter(file)) { + writer.write(jsonString); + } + + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Failed to save data to file", e); + } + } + + // 定义一个内部类来处理页码 + private class PageProcessor implements Runnable { + private final ConcurrentLinkedQueue pageQueue; + + public PageProcessor(ConcurrentLinkedQueue pageQueue) { + this.pageQueue = pageQueue; + } + + @Override + public void run() { + while (true) { + Integer page = pageQueue.poll(); + if (page == null) { + // 队列为空,退出循环 + break; + } + try{ + processPage(page); + }catch (Exception e){ + System.out.println("第"+page+"页出错"); + e.printStackTrace(); + } + + + } + } + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/FileUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/FileUtil.java new file mode 100644 index 0000000..9b29f11 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/FileUtil.java @@ -0,0 +1,105 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.syjiaer.pharmacy.server.common.exception.MessageException; +import org.springframework.stereotype.Component; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +@Component +public class FileUtil { + public List readToList(List file_list) { + List list = new ArrayList(); + for (String file : file_list) { + List child_list = readToList(file); + list.addAll(child_list); + } + return list; + + } + + public List readToList(String file) { + List list = new ArrayList(); + int i = 0; + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + String line; + while ((line = br.readLine()) != null) { + list.add(line); + } + } catch (IOException e) { + throw new MessageException("读取文件失败"); + } + return list; + } + + public String readFileToString(String path) { + StringBuilder content = new StringBuilder(); + try (BufferedReader br = new BufferedReader(new FileReader(path))) { + String line; + while ((line = br.readLine()) != null) { + content.append(line).append("\n"); + } + } catch (IOException e) { + throw new MessageException("读取文件失败"); + } + return content.toString(); + } + + + public List unzip(String path, String filename) { + List file_list = new ArrayList(); + try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(path + "/" + filename))) { + byte[] buffer = new byte[4096]; + ZipEntry zipEntry; + + while ((zipEntry = zipInputStream.getNextEntry()) != null) { + String fileName = zipEntry.getName(); + String txtfilename = path + File.separator + fileName; + File newFile = new File(txtfilename); + if (txtfilename.endsWith(".txt")) { + file_list.add(txtfilename); + } + // Create directories if needed + new File(newFile.getParent()).mkdirs(); + + // Write the extracted file to disk + try (FileOutputStream fos = new FileOutputStream(newFile)) { + int length; + while ((length = zipInputStream.read(buffer)) > 0) { + fos.write(buffer, 0, length); + } + } + zipInputStream.closeEntry(); + } + } catch (IOException e) { + e.printStackTrace(); + } + return file_list; + } + + public void zipFiles(String[] srcFiles, String zipFile) { + try (FileOutputStream fos = new FileOutputStream(zipFile); + ZipOutputStream zos = new ZipOutputStream(fos)) { + + for (String srcFile : srcFiles) { + File fileToZip = new File(srcFile); + FileInputStream fis = new FileInputStream(fileToZip); + ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); + zos.putNextEntry(zipEntry); + + byte[] bytes = new byte[1024]; + int length; + while ((length = fis.read(bytes)) >= 0) { + zos.write(bytes, 0, length); + } + fis.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/HeadersUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/HeadersUtil.java new file mode 100644 index 0000000..cc3703b --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/HeadersUtil.java @@ -0,0 +1,21 @@ +package com.syjiaer.pharmacy.server.common.util; + +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +public class HeadersUtil { + private static final ThreadLocal> threadLocal = new ThreadLocal<>(); + public void setMap(Map map) { + threadLocal.set(map); + } + + public Map getMap() { + return threadLocal.get(); + } + + public void remove() { + threadLocal.remove(); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/HttpUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/HttpUtil.java new file mode 100644 index 0000000..6b545a7 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/HttpUtil.java @@ -0,0 +1,380 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; +import com.syjiaer.pharmacy.server.common.config.Config; +import com.syjiaer.pharmacy.server.common.exception.MessageException; +import com.syjiaer.pharmacy.server.modules.social.api.input.IM9101; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.logging.Logger; + +@Slf4j +@Component +public class HttpUtil { + @Autowired + private Config config; + + private Logger logger = Logger.getLogger(HttpUtil.class.getName()); + + private JSONObject post(String posturl, String params,Boolean isLog) { + String result = ""; + try { + StringBuffer resultBuffer = new StringBuffer(); + logger.info("调用医保请求入参==》" + params); + URL url = new URL(posturl); + URLConnection conn = url.openConnection(); + + //2.处理设置参数和一般请求属性 + //2.1设置参数 + //可以根据请求的需要设置参数 + conn.setDoInput(true); //默认为true 所以不设置也可以 + conn.setDoOutput(true); //默认为false 发送post请求必须设置setDoOutput(true) + conn.setUseCaches(false); //是否可以使用缓存 不使用缓存 + conn.setConnectTimeout(120000);//请求超时时间 + + //2.2请求属性 + //设置通用的请求属性 消息报头 即设置头字段 更多的头字段信息可以查阅HTTP协议 + conn.setRequestProperty("Connection", "Keep-Alive"); + conn.setRequestProperty("Content-Type", "application/json"); + + //2.3设置请求正文 即要提交的数据 + PrintWriter pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream())); + pw.print(params); + pw.flush(); + pw.close(); + + //3.使用 connect 方法建立到远程对象的实际连接。 + conn.connect(); + + //4.远程对象变为可用。远程对象的头字段和内容变为可访问。 + BufferedReader reader = null; + String tempLine = null; + + reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK")); + while ((tempLine = reader.readLine()) != null) { + resultBuffer.append(tempLine); + } + reader.close(); + result = resultBuffer.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + logger.info("调用医保请求出参==》" + result); + JSONObject result_json = JSON.parseObject(result); + + if (!result_json.getString("err_msg").equals("成功") &&!result_json.getString("err_msg").equals("success") && !result_json.getString("err_msg").isEmpty()) { + throw new MessageException(result_json.getString("err_msg")); + } + JSONObject output = result_json.getJSONObject("output"); + //清理一周前记录 + + return output; + } + private JSONArray postArray(String posturl, String params) { + String result = ""; + try { + StringBuffer resultBuffer = new StringBuffer(); + logger.info("调用医保请求入参==》" + params); + URL url = new URL(posturl); + URLConnection conn = url.openConnection(); + + //2.处理设置参数和一般请求属性 + //2.1设置参数 + //可以根据请求的需要设置参数 + conn.setDoInput(true); //默认为true 所以不设置也可以 + conn.setDoOutput(true); //默认为false 发送post请求必须设置setDoOutput(true) + conn.setUseCaches(false); //是否可以使用缓存 不使用缓存 + conn.setConnectTimeout(120000);//请求超时时间 + + //2.2请求属性 + //设置通用的请求属性 消息报头 即设置头字段 更多的头字段信息可以查阅HTTP协议 + conn.setRequestProperty("Connection", "Keep-Alive"); + conn.setRequestProperty("Content-Type", "application/json"); + + //2.3设置请求正文 即要提交的数据 + PrintWriter pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream())); + pw.print(params); + pw.flush(); + pw.close(); + + //3.使用 connect 方法建立到远程对象的实际连接。 + conn.connect(); + + //4.远程对象变为可用。远程对象的头字段和内容变为可访问。 + BufferedReader reader = null; + String tempLine = null; + + reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK")); + while ((tempLine = reader.readLine()) != null) { + resultBuffer.append(tempLine); + } + reader.close(); + result = resultBuffer.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + logger.info("调用医保请求出参==》" + result); + JSONObject result_json = JSON.parseObject(result); + if (!result_json.getString("err_msg").equals("success") && !result_json.getString("err_msg").isEmpty()) { + throw new MessageException(result_json.getString("err_msg")); + } + JSONArray output = result_json.getJSONArray("output"); + return output; + } + + private String download(String posturl, String params, String saveFilePath) { + StringBuffer resultBuffer = new StringBuffer(); + try { + URL url = new URL(posturl); + URLConnection conn = url.openConnection(); + + //2.处理设置参数和一般请求属性 + //2.1设置参数 + //可以根据请求的需要设置参数 + conn.setDoInput(true); //默认为true 所以不设置也可以 + conn.setDoOutput(true); //默认为false 发送post请求必须设置setDoOutput(true) + conn.setUseCaches(false); //是否可以使用缓存 不使用缓存 + conn.setConnectTimeout(120000);//请求超时时间 + + //2.2请求属性 + //设置通用的请求属性 消息报头 即设置头字段 更多的头字段信息可以查阅HTTP协议 + conn.setRequestProperty("Connection", "Keep-Alive"); + conn.setRequestProperty("Content-Type", "application/json"); + + //2.3设置请求正文 即要提交的数据 + PrintWriter pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream())); + pw.print(params); + pw.flush(); + pw.close(); + + //3.使用 connect 方法建立到远程对象的实际连接。 + conn.connect(); + //4.远程对象变为可用。远程对象的头字段和内容变为可访问。 + InputStream inputStream = conn.getInputStream(); + FileOutputStream outputStream = new FileOutputStream(saveFilePath); + + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + + outputStream.close(); + inputStream.close(); + log.info("文件下载完成"); + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } + + public JSONObject call(String infno,Map input) { + + JSONObject output = post(config.get("social", "url"), JSON.toJSONString(getparms(infno, input)),true); + return output; + } + public JSONObject call(String infno, String tag, Map input) { + + JSONObject output = post(config.get("social", "url"), JSON.toJSONString(getparms(infno, tag, input)),true); + return output; + } + public JSONObject callWithOutLog(String infno, String tag, Map input) { + + JSONObject output = post(config.get("social", "url"), JSON.toJSONString(getparms(infno, tag, input)), false); + return output; + } + + public JSONObject callMutiply(String infno, String tag, Map input, Map inputs) { + Map map = getparms(infno, tag, input); + @SuppressWarnings("unchecked") + Map inputMap = (Map)map.get("input"); + for (String key : inputs.keySet()){ + inputMap.put(key, inputs.get(key)); + } + JSONObject output = post(config.get("social", "url"), JSON.toJSONString(map),true); + return output; + } + + + public void callToFile(String infno, String tag, Map input, String saveFilePath) { + download(config.get("social", "url"), JSON.toJSONString(getparms(infno, tag, input)), saveFilePath); + } + public JSONObject callUploadFile(String filePath){ + return uploadFile(config.get("social", "url"), filePath); + } + + + private Map getparms(String infno, String tag, Object input) { + + Random random = new Random(); + int randomNumber = random.nextInt(9000) + 1000; + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter now_str = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + DateTimeFormatter now_str2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + Map map = new HashMap<>(); + + map.put("infno", infno); + map.put("insuplc_admdvs", config.get("social", "insuplcAdmdvs")); + map.put("msgid", config.get("social", "msgid") + now_str.format(now) + String.valueOf(randomNumber)); + map.put("infver", "V1.0"); + map.put("inf_time", now.format(now_str2)); + map.put("opter", config.get("social", "opter")); + map.put("opter_name", config.get("social", "opterName")); + map.put("opter_type", "1"); + map.put("fixmedins_code", config.get("social", "fixmedinsCode")); + map.put("fixmedins_name", config.get("social", "fixmedinsName")); + map.put("mdtrtarea_admvs", config.get("social", "mdtrtareaAdmvs")); + map.put("recer_sys_code", config.get("social", "recerSysCode")); + map.put("cainfo", config.get("social", "cainfo")); + map.put("sign_no", ""); + HashMap inputMap = new HashMap<>(); + inputMap.put(tag, input); + map.put("input", inputMap); + return map; + } + private Map getparms(String infno, Object input) { + + Random random = new Random(); + int randomNumber = random.nextInt(9000) + 1000; + LocalDateTime now = LocalDateTime.now(); + DateTimeFormatter now_str = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + DateTimeFormatter now_str2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + Map map = new HashMap<>(); + + map.put("infno", infno); + map.put("insuplc_admdvs", config.get("social", "insuplcAdmdvs")); + map.put("msgid", config.get("social", "msgid") + now_str.format(now) + String.valueOf(randomNumber)); + map.put("infver", "V1.0"); + map.put("inf_time", now.format(now_str2)); + map.put("opter", config.get("social", "opter")); + map.put("opter_name", config.get("social", "opterName")); + map.put("opter_type", "1"); + map.put("fixmedins_code", config.get("social", "fixmedinsCode")); + map.put("fixmedins_name", config.get("social", "fixmedinsName")); + map.put("mdtrtarea_admvs", config.get("social", "mdtrtareaAdmvs")); + map.put("recer_sys_code", config.get("social", "recerSysCode")); + map.put("cainfo", config.get("social", "cainfo")); + map.put("sign_no", ""); + map.put("input", input); + return map; + } + + + + +// private JSONObject uploadFile(String posturl, String filePath) { +// String result = ""; +// try { +// URL url = new URL(posturl); +// URLConnection conn = url.openConnection(); +// +// // 设置请求属性 +// conn.setDoInput(true); +// conn.setDoOutput(true); +// conn.setUseCaches(false); +// conn.setConnectTimeout(120000); +// conn.setRequestProperty("Connection", "Keep-Alive"); +// conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); +// +// // 写入请求正文 +// try (OutputStream os = conn.getOutputStream()) { +// // 读取文件字节数组 +// byte[] fileBytes = Files.readAllBytes(Paths.get(filePath)); +// String fileName = Paths.get(filePath).getFileName().toString(); +// +// // 写入文件部分 +// os.write(("--" + boundary + "\r\n").getBytes()); +// os.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n").getBytes()); +// os.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); +// +// os.write(fileBytes); +// os.write(("\r\n--" + boundary + "\r\n").getBytes()); +// IM9101 im9101 = new IM9101(); +// IM9101.Data data = new IM9101.Data(); +// data.setIn(fileBytes); +// data.setFilename(fileName); +// data.setFixmedinsCode(config.get("social", "fixmedinsCode")); +// im9101.setData(data); +// Map parms = getparms("9101", im9101.buildToMap()); +// // 构建JSON参数部分 +// String jsonString = JSON.toJSONString(parms); +// logger.info("调用医保请求入参==》" + parms); +// // 写入JSON参数部分 +// os.write(("Content-Disposition: form-data; name=\"params\"\r\n").getBytes()); +// os.write(("Content-Type: application/json\r\n\r\n").getBytes()); +// os.write((jsonString + "\r\n").getBytes()); +// +// os.write(("--" + boundary + "--\r\n").getBytes()); +// } +// +//// // 获取响应 +//// try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"))) { +//// String tempLine; +//// StringBuilder resultBuffer = new StringBuilder(); +//// while ((tempLine = reader.readLine()) != null) { +//// resultBuffer.append(tempLine); +//// } +//// result = resultBuffer.toString(); +//// } +// } catch (Exception e) { +// e.printStackTrace(); +// } +// logger.info("调用医保请求出参==》" + result); +// JSONObject result_json = JSON.parseObject(result); +// +// if (!result_json.getString("err_msg").equals("成功") && !result_json.getString("err_msg").equals("success") && !result_json.getString("err_msg").isEmpty()) { +// throw new MessageException(result_json.getString("err_msg")); +// } +// JSONObject output = result_json.getJSONObject("output"); +// return output; +// } + + private static final String boundary = UUID.randomUUID().toString(); + + + private JSONObject uploadFile(String posturl, String filePath) { + + // 写入请求正文 + try { + // 读取文件字节数组 + byte[] fileBytes = Files.readAllBytes(Paths.get(filePath)); + String fileName = Paths.get(filePath).getFileName().toString(); + + + IM9101 im9101 = new IM9101(); + IM9101.FsUploadIn fsUploadIn = new IM9101.FsUploadIn(); + fsUploadIn.setIn(fileBytes); + fsUploadIn.setFilename(fileName); + fsUploadIn.setFixmedins_code(config.get("social", "fixmedinsCode")); + im9101.setFsUploadIn(fsUploadIn); + Map parms = getparms("9101", im9101.buildToMap()); + // 构建JSON参数部分 + String jsonString = JSON.toJSONString(parms); + // 写入JSON参数部分 + JSONObject result = post(posturl, jsonString, true); + return result; + + } catch (Exception e) { + e.printStackTrace(); + return null; + } + + } + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/InfoUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/InfoUtil.java new file mode 100644 index 0000000..ff208fa --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/InfoUtil.java @@ -0,0 +1,30 @@ +package com.syjiaer.pharmacy.server.common.util; + +import org.springframework.stereotype.Component; + +import java.util.Map; + +@Component +public class InfoUtil { + private static final ThreadLocal> threadLocal = new ThreadLocal<>(); + + public void setMap(Map map) { + threadLocal.set(map); + } + + public Map getMap() { + return threadLocal.get(); + } + + public void remove() { + threadLocal.remove(); + } + public Boolean isEmpty(String key){ + Map map = getMap(); + + if(map.get(key)==null||map.get(key).equals("")){ + return true; + } + return false; + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/JoinQueryWrapper.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/JoinQueryWrapper.java new file mode 100644 index 0000000..b0f1fbc --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/JoinQueryWrapper.java @@ -0,0 +1,60 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; + +import java.util.ArrayList; +import java.util.List; + +public class JoinQueryWrapper extends QueryWrapper { + private List joins = new ArrayList<>(); // 存储连接条件 + + // 定义连接条件类 + private static class JoinCondition { + private String alias; + private String table; + private String type; + private String onCondition; + + public JoinCondition(String alias, String table, String type, String onCondition) { + this.alias = alias; + this.table = table; + this.type = type; + this.onCondition = onCondition; + } + + public String getAlias() { + return alias; + } + + public String getTable() { + return table; + } + + public String getType() { + return type; + } + + public String getOnCondition() { + return onCondition; + } + } + + // 实现左连接方法 + public JoinQueryWrapper leftJoin(String tableAlias, String tableName, String onCondition) { + joins.add(new JoinCondition(tableAlias, tableName, "LEFT JOIN", onCondition)); + return this; + } + + // 实现右连接方法 + public JoinQueryWrapper rightJoin(String tableAlias, String tableName, String onCondition) { + joins.add(new JoinCondition(tableAlias, tableName, "RIGHT JOIN", onCondition)); + return this; + } + + + // 重写 instance 方法 + @Override + protected JoinQueryWrapper instance() { + return this; + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/ParmsUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/ParmsUtil.java new file mode 100644 index 0000000..0e07dac --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/ParmsUtil.java @@ -0,0 +1,124 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import com.syjiaer.pharmacy.server.common.exception.MessageException; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Component +public class ParmsUtil { + private static final ThreadLocal> threadLocal = new ThreadLocal<>(); + + public void setMap(Map map) { + threadLocal.set(map); + } + + public Map getMap() { + return threadLocal.get(); + } + + public void remove() { + threadLocal.remove(); + } + public Boolean isEmpty(String key){ + Map map = getMap(); + + if(map.get(key)==null||map.get(key).equals("")){ + return true; + } + return false; + } + public String getString(String key){ + Map map = getMap(); + if(isEmpty(key)){ + return ""; + } + return map.get(key).toString(); + } + public T getObject(String key, Class clazz){ + Map map = getMap(); + if(isEmpty(key)){ + return null; + } + T t = JSON.parseObject(JSON.toJSONString(map.get(key)), clazz); + return t; + } + public Map getMap(String key){ + Map map = getMap(); + if(isEmpty(key)){ + return null; + } + return JSON.parseObject(JSON.toJSONString(map.get(key)), Map.class); + } + public List getList(String key, Class clazz,String empty_message){ + Map map = getMap(); + if(isEmpty(key)){ + throw new MessageException(empty_message); + } + List list = getList(key, clazz); + if(list==null|| list.isEmpty()){ + throw new MessageException(empty_message); + } + return list; + + } + public List getIntList(String key){ + Map map = getMap(); + if(isEmpty(key)){ + return null; + } + List _list= (List) map.get(key); + if(_list==null||_list.size()==0){ + return null; + } + List list=new ArrayList<>(); + for (int i = 0; i < _list.size(); i++) { + list.add(_list.get(i)); + } + + return list; + } + public List getList(String key, Class clazz){ + Map map = getMap(); + if(isEmpty(key)){ + return null; + } + List _list= (List) map.get(key); + if(_list==null||_list.size()==0){ + return null; + } + List list=new ArrayList<>(); + for (int i = 0; i < _list.size(); i++) { + JSONObject jsonObject = _list.get(i); + T t=jsonObject.toJavaObject(clazz); + list.add(t); + } + + return list; + } + public Integer getInteger(String key){ + Map map = getMap(); + if(isEmpty(key)){ + return null; + } + return Integer.parseInt(map.get(key).toString()); + } + public String getString(String key,String empty_message){ + Map map = getMap(); + if(isEmpty(key)){ + throw new MessageException(empty_message); + } + return map.get(key).toString(); + } + public Integer getInteger(String key,String empty_message){ + Map map = getMap(); + if(isEmpty(key)){ + throw new MessageException(empty_message); + } + return Integer.parseInt(map.get(key).toString()); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/PdfUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/PdfUtil.java new file mode 100644 index 0000000..3415072 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/PdfUtil.java @@ -0,0 +1,50 @@ +package com.syjiaer.pharmacy.server.common.util; + +import com.syjiaer.pharmacy.server.common.exception.MessageException; +import net.sf.jasperreports.engine.*; +import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; +import org.springframework.stereotype.Component; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +@Component +public class PdfUtil { + public void setPdf(String templateName,String fileName, Map map, List> list) { + InputStream inputStream = PdfUtil.class.getClassLoader().getResourceAsStream("jasTemplate\\"+templateName+".jasper"); + JRDataSource dataSource = null; + if(list == null){ + dataSource = new JREmptyDataSource(); + }else{ + dataSource = new JRBeanCollectionDataSource(list); + } + if(map==null){ + map = new HashMap(); + } + try { + JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, map, dataSource); + // 生成随机文件名 + String randomFileName = UUID.randomUUID().toString() + ".pdf"; + // 导出PDF到指定路径 + JasperExportManager.exportReportToPdfFile(jasperPrint, fileName); + // 返回随机文件名 + return; + } catch (Exception e) { + e.printStackTrace(); + throw new MessageException("生成PDF出错"); + + + } finally { + try { + if (inputStream != null) { + inputStream.close(); // 确保输入流关闭 + } + } catch (Exception e) { + e.printStackTrace(); + throw new MessageException("关闭PDF流出错"); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/RsaUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/RsaUtil.java new file mode 100644 index 0000000..4b80412 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/RsaUtil.java @@ -0,0 +1,21 @@ +package com.syjiaer.pharmacy.server.common.util; + +import javax.crypto.Cipher; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; + +public class RsaUtil { + private final String publicKeyText="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuZIsQPculdbnvQhgNN6DyvMgnr1NhYfUcL6hYbUTrO1aF/GJDBOL8HTHnII8rz5CNmG/R55Ev6nMb9kLHnhjXujDsdNpNjVtH1EZkvjxIIl87sPP0xQCeI2qScLX2Jb/41g6zv2iopwISV/tbKk4KchJaMByJFpUfA1Dpc35sjQugI2j4+MY7OSd6JFO2i/xmtwev2cBQqZ6y7YX6BgMyKxBnaYZ9sFTa5AkMZoIfMyfllQm/MFtStHcLPM/sycooQOGwYGsFCShY/4oSwaG+WlVdW28+JOHgWlNAMR7S5ebb8PkGF+Kyva/KR+EG1b8bL5MkA1iZ5+dRFrQXwE3gwIDAQAB" ; + public String decryp(String encryptedDataStr) throws Exception { + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyText)); + PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec); + + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + cipher.init(Cipher.DECRYPT_MODE, publicKey); + byte[] encryptedData = Base64.getDecoder().decode(encryptedDataStr); + return new String(cipher.doFinal(encryptedData)); + } + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/util/StringUtil.java b/src/main/java/com/syjiaer/pharmacy/server/common/util/StringUtil.java new file mode 100644 index 0000000..2afe3c6 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/util/StringUtil.java @@ -0,0 +1,12 @@ +package com.syjiaer.pharmacy.server.common.util; + +import org.springframework.stereotype.Component; + +import java.util.UUID; + +@Component +public class StringUtil { + public String generateRandomId() { + return UUID.randomUUID().toString(); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/vo/Page.java b/src/main/java/com/syjiaer/pharmacy/server/common/vo/Page.java new file mode 100644 index 0000000..280f26a --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/vo/Page.java @@ -0,0 +1,21 @@ +package com.syjiaer.pharmacy.server.common.vo; + +import lombok.Getter; +import lombok.Setter; + +import java.util.List; +import java.util.function.Function; + +@Setter +@Getter +public class Page { + private int total_page; + private long total_count; + private List list; + + public Page process(Page page, Function, List> processor) { + List processedList = processor.apply(page.getList()); + page.setList(processedList); + return page; + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/common/vo/Result.java b/src/main/java/com/syjiaer/pharmacy/server/common/vo/Result.java new file mode 100644 index 0000000..74e1d81 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/common/vo/Result.java @@ -0,0 +1,31 @@ +package com.syjiaer.pharmacy.server.common.vo; + +public class Result { + private int code; + private String message; + private T data; + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseController.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseController.java new file mode 100644 index 0000000..afb1d9d --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseController.java @@ -0,0 +1,137 @@ +package com.syjiaer.pharmacy.server.modules.base.controller; + + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.IService; +import com.syjiaer.pharmacy.server.common.exception.VerifyException; +import com.syjiaer.pharmacy.server.common.util.HeadersUtil; +import com.syjiaer.pharmacy.server.common.util.InfoUtil; +import com.syjiaer.pharmacy.server.common.util.ParmsUtil; +import com.syjiaer.pharmacy.server.common.vo.Page; +import com.syjiaer.pharmacy.server.common.vo.Result; +import com.syjiaer.pharmacy.server.modules.base.entity.ManagerUser; +import com.syjiaer.pharmacy.server.modules.base.service.ICommonLogService; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.JwtException; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Map; + +public abstract class BaseController { + @Value("${jwt.secret}") + protected String jwtSecret; + @Autowired + protected ParmsUtil parmsUtil; + @Autowired + protected HeadersUtil headersUtil; + @Autowired + protected InfoUtil infoUtil; + @Autowired + private ICommonLogService commonLogService; + // 使用 ThreadLocal 来缓存请求参数 + + public Boolean isEmpty(String key, Map map) { + if (map.get(key) == null || map.get(key).toString().isEmpty()) { + return true; + } + return false; + } + + protected Result success() { + Result result = new Result<>(); + result.setCode(0); + return result; + } + + protected Result success(T data) { + Result result = new Result<>(); + result.setCode(0); + result.setData(data); + return result; + } + + protected Result error(String message) { + Result result = new Result<>(); + result.setCode(1001); + result.setMessage(message); + return result; + } + + + protected Result error(int code, String message) { + Result result = new Result<>(); + result.setCode(code); + result.setMessage(message); + return result; + } + + ; + + protected Map getParms() { + return parmsUtil.getMap(); + } + + + protected Map getHeaders() { + return headersUtil.getMap(); + } + + protected HttpServletRequest getRequest() { + return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); + } + + protected ManagerUser getManagerUser() { + Map headers = getHeaders(); + String token = headers.get("authorization"); + if (token == null || token.isEmpty()) { + throw new VerifyException("登陆令牌不存在,请重新登陆"); + } + Jws claimsJws = null; + try { + claimsJws = Jwts.parser() + .verifyWith(Keys.hmacShaKeyFor(jwtSecret.getBytes())) + .build() + .parseSignedClaims(token); + } catch (JwtException e) { + throw new VerifyException("用户身份验证已失效,请重新登陆"); + } catch (Exception e) { + throw new VerifyException("未知验证错误,请重新登陆"); + } + + if (claimsJws == null) { + throw new VerifyException("用户身份验证已失效,请重新登陆"); + } + Claims claims = claimsJws.getPayload(); + ManagerUser managerUser = new ManagerUser(); + managerUser.setId(Integer.parseInt(claims.getSubject())); + managerUser.setUsername(claims.get("username", String.class)); + managerUser.setName(claims.get("name", String.class)); + return managerUser; + + } + protected DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + protected Page pageHelper(int pageNum, int pageSize, QueryWrapper queryWrapper, IService iservice){ + Long totalCount = iservice.count(queryWrapper); + queryWrapper.last("LIMIT " + (pageNum - 1) * pageSize + ", " + pageSize); + List list = iservice.list(queryWrapper); + Page page = new Page(); + page.setList(list); + page.setTotal_count(totalCount); + page.setTotal_page((int) Math.ceil(totalCount / (double) pageSize)); + return page; + } + protected void saveLog(String message){ + ManagerUser managerUser = getManagerUser(); + commonLogService.saveLog(message,managerUser.getId()); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseDefaultController.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseDefaultController.java new file mode 100644 index 0000000..431f7c0 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseDefaultController.java @@ -0,0 +1,6 @@ +package com.syjiaer.pharmacy.server.modules.base.controller; + + +public class BaseDefaultController extends BaseController { + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseSocialController.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseSocialController.java new file mode 100644 index 0000000..e4cfbee --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/BaseSocialController.java @@ -0,0 +1,35 @@ +package com.syjiaer.pharmacy.server.modules.base.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.service.IService; +import com.syjiaer.pharmacy.server.common.vo.Page; +import org.springframework.beans.factory.annotation.Value; + +import java.util.List; + +public class BaseSocialController extends BaseController { + @Value("${common.isdev}") + private Boolean isdev; + + protected Page SelectPage(QueryWrapper queryWrapper, int page_num, int size, IService service, String order_field, String order_type) { + Long total_count = service.count(queryWrapper); + queryWrapper.last("LIMIT " + size + " OFFSET " + (page_num - 1) * size); + if (order_type.equals("asc")) { + queryWrapper.orderByAsc(order_field); + } else { + queryWrapper.orderByDesc(order_field); + } + + List socialDirectoryList = service.list(queryWrapper); + int total_page = (int) Math.ceil((double) total_count / size); + Page page = new Page(); + page.setTotal_page(total_page); + page.setTotal_count(total_count); + page.setList(socialDirectoryList); + return page; + } + + protected Page SelectPage(QueryWrapper queryWrapper, int page_num, int size, IService service) { + return SelectPage(queryWrapper, page_num, size, service, "id", "asc"); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/CommonConfigController.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/CommonConfigController.java new file mode 100644 index 0000000..3ea9561 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/CommonConfigController.java @@ -0,0 +1,73 @@ +package com.syjiaer.pharmacy.server.modules.base.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.syjiaer.pharmacy.server.common.vo.Result; +import com.syjiaer.pharmacy.server.modules.base.entity.CommonConfig; +import com.syjiaer.pharmacy.server.modules.base.service.ICommonConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

+ * 前端控制器 + *

+ * + * @author NiuZiYuan + * @since 2025-02-24 + */ +@RestController +@RequestMapping("/common/config") +public class CommonConfigController extends BaseController { + @Autowired + private ICommonConfigService iCommonConfigService; + + @RequestMapping("list") + public Result list() { + return success(iCommonConfigService.list()); + } + + @RequestMapping("getall") + public Result getall() { + List list = iCommonConfigService.list(); + Map map=new HashMap<>(); + for (CommonConfig commonConfig : list) { + map.put(commonConfig.getK(),commonConfig.getVal()); + } + return success(map); + } + + @RequestMapping("edit") + public Result edit() { + Map parms = getParms(); + for (String key : parms.keySet()) { + CommonConfig commonConfig = new CommonConfig(); + commonConfig.setK(key); + commonConfig.setVal(parms.get(key).toString()); + iCommonConfigService.saveOrUpdate(commonConfig); + } + return success(); + } + @RequestMapping("setcert") + public Result sercert() { + Map parms = getParms(); + String encryptedText= parmsUtil.getString("encryptedText","请输入密文"); + CommonConfig commonConfig=new CommonConfig(); + commonConfig.setK("common_cert"); + commonConfig.setVal(encryptedText); + iCommonConfigService.saveOrUpdate(commonConfig); + return success(); + } + @RequestMapping("get") + public Result get() { + String key= parmsUtil.getString("key","请输入key"); + QueryWrapper queryWrapper=new QueryWrapper(); + queryWrapper.eq("k",key); + return success(iCommonConfigService.getOne(queryWrapper)); + } + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/ManagerUserController.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/ManagerUserController.java new file mode 100644 index 0000000..907e3cb --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/controller/ManagerUserController.java @@ -0,0 +1,73 @@ +package com.syjiaer.pharmacy.server.modules.base.controller; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.syjiaer.pharmacy.server.common.vo.Result; +import com.syjiaer.pharmacy.server.modules.base.entity.ManagerUser; +import com.syjiaer.pharmacy.server.modules.base.service.IManagerUserService; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.crypto.SecretKey; +import java.util.Date; +import java.util.Map; + +/** + *

+ * 前端控制器 + *

+ * + * @author NiuZiYuan + * @since 2025-02-28 + */ +@RestController +@RequestMapping("/manager/user") +public class ManagerUserController extends BaseDefaultController { + @Autowired + private IManagerUserService managerUserService; + + @Value("${jwt.expiration}") + private long jwtExpiration; + + @PostMapping("login") + public Result login() { + Map parms = getParms(); + String username = (String) parms.get("username"); + String password = (String) parms.get("password"); + if (username == null || username.isEmpty()) { + return error("请输入用户名"); + } + if (password == null || password.isEmpty()) { + return error("请输入密码"); + } + ManagerUser managerUser = managerUserService.getOne(new QueryWrapper().eq("username", username).eq("password", password)); + if (managerUser == null) { + return error("用户名或密码错误"); + } + Date exdata = new Date(System.currentTimeMillis() + jwtExpiration * 1000); + System.out.println(exdata); + SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes()); + String token = Jwts.builder() + .subject(managerUser.getId().toString()) // 用户ID作为主题 + .expiration(exdata) + .claim("username", managerUser.getUsername()) // 添加自定义声明 + .claim("name", managerUser.getName()) // 添加自定义声明 + .claim("userId", managerUser.getId()) + .signWith(key) + .compact(); + return success(token); + } + + //验证token + @PostMapping("verify") + public Result verify() { + ManagerUser managerUser =getManagerUser(); + return success(managerUser); + } + + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/CommonConfig.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/CommonConfig.java new file mode 100644 index 0000000..63d740b --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/CommonConfig.java @@ -0,0 +1,37 @@ +package com.syjiaer.pharmacy.server.modules.base.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.Accessors; + +import java.io.Serializable; +/** + *

+ * 配置信息表 + *

+ * + * @author NiuZiYuan + * @since 2025-03-09 + */ +@Getter +@Setter +@ToString +@Accessors(chain = true) +@TableName("common_config") +@ApiModel(value = "CommonConfig对象", description = "配置信息表") +public class CommonConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId("k") + @ApiModelProperty("键") + private String k; + + @ApiModelProperty("值") + private String val; +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/CommonLog.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/CommonLog.java new file mode 100644 index 0000000..e61e9aa --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/CommonLog.java @@ -0,0 +1,41 @@ +package com.syjiaer.pharmacy.server.modules.base.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.time.LocalDateTime; + +/** + *

+ * + *

+ * + * @author NiuZiYuan + * @since 2025-04-14 + */ +@Getter +@Setter +@ToString +@Accessors(chain = true) +@TableName("common_log") +@ApiModel(value = "CommonLog对象", description = "") +public class CommonLog implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + + private String message; + + private Integer managerId; + + private LocalDateTime createDatetime; +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/ManagerUser.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/ManagerUser.java new file mode 100644 index 0000000..cc9810d --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/entity/ManagerUser.java @@ -0,0 +1,51 @@ +package com.syjiaer.pharmacy.server.modules.base.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.Accessors; + +import java.io.Serializable; + +/** + *

+ * + *

+ * + * @author NiuZiYuan + * @since 2025-04-02 + */ +@Getter +@Setter +@ToString +@Accessors(chain = true) +@TableName("manager_user") +@ApiModel(value = "ManagerUser对象", description = "") +public class ManagerUser implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("自增主键") + @TableId(value = "id", type = IdType.AUTO) + private Integer id; + + @ApiModelProperty("用户名") + private String username; + + @ApiModelProperty("密码") + private String password; + + @ApiModelProperty("名称") + private String name; + + @ApiModelProperty("用户类型 0管理员 1销售人 2药师") + private Integer type; + + @ApiModelProperty("0禁用 1启用") + private Integer status; +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/CommonConfigMapper.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/CommonConfigMapper.java new file mode 100644 index 0000000..e7599f7 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/CommonConfigMapper.java @@ -0,0 +1,16 @@ +package com.syjiaer.pharmacy.server.modules.base.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.syjiaer.pharmacy.server.modules.base.entity.CommonConfig; + +/** + *

+ * Mapper 接口 + *

+ * + * @author NiuZiYuan + * @since 2025-02-24 + */ +public interface CommonConfigMapper extends BaseMapper { + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/CommonLogMapper.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/CommonLogMapper.java new file mode 100644 index 0000000..e59007c --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/CommonLogMapper.java @@ -0,0 +1,18 @@ +package com.syjiaer.pharmacy.server.modules.base.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.syjiaer.pharmacy.server.modules.base.entity.CommonLog; + + +/** + *

+ * Mapper 接口 + *

+ * + * @author NiuZiYuan + * @since 2025-04-14 + */ +public interface CommonLogMapper extends BaseMapper { + +} + diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/ManagerUserMapper.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/ManagerUserMapper.java new file mode 100644 index 0000000..3cf0ec7 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/mapper/ManagerUserMapper.java @@ -0,0 +1,18 @@ +package com.syjiaer.pharmacy.server.modules.base.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.syjiaer.pharmacy.server.modules.base.entity.ManagerUser; + + +/** + *

+ * Mapper 接口 + *

+ * + * @author NiuZiYuan + * @since 2025-02-28 + */ +public interface ManagerUserMapper extends BaseMapper { + +} + diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/ICommonConfigService.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/ICommonConfigService.java new file mode 100644 index 0000000..cde89bc --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/ICommonConfigService.java @@ -0,0 +1,16 @@ +package com.syjiaer.pharmacy.server.modules.base.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.syjiaer.pharmacy.server.modules.base.entity.CommonConfig; + +/** + *

+ * 服务类 + *

+ * + * @author NiuZiYuan + * @since 2025-02-24 + */ +public interface ICommonConfigService extends IService { + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/ICommonLogService.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/ICommonLogService.java new file mode 100644 index 0000000..946e12d --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/ICommonLogService.java @@ -0,0 +1,18 @@ +package com.syjiaer.pharmacy.server.modules.base.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.syjiaer.pharmacy.server.modules.base.entity.CommonLog; + +/** + *

+ * 服务类 + *

+ * + * @author NiuZiYuan + * @since 2025-04-14 + */ +public interface ICommonLogService extends IService { + + + void saveLog(String message, Integer managerId); +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/IManagerUserService.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/IManagerUserService.java new file mode 100644 index 0000000..3331f30 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/IManagerUserService.java @@ -0,0 +1,16 @@ +package com.syjiaer.pharmacy.server.modules.base.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.syjiaer.pharmacy.server.modules.base.entity.ManagerUser; + +/** + *

+ * 服务类 + *

+ * + * @author NiuZiYuan + * @since 2025-02-28 + */ +public interface IManagerUserService extends IService { + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/CommonConfigServiceImpl.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/CommonConfigServiceImpl.java new file mode 100644 index 0000000..187d581 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/CommonConfigServiceImpl.java @@ -0,0 +1,20 @@ +package com.syjiaer.pharmacy.server.modules.base.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.syjiaer.pharmacy.server.modules.base.entity.CommonConfig; +import com.syjiaer.pharmacy.server.modules.base.mapper.CommonConfigMapper; +import com.syjiaer.pharmacy.server.modules.base.service.ICommonConfigService; +import org.springframework.stereotype.Service; + +/** + *

+ * 服务实现类 + *

+ * + * @author NiuZiYuan + * @since 2025-02-24 + */ +@Service +public class CommonConfigServiceImpl extends ServiceImpl implements ICommonConfigService { + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/CommonLogServiceImpl.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/CommonLogServiceImpl.java new file mode 100644 index 0000000..588201e --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/CommonLogServiceImpl.java @@ -0,0 +1,30 @@ +package com.syjiaer.pharmacy.server.modules.base.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.syjiaer.pharmacy.server.modules.base.entity.CommonLog; +import com.syjiaer.pharmacy.server.modules.base.mapper.CommonLogMapper; +import com.syjiaer.pharmacy.server.modules.base.service.ICommonLogService; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; + +/** + *

+ * 服务实现类 + *

+ * + * @author NiuZiYuan + * @since 2025-04-14 + */ +@Service +public class CommonLogServiceImpl extends ServiceImpl implements ICommonLogService { + + @Override + public void saveLog(String message, Integer managerId) { + CommonLog commonLog = new CommonLog(); + commonLog.setMessage(message); + commonLog.setManagerId(managerId); + commonLog.setCreateDatetime(LocalDateTime.now()); + save(commonLog); + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/ManagerUserServiceImpl.java b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/ManagerUserServiceImpl.java new file mode 100644 index 0000000..1c84823 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/base/service/impl/ManagerUserServiceImpl.java @@ -0,0 +1,20 @@ +package com.syjiaer.pharmacy.server.modules.base.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.syjiaer.pharmacy.server.modules.base.entity.ManagerUser; +import com.syjiaer.pharmacy.server.modules.base.mapper.ManagerUserMapper; +import com.syjiaer.pharmacy.server.modules.base.service.IManagerUserService; +import org.springframework.stereotype.Service; + +/** + *

+ * 服务实现类 + *

+ * + * @author NiuZiYuan + * @since 2025-02-28 + */ +@Service +public class ManagerUserServiceImpl extends ServiceImpl implements IManagerUserService { + +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/social/BaseService.java b/src/main/java/com/syjiaer/pharmacy/server/modules/social/BaseService.java new file mode 100644 index 0000000..7437ff4 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/social/BaseService.java @@ -0,0 +1,12 @@ +package com.syjiaer.pharmacy.server.modules.social; + +import com.syjiaer.pharmacy.server.common.util.InfoUtil; +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class BaseService { + @Autowired + private InfoUtil infoUtil; + public void commonLog(String message){ + + } +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/social/entity/SocialDirectory.java b/src/main/java/com/syjiaer/pharmacy/server/modules/social/entity/SocialDirectory.java new file mode 100644 index 0000000..f0adc44 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/social/entity/SocialDirectory.java @@ -0,0 +1,59 @@ +package com.syjiaer.pharmacy.server.modules.social.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.Serializable; +import java.time.LocalDateTime; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import lombok.experimental.Accessors; +/** + *

+ * 医保目录 + *

+ * + * @author NiuZiYuan + * @since 2025-04-16 + */ +@Getter +@Setter +@ToString +@Accessors(chain = true) +@TableName("social_directory") +@ApiModel(value = "SocialDirectory对象", description = "医保目录") +public class SocialDirectory implements Serializable { + + private static final long serialVersionUID = 1L; + + @ApiModelProperty("主键") + private String id; + + @ApiModelProperty("医保目录编码") + private String code; + + @ApiModelProperty("名称") + private String name; + + @ApiModelProperty("检索关键词") + private String keyword; + + @ApiModelProperty("类型") + private Integer type; + + @ApiModelProperty("生产企业") + private String producer; + + @ApiModelProperty("数据创建时间") + private LocalDateTime createDatetime; + + @ApiModelProperty("数据更新时间") + private LocalDateTime updateDatetime; + + @ApiModelProperty("版本名称") + private String versionName; + + @ApiModelProperty("json处理后的数据") + private String data; +} diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/social/mapper/SocialDirectoryMapper.java b/src/main/java/com/syjiaer/pharmacy/server/modules/social/mapper/SocialDirectoryMapper.java new file mode 100644 index 0000000..a5a0117 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/social/mapper/SocialDirectoryMapper.java @@ -0,0 +1,18 @@ +package com.syjiaer.pharmacy.server.modules.social.mapper; + +import com.syjiaer.pharmacy.server.modules.social.entity.SocialDirectory; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + + +/** + *

+ * 医保目录 Mapper 接口 + *

+ * + * @author NiuZiYuan + * @since 2025-04-16 + */ +public interface SocialDirectoryMapper extends BaseMapper { + +} + diff --git a/src/main/java/com/syjiaer/pharmacy/server/modules/social/service/SocialDirectoryService.java b/src/main/java/com/syjiaer/pharmacy/server/modules/social/service/SocialDirectoryService.java new file mode 100644 index 0000000..7dfb046 --- /dev/null +++ b/src/main/java/com/syjiaer/pharmacy/server/modules/social/service/SocialDirectoryService.java @@ -0,0 +1,10 @@ +package com.syjiaer.pharmacy.server.modules.social.service; + +import com.syjiaer.pharmacy.server.modules.social.BaseService; +import org.springframework.stereotype.Service; + +@Service +public class SocialDirectoryService extends BaseService { + + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..2101933 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,28 @@ +spring: + application: + name: server + datasource: + driver-class-name: org.postgresql.Driver + url: jdbc:postgresql://dev.jizhiweb.cn:15321/syjiaer_pharmacy + username: postgres + password: i7L0BS91pADGuy7z + hikari: + maximum-pool-size: 10 + minimum-idle: 5 + idle-timeout: 300000 + max-lifetime: 1800000 + connection-timeout: 30000 + leak-detection-threshold: 60000 + initialization-fail-timeout: 60000 + keepalive-time: 30000 + config: + import: optional:classpath:developer-config.yml +server: + port: 8080 +common: + isdev: true +jwt: + secret: Lrhcnqby4UiFnFqQIWGp8051odVDtqEHaMeDvdzwGhsUPa2nEUAPrlPHTKaABWoM + expiration: 86400 +mybatis-plus: + mapper-locations: classpath*:xml/*.xml \ No newline at end of file diff --git a/src/main/resources/developer-config.yml b/src/main/resources/developer-config.yml new file mode 100644 index 0000000..a5caed1 --- /dev/null +++ b/src/main/resources/developer-config.yml @@ -0,0 +1,3 @@ +mybatis-plus: + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl \ No newline at end of file diff --git a/src/main/resources/xml/SocialDirectoryMapper.xml b/src/main/resources/xml/SocialDirectoryMapper.xml new file mode 100644 index 0000000..57cdcb9 --- /dev/null +++ b/src/main/resources/xml/SocialDirectoryMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/test/java/com/syjiaer/pharmacy/server/ServerApplicationTests.java b/src/test/java/com/syjiaer/pharmacy/server/ServerApplicationTests.java new file mode 100644 index 0000000..394e2b8 --- /dev/null +++ b/src/test/java/com/syjiaer/pharmacy/server/ServerApplicationTests.java @@ -0,0 +1,13 @@ +package com.syjiaer.pharmacy.server; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ServerApplicationTests { + + @Test + void contextLoads() { + } + +}