commit 401b61eddb75577c24fec7707f3a9d918f1f5226 Author: xclele Date: Tue Jan 21 10:01:55 2025 +0800 first commit 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/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..4868c95 --- /dev/null +++ b/pom.xml @@ -0,0 +1,108 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.1.3 + + + com.xclele + big-event + 0.0.1-SNAPSHOT + big-event + big-event + + + + + + + + + + + + + + + 17 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 3.0.0 + + + + + com.mysql + mysql-connector-j + + + + org.projectlombok + lombok + + + + org.hibernate.validator + hibernate-validator + 8.0.0.Final + + + + jakarta.platform + jakarta.jakartaee-api + 9.1.0 + provided + + + + org.springframework.boot + spring-boot-starter-validation + + + + + com.auth0 + java-jwt + 4.4.0 + + + + + org.springframework.boot + spring-boot-starter-test + + + + com.github.pagehelper + pagehelper-spring-boot-starter + 1.4.6 + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 3.1.3 + + + + + diff --git a/src/main/java/com/xclele/bigevent/BigEventApplication.java b/src/main/java/com/xclele/bigevent/BigEventApplication.java new file mode 100644 index 0000000..921e820 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/BigEventApplication.java @@ -0,0 +1,13 @@ +package com.xclele.bigevent; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BigEventApplication { + + public static void main(String[] args) { + SpringApplication.run(BigEventApplication.class, args); + } + +} diff --git a/src/main/java/com/xclele/bigevent/anno/State.java b/src/main/java/com/xclele/bigevent/anno/State.java new file mode 100644 index 0000000..82c44a8 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/anno/State.java @@ -0,0 +1,28 @@ +package com.xclele.bigevent.anno; + +import com.xclele.bigevent.validation.StateValidation; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; +import jakarta.validation.constraints.NotEmpty; + +import java.lang.annotation.Documented; +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Documented//元注解 +@Target({ FIELD})//元注解 +@Retention(RUNTIME)//元注解 +@Constraint(validatedBy = { StateValidation.class})//指定提供校验规则的类 +public @interface State { + //提供校验失败后的提示信息 + String message() default "state参数的值只能是已发布或者草稿"; + //指定分组 + Class[] groups() default { }; + //负载 获取到State注解的附加信息 + Class[] payload() default { }; +} diff --git a/src/main/java/com/xclele/bigevent/config/WebConfig.java b/src/main/java/com/xclele/bigevent/config/WebConfig.java new file mode 100644 index 0000000..664fad8 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/config/WebConfig.java @@ -0,0 +1,19 @@ +package com.xclele.bigevent.config; + +import com.xclele.bigevent.interceptors.LoginInterceptor; +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 WebConfig implements WebMvcConfigurer { + + @Autowired + private LoginInterceptor loginInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login", "/user/register"); + } +} diff --git a/src/main/java/com/xclele/bigevent/controller/ArticleController.java b/src/main/java/com/xclele/bigevent/controller/ArticleController.java new file mode 100644 index 0000000..3cf36dc --- /dev/null +++ b/src/main/java/com/xclele/bigevent/controller/ArticleController.java @@ -0,0 +1,39 @@ +package com.xclele.bigevent.controller; + +import com.xclele.bigevent.pojo.Article; +import com.xclele.bigevent.pojo.PageBean; +import com.xclele.bigevent.pojo.Result; +import com.xclele.bigevent.service.ArticleService; +import com.xclele.bigevent.utils.JwtUtil; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +@RestController +@RequestMapping("/article") +public class ArticleController { + + @Autowired + private ArticleService articleService; + + @PostMapping + public Result add(@RequestBody Article article) { + articleService.add(article); + + return Result.success(); + } + + @GetMapping + public Result> list( + Integer pageNum, + Integer pageSize, + @RequestParam(required = false) Integer categoryId, + @RequestParam(required = false) String state + ) { + PageBean
pb = articleService.list(pageNum, pageSize, categoryId, state); + return Result.success(pb); + } + +} diff --git a/src/main/java/com/xclele/bigevent/controller/CategoryController.java b/src/main/java/com/xclele/bigevent/controller/CategoryController.java new file mode 100644 index 0000000..84a31cd --- /dev/null +++ b/src/main/java/com/xclele/bigevent/controller/CategoryController.java @@ -0,0 +1,50 @@ +package com.xclele.bigevent.controller; + +import com.xclele.bigevent.pojo.Category; +import com.xclele.bigevent.pojo.Result; +import com.xclele.bigevent.service.CategoryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/category") +public class CategoryController { + + @Autowired + private CategoryService categoryService; + + //校验添加组 + @PostMapping + public Result add(@RequestBody @Validated(Category.Add.class) Category category){ + categoryService.add(category); + return Result.success(); + } + + @GetMapping + public Result> list(){ + List cs = categoryService.list(); + return Result.success(cs); + } + + @GetMapping("/detail") + public Result detail(@RequestParam Integer id){ + Category c = categoryService.findById(id); + return Result.success(c); + } + + @PutMapping + public Result update(@RequestBody @Validated(Category.Update.class) Category category){ + categoryService.update(category); + return Result.success(); + } + + //删除 + @DeleteMapping + public Result delete(@RequestParam Integer id){ + categoryService.deleteById(id); + return Result.success(); + } +} diff --git a/src/main/java/com/xclele/bigevent/controller/FileUploadController.java b/src/main/java/com/xclele/bigevent/controller/FileUploadController.java new file mode 100644 index 0000000..a4df1e3 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/controller/FileUploadController.java @@ -0,0 +1,20 @@ +package com.xclele.bigevent.controller; + +import com.xclele.bigevent.pojo.Result; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; + +@RestController +public class FileUploadController { + + @PostMapping("/upload") + public Result upload(MultipartFile file) throws IOException { + String originalFilename = file.getOriginalFilename(); + file.transferTo(new File("D:\\" + originalFilename)); + return Result.success("url访问地址。。。"); + } +} diff --git a/src/main/java/com/xclele/bigevent/controller/UserController.java b/src/main/java/com/xclele/bigevent/controller/UserController.java new file mode 100644 index 0000000..5de276f --- /dev/null +++ b/src/main/java/com/xclele/bigevent/controller/UserController.java @@ -0,0 +1,134 @@ +package com.xclele.bigevent.controller; + +import com.xclele.bigevent.pojo.Result; +import com.xclele.bigevent.pojo.User; +import com.xclele.bigevent.service.UserService; +import com.xclele.bigevent.utils.JwtUtil; +import com.xclele.bigevent.utils.Md5Util; +import com.xclele.bigevent.utils.ThreadLocalUtil; +import jakarta.validation.constraints.Pattern; +import jdk.dynalink.Operation; +import org.hibernate.validator.constraints.URL; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.util.StringUtils; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@RestController +@RequestMapping("/user") +@Validated +public class UserController { + + @Autowired + private UserService userService; + @Autowired + private StringRedisTemplate stringRedisTemplate; + + @PostMapping("/register") + public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, String password) { + //@Pattern用来校验参数 + //search for users + User u = userService.findByUsername(username); + if (u == null) { + // No existing + userService.register(username, password); + return Result.success(); + } else { + // Exists + return Result.error("Username already exists"); + } + + } + + @PostMapping("/login") + public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, String password) { + //@Pattern用来校验参数 + //search for users + User loginUsr = userService.findByUsername(username); + if (loginUsr == null) { + // No existing + return Result.error("Username does not exist"); + } + + // check password + if (Md5Util.getMD5String(password).equals(loginUsr.getPassword())){ + Map claims = new HashMap<>(); + claims.put("id",loginUsr.getId()); + claims.put("username",loginUsr.getUsername()); + String token = JwtUtil.genToken(claims); + //把token存到redis + ValueOperations operations = stringRedisTemplate.opsForValue(); + operations.set(token, token, 15, TimeUnit.MINUTES); + + return Result.success(token); + } + + return Result.error("Password error"); + + } + + @GetMapping("/userinfo") + public Result userInfo(/*@RequestHeader(name="Authorization") String token*/) { + //根据用户名查询用户 +// Map map = JwtUtil.parseToken(token); +// String username = (String) map.get("username"); + Map map = ThreadLocalUtil.get(); + String username = (String) map.get("username"); + + User user = userService.findByUsername(username); + return Result.success(user); + } + + @PutMapping("/update") + public Result update(@RequestBody @Validated User user){ + userService.update(user); + return Result.success(); + } + + @PatchMapping("/updateavatar") + public Result updateAvatar(@RequestParam @URL String avatarUrl){ + userService.updateAvatar(avatarUrl); + return Result.success(); + } + + @PatchMapping("/updatePwd") + public Result updatePwd(@RequestBody Map params, @RequestHeader("Authorization") String token){ + String oldPwd = params.get("old_pwd"); + String newPwd = params.get("new_pwd"); + String confirmPwd = params.get("re_pwd"); + + if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(confirmPwd)){ + return Result.error("Please enter all fields"); + }; + + //原密码是否匹配 + Map map = ThreadLocalUtil.get(); + String username = (String) map.get("username"); + User loginUser = userService.findByUsername(username); + + if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){ + return Result.error("old Password error"); + }; + + //newpwd和confirmPwd是否一致 + if (!newPwd.equals(confirmPwd)){ + return Result.error("new Password and confirm Password are inconsistent"); + }; + + //调用service实现更新 + userService.updatePwd(newPwd); + //删除redis里面旧的token + ValueOperations operations = stringRedisTemplate.opsForValue(); + operations.getOperations().delete(token); + + return Result.success(); + } + + +} diff --git a/src/main/java/com/xclele/bigevent/exception/GlobalExceptionHandler.java b/src/main/java/com/xclele/bigevent/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..2bcbba3 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/exception/GlobalExceptionHandler.java @@ -0,0 +1,16 @@ +package com.xclele.bigevent.exception; + +import com.xclele.bigevent.pojo.Result; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(Exception.class) + public Result handleException(Exception e){ + e.printStackTrace(); + return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "System error"); + } +} diff --git a/src/main/java/com/xclele/bigevent/interceptors/LoginInterceptor.java b/src/main/java/com/xclele/bigevent/interceptors/LoginInterceptor.java new file mode 100644 index 0000000..5dd4911 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/interceptors/LoginInterceptor.java @@ -0,0 +1,53 @@ +package com.xclele.bigevent.interceptors; + +import com.xclele.bigevent.pojo.Result; +import com.xclele.bigevent.utils.JwtUtil; +import com.xclele.bigevent.utils.ThreadLocalUtil; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import java.util.Map; + +@Component +public class LoginInterceptor implements HandlerInterceptor { + + @Autowired + private StringRedisTemplate stringRedisTemplate; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + //validate token + String token = request.getHeader("Authorization"); + + try { + //从redis里面找到相同的令牌 + ValueOperations operations = stringRedisTemplate.opsForValue(); + String redisToken = operations.get(token); + if (redisToken == null) { + //如果得到的值是nil,说明已经过期了 + throw new RuntimeException(); + } + + Map claims = JwtUtil.parseToken(token); + + ThreadLocalUtil.set(claims); + //放行 + return true; + } catch (Exception e) { + response.setStatus(401); + //拦截 + return false; + } + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + //清空threadlocal里面的数据,避免内存泄漏 + ThreadLocalUtil.remove(); + } +} diff --git a/src/main/java/com/xclele/bigevent/mapper/ArticleMapper.java b/src/main/java/com/xclele/bigevent/mapper/ArticleMapper.java new file mode 100644 index 0000000..8174ba1 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/mapper/ArticleMapper.java @@ -0,0 +1,18 @@ +package com.xclele.bigevent.mapper; + +import com.xclele.bigevent.pojo.Article; +import org.apache.ibatis.annotations.Insert; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +@Mapper +public interface ArticleMapper { + + @Insert("insert into article(title,content,cover_img,state,category_id,create_user,create_time,update_time) "+ + "values(#{title},#{content},#{coverImg},#{state},#{categoryId},#{createUser},#{createTime},#{updateTime})") + void add(Article article); + + + List
list(Integer userId, Integer categoryId, String state); +} diff --git a/src/main/java/com/xclele/bigevent/mapper/CategoryMapper.java b/src/main/java/com/xclele/bigevent/mapper/CategoryMapper.java new file mode 100644 index 0000000..7aeed69 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/mapper/CategoryMapper.java @@ -0,0 +1,26 @@ +package com.xclele.bigevent.mapper; + +import com.xclele.bigevent.pojo.Category; +import org.apache.ibatis.annotations.*; + +import java.util.List; + +@Mapper +public interface CategoryMapper { + + @Insert("insert into category(category_name,category_alias,create_user,create_time,update_time) " + + "values(#{categoryName},#{categoryAlias},#{createUser},#{createTime},#{updateTime})") + void add(Category category); + + @Select("select * from category where create_user=#{userId} order by create_time desc") + List list(Integer userId); + + @Select("select * from category where id=#{id}") + Category findById(Integer userId); + + @Update("update category set category_name=#{categoryName},category_alias=#{categoryAlias},update_time=#{updateTime} where id=#{id}") + void update(Category category); + + @Delete("delete from category where id=#{id}") + void deleteById(Integer id); +} diff --git a/src/main/java/com/xclele/bigevent/mapper/UserMapper.java b/src/main/java/com/xclele/bigevent/mapper/UserMapper.java new file mode 100644 index 0000000..8f1da16 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/mapper/UserMapper.java @@ -0,0 +1,27 @@ +package com.xclele.bigevent.mapper; + +import com.xclele.bigevent.pojo.User; +import org.apache.ibatis.annotations.Insert; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +@Mapper +public interface UserMapper { + + @Select("select * from user where username=#{username}") + User findByUsername(String username); + + @Insert("insert into user(username,password,create_time,update_time)"+ + " values(#{username},#{password},now(),now())") + void add(String username, String password); + + @Update("update user set nickname=#{nickname},email=#{email},update_time=#{updateTime} where id=#{id}") + void update(User user); + + @Update("update user set user_pic=#{avatarUrl},update_time=now() where id=#{id}") + void updateAvatar(String avatarUrl,Integer id); + + @Update("update user set password=#{md5String},update_time=now() where id=#{id}") + void updatePwd(String md5String, Integer id); +} diff --git a/src/main/java/com/xclele/bigevent/pojo/Article.java b/src/main/java/com/xclele/bigevent/pojo/Article.java new file mode 100644 index 0000000..064348c --- /dev/null +++ b/src/main/java/com/xclele/bigevent/pojo/Article.java @@ -0,0 +1,31 @@ +package com.xclele.bigevent.pojo; + + +import com.xclele.bigevent.anno.State; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import lombok.Data; +import org.hibernate.validator.constraints.URL; + +import java.time.LocalDateTime; +@Data +public class Article { + private Integer id;//主键ID + @NotEmpty + @Pattern(regexp = "^\\S{1,10}$") + private String title;//文章标题 + @NotEmpty + private String content;//文章内容 + @NotEmpty + @URL + private String coverImg;//封面图像 + + @State + private String state;//发布状态 已发布|草稿 + @NotNull + private Integer categoryId;//文章分类id + private Integer createUser;//创建人ID + private LocalDateTime createTime;//创建时间 + private LocalDateTime updateTime;//更新时间 +} diff --git a/src/main/java/com/xclele/bigevent/pojo/Category.java b/src/main/java/com/xclele/bigevent/pojo/Category.java new file mode 100644 index 0000000..5c21877 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/pojo/Category.java @@ -0,0 +1,35 @@ +package com.xclele.bigevent.pojo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.groups.Default; +import lombok.Data; + +import java.time.LocalDateTime; +@Data +public class Category { + @NotNull(groups = Update.class) + private Integer id;//主键ID + @NotEmpty + private String categoryName;//分类名称 + @NotEmpty + private String categoryAlias;//分类别名 + private Integer createUser;//创建人ID + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime createTime;//创建时间 + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime updateTime;//更新时间 + + //如果说某个校验项没有指定分组,默认属于Default分组 + //分组之间可以继承, A extends B 那么A中拥有B中所有的校验项 + + + public interface Add extends Default { + + } + + public interface Update extends Default{ + + } +} diff --git a/src/main/java/com/xclele/bigevent/pojo/PageBean.java b/src/main/java/com/xclele/bigevent/pojo/PageBean.java new file mode 100644 index 0000000..c4fe08b --- /dev/null +++ b/src/main/java/com/xclele/bigevent/pojo/PageBean.java @@ -0,0 +1,16 @@ +package com.xclele.bigevent.pojo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; + +//分页返回结果对象 +@Data +@NoArgsConstructor +@AllArgsConstructor +public class PageBean { + private Long total;//总条数 + private List items;//当前页数据集合 +} diff --git a/src/main/java/com/xclele/bigevent/pojo/Result.java b/src/main/java/com/xclele/bigevent/pojo/Result.java new file mode 100644 index 0000000..5b58c02 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/pojo/Result.java @@ -0,0 +1,30 @@ +package com.xclele.bigevent.pojo; + + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +//统一响应结果 +@NoArgsConstructor +@AllArgsConstructor +@Data +public class Result { + private Integer code;//业务状态码 0-成功 1-失败 + private String message;//提示信息 + private T data;//响应数据 + + //快速返回操作成功响应结果(带响应数据) + public static Result success(E data) { + return new Result<>(0, "操作成功", data); + } + + //快速返回操作成功响应结果 + public static Result success() { + return new Result(0, "操作成功", null); + } + + public static Result error(String message) { + return new Result(1, message, null); + } +} diff --git a/src/main/java/com/xclele/bigevent/pojo/User.java b/src/main/java/com/xclele/bigevent/pojo/User.java new file mode 100644 index 0000000..f479959 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/pojo/User.java @@ -0,0 +1,34 @@ +package com.xclele.bigevent.pojo; + + + +import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import lombok.Data; + +import java.time.LocalDateTime; +//lombok 在编译阶段,为实体类自动生成setter getter toString +// pom文件中引入依赖 在实体类上添加注解 +@Data +public class User { + @NotNull + private Integer id;//主键ID + private String username;//用户名 + @JsonIgnore//让springmvc把当前对象转换成json字符串的时候,忽略password,最终的json字符串中就没有password这个属性了 + private String password;//密码 + + + @NotEmpty + @Pattern(regexp = "^\\S{1,10}$") + private String nickname;//昵称 + + @NotEmpty + @Email + private String email;//邮箱 + private String userPic;//用户头像地址 + private LocalDateTime createTime;//创建时间 + private LocalDateTime updateTime;//更新时间 +} diff --git a/src/main/java/com/xclele/bigevent/service/ArticleService.java b/src/main/java/com/xclele/bigevent/service/ArticleService.java new file mode 100644 index 0000000..9d68ceb --- /dev/null +++ b/src/main/java/com/xclele/bigevent/service/ArticleService.java @@ -0,0 +1,13 @@ +package com.xclele.bigevent.service; + +import com.xclele.bigevent.pojo.Article; +import com.xclele.bigevent.pojo.PageBean; +import com.xclele.bigevent.pojo.Result; +import org.springframework.web.bind.annotation.RequestBody; + +public interface ArticleService { + + public void add(@RequestBody Article article); + + PageBean
list(Integer pageNum, Integer pageSize, Integer categoryId, String state); +} diff --git a/src/main/java/com/xclele/bigevent/service/CategoryService.java b/src/main/java/com/xclele/bigevent/service/CategoryService.java new file mode 100644 index 0000000..2ec278c --- /dev/null +++ b/src/main/java/com/xclele/bigevent/service/CategoryService.java @@ -0,0 +1,18 @@ +package com.xclele.bigevent.service; + +import com.xclele.bigevent.pojo.Category; + +import java.util.List; + +public interface CategoryService { + void add(Category category); + + //列表查询 + List list(); + + Category findById(Integer id); + + void update(Category category); + + void deleteById(Integer id); +} diff --git a/src/main/java/com/xclele/bigevent/service/UserService.java b/src/main/java/com/xclele/bigevent/service/UserService.java new file mode 100644 index 0000000..d806591 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/service/UserService.java @@ -0,0 +1,18 @@ +package com.xclele.bigevent.service; + +import com.xclele.bigevent.pojo.User; + + +public interface UserService { + // search by username + User findByUsername(String username); + + // register + void register(String username, String password); + + void update(User user); + + void updateAvatar(String avatarUrl); + + void updatePwd(String newPwd); +} diff --git a/src/main/java/com/xclele/bigevent/service/impl/ArticleServiceImpl.java b/src/main/java/com/xclele/bigevent/service/impl/ArticleServiceImpl.java new file mode 100644 index 0000000..953f6c7 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/service/impl/ArticleServiceImpl.java @@ -0,0 +1,58 @@ +package com.xclele.bigevent.service.impl; + +import com.github.pagehelper.Page; +import com.github.pagehelper.PageHelper; +import com.xclele.bigevent.mapper.ArticleMapper; +import com.xclele.bigevent.pojo.Article; +import com.xclele.bigevent.pojo.PageBean; +import com.xclele.bigevent.pojo.Result; +import com.xclele.bigevent.service.ArticleService; +import com.xclele.bigevent.utils.ThreadLocalUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.RequestBody; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +@Service +public class ArticleServiceImpl implements ArticleService { + + @Autowired + private ArticleMapper articleMapper; + + @Override + public void add(@RequestBody Article article) { + article.setCreateTime(LocalDateTime.now()); + article.setUpdateTime(LocalDateTime.now()); + + Map map = ThreadLocalUtil.get(); + Integer userId = (Integer) map.get("id"); + article.setCreateUser(userId); + + articleMapper.add(article); + } + + @Override + public PageBean
list(Integer pageNum, Integer pageSize, Integer categoryId, String state) { + //创建pagebean + PageBean
pb = new PageBean<>(); + + //开启分类查询pagehelper + PageHelper.startPage(pageNum, pageSize); + + //用Mapper查询 + Map map = ThreadLocalUtil.get(); + Integer userId = (Integer) map.get("id"); + List
as = articleMapper.list(userId, categoryId, state); + + Page
p = (Page
) as; + + pb.setTotal(p.getTotal()); + pb.setItems(p.getResult()); + + return pb; + } + +} diff --git a/src/main/java/com/xclele/bigevent/service/impl/CategoryServiceImpl.java b/src/main/java/com/xclele/bigevent/service/impl/CategoryServiceImpl.java new file mode 100644 index 0000000..5e3159b --- /dev/null +++ b/src/main/java/com/xclele/bigevent/service/impl/CategoryServiceImpl.java @@ -0,0 +1,55 @@ +package com.xclele.bigevent.service.impl; + +import com.xclele.bigevent.mapper.CategoryMapper; +import com.xclele.bigevent.pojo.Category; +import com.xclele.bigevent.service.CategoryService; +import com.xclele.bigevent.utils.ThreadLocalUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +@Service +public class CategoryServiceImpl implements CategoryService { + + @Autowired + private CategoryMapper categoryMapper; + + @Override + public void add(Category category) { + category.setCreateTime(LocalDateTime.now()); + category.setUpdateTime(LocalDateTime.now()); + + Map map = ThreadLocalUtil.get(); + Integer userId = (Integer) map.get("id"); + category.setCreateUser(userId); + categoryMapper.add(category); + } + + @Override + public List list() { + Map map = ThreadLocalUtil.get(); + Integer userId = (Integer) map.get("id"); + + return categoryMapper.list(userId); + } + + @Override + public Category findById(Integer id) { + Category c = categoryMapper.findById(id); + return c; + } + + @Override + public void update(Category category) { + category.setUpdateTime(LocalDateTime.now()); + categoryMapper.update(category); + } + + @Override + public void deleteById(Integer id) { + categoryMapper.deleteById(id); + } +} diff --git a/src/main/java/com/xclele/bigevent/service/impl/UserServiceImpl.java b/src/main/java/com/xclele/bigevent/service/impl/UserServiceImpl.java new file mode 100644 index 0000000..09ee1f1 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/service/impl/UserServiceImpl.java @@ -0,0 +1,56 @@ +package com.xclele.bigevent.service.impl; + +import com.xclele.bigevent.mapper.UserMapper; +import com.xclele.bigevent.pojo.User; +import com.xclele.bigevent.service.UserService; +import com.xclele.bigevent.utils.Md5Util; +import com.xclele.bigevent.utils.ThreadLocalUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.time.LocalDateTime; +import java.util.Map; + +@Service +public class UserServiceImpl implements UserService { + + @Autowired + private UserMapper userMapper; + + @Override + public User findByUsername(String username) { + User u = userMapper.findByUsername(username); + return u; + } + + @Override + public void register(String username, String password) { + //password encrypt + String md5String = Md5Util.getMD5String(password); + //add user + userMapper.add(username, md5String); + } + + @Override + public void update(User user) { + user.setUpdateTime(LocalDateTime.now()); + userMapper.update(user); + } + + @Override + public void updateAvatar(String avatarUrl) { + Map map = ThreadLocalUtil.get(); + Integer id = (Integer) map.get("id"); + userMapper.updateAvatar(avatarUrl,id); + } + + @Override + public void updatePwd(String newPwd) { + Map map = ThreadLocalUtil.get(); + Integer id = (Integer) map.get("id"); + + String md5String = Md5Util.getMD5String(newPwd); + userMapper.updatePwd(md5String,id); + } + +} diff --git a/src/main/java/com/xclele/bigevent/utils/JwtUtil.java b/src/main/java/com/xclele/bigevent/utils/JwtUtil.java new file mode 100644 index 0000000..b642780 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/utils/JwtUtil.java @@ -0,0 +1,30 @@ +package com.xclele.bigevent.utils; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.algorithms.Algorithm; + +import java.util.Date; +import java.util.Map; + +public class JwtUtil { + + private static final String KEY = "itheima"; + + //接收业务数据,生成token并返回 + public static String genToken(Map claims) { + return JWT.create() + .withClaim("claims", claims) + .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 )) + .sign(Algorithm.HMAC256(KEY)); + } + + //接收token,验证token,并返回业务数据 + public static Map parseToken(String token) { + return JWT.require(Algorithm.HMAC256(KEY)) + .build() + .verify(token) + .getClaim("claims") + .asMap(); + } + +} diff --git a/src/main/java/com/xclele/bigevent/utils/Md5Util.java b/src/main/java/com/xclele/bigevent/utils/Md5Util.java new file mode 100644 index 0000000..93acf79 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/utils/Md5Util.java @@ -0,0 +1,73 @@ +package com.xclele.bigevent.utils; + + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class Md5Util { + /** + * 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合 + */ + protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + + protected static MessageDigest messagedigest = null; + + static { + try { + messagedigest = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException nsaex) { + System.err.println(Md5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util。"); + nsaex.printStackTrace(); + } + } + + /** + * 生成字符串的md5校验值 + * + * @param s + * @return + */ + public static String getMD5String(String s) { + return getMD5String(s.getBytes()); + } + + /** + * 判断字符串的md5校验码是否与一个已知的md5码相匹配 + * + * @param password 要校验的字符串 + * @param md5PwdStr 已知的md5校验码 + * @return + */ + public static boolean checkPassword(String password, String md5PwdStr) { + String s = getMD5String(password); + return s.equals(md5PwdStr); + } + + + public static String getMD5String(byte[] bytes) { + messagedigest.update(bytes); + return bufferToHex(messagedigest.digest()); + } + + private static String bufferToHex(byte bytes[]) { + return bufferToHex(bytes, 0, bytes.length); + } + + private static String bufferToHex(byte bytes[], int m, int n) { + StringBuffer stringbuffer = new StringBuffer(2 * n); + int k = m + n; + for (int l = m; l < k; l++) { + appendHexPair(bytes[l], stringbuffer); + } + return stringbuffer.toString(); + } + + private static void appendHexPair(byte bt, StringBuffer stringbuffer) { + char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>> + // 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同 + char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换 + stringbuffer.append(c0); + stringbuffer.append(c1); + } + +} diff --git a/src/main/java/com/xclele/bigevent/utils/ThreadLocalUtil.java b/src/main/java/com/xclele/bigevent/utils/ThreadLocalUtil.java new file mode 100644 index 0000000..4d79518 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/utils/ThreadLocalUtil.java @@ -0,0 +1,29 @@ +package com.xclele.bigevent.utils; + +import java.util.HashMap; +import java.util.Map; + +/** + * ThreadLocal 工具类 + */ +@SuppressWarnings("all") +public class ThreadLocalUtil { + //提供ThreadLocal对象, + private static final ThreadLocal THREAD_LOCAL = new ThreadLocal(); + + //根据键获取值 + public static T get(){ + return (T) THREAD_LOCAL.get(); + } + + //存储键值对 + public static void set(Object value){ + THREAD_LOCAL.set(value); + } + + + //清除ThreadLocal 防止内存泄漏 + public static void remove(){ + THREAD_LOCAL.remove(); + } +} diff --git a/src/main/java/com/xclele/bigevent/validation/StateValidation.java b/src/main/java/com/xclele/bigevent/validation/StateValidation.java new file mode 100644 index 0000000..b7c0e93 --- /dev/null +++ b/src/main/java/com/xclele/bigevent/validation/StateValidation.java @@ -0,0 +1,26 @@ +package com.xclele.bigevent.validation; + +import com.xclele.bigevent.anno.State; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; + +public class StateValidation implements ConstraintValidator { + /** + * + * @param value 将来要校验的数据 + * @param context context in which the constraint is evaluated + * + * @return 如果返回false,则校验不通过,如果返回true,则校验通过 + */ + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + //提供校验规则 + if (value == null){ + return false; + } + if (value.equals("已发布") || value.equals("草稿")){ + return true; + } + return false; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..774a7a5 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,17 @@ +spring: + datasource: + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/big_event + username: root + password: Lele1234 + data: + redis: + host: localhost + port: 6379 + +mybatis: + configuration: + map-underscore-to-camel-case: true #开启驼峰命名和下划线命名的自动转换 + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + + mapper-locations: classpath:mapper/*.xml diff --git a/src/main/resources/mapper/ArticleMapper.xml b/src/main/resources/mapper/ArticleMapper.xml new file mode 100644 index 0000000..813a9ef --- /dev/null +++ b/src/main/resources/mapper/ArticleMapper.xml @@ -0,0 +1,21 @@ + + + + + + \ No newline at end of file diff --git a/src/test/java/com/xclele/bigevent/BigEventApplicationTests.java b/src/test/java/com/xclele/bigevent/BigEventApplicationTests.java new file mode 100644 index 0000000..3e5a0e5 --- /dev/null +++ b/src/test/java/com/xclele/bigevent/BigEventApplicationTests.java @@ -0,0 +1,13 @@ +package com.xclele.bigevent; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class BigEventApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/xclele/bigevent/JwtTest.java b/src/test/java/com/xclele/bigevent/JwtTest.java new file mode 100644 index 0000000..011bbb0 --- /dev/null +++ b/src/test/java/com/xclele/bigevent/JwtTest.java @@ -0,0 +1,46 @@ +package com.xclele.bigevent; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.Claim; +import com.auth0.jwt.interfaces.DecodedJWT; +import org.junit.jupiter.api.Test; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +public class JwtTest { + + public void testGen(){ + Map claims = new HashMap<>(); + claims.put("id",1); + claims.put("username","张三"); + + //生成jwt代码 + String token = JWT.create(). + withClaim("user",claims). + withExpiresAt(new Date(System.currentTimeMillis()+1000*60*20)). + sign(Algorithm.HMAC256("123456"));//添加载荷 + + System.out.println(token); + } + + + public void testParse(){ + String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" + + ".eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3MzUyODQ5OTl9" + + ".tDWyCZnsurokdF4iSw-ispbJIZPZ-rrf9xTbs4qK1kU"; + + JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("123456")).build(); + + DecodedJWT decodedJWT = jwtVerifier.verify(token); + Map claims = decodedJWT.getClaims(); + System.out.println(claims.get("user")); + + // 如果篡改了数据,验证失败 + // 如果token过期,验证失败 + + } +} diff --git a/src/test/java/com/xclele/bigevent/RedisTest.java b/src/test/java/com/xclele/bigevent/RedisTest.java new file mode 100644 index 0000000..623d16e --- /dev/null +++ b/src/test/java/com/xclele/bigevent/RedisTest.java @@ -0,0 +1,31 @@ +package com.xclele.bigevent; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.redis.core.RedisOperations; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.util.concurrent.TimeUnit; + +@SpringBootTest +public class RedisTest { + + @Autowired + private StringRedisTemplate stringRedisTemplate; + + @Test + public void test() { + ValueOperations operations = stringRedisTemplate.opsForValue(); + + operations.set("username", "xclele"); + operations.set("password", "123456", 15, TimeUnit.SECONDS); + } + + @Test + public void testGet() { + ValueOperations operations = stringRedisTemplate.opsForValue(); + System.out.println(operations.get("username")); + } +} diff --git a/src/test/java/com/xclele/bigevent/ThreadLocalTest.java b/src/test/java/com/xclele/bigevent/ThreadLocalTest.java new file mode 100644 index 0000000..6f9ea94 --- /dev/null +++ b/src/test/java/com/xclele/bigevent/ThreadLocalTest.java @@ -0,0 +1,26 @@ +package com.xclele.bigevent; + +import org.junit.jupiter.api.Test; + +public class ThreadLocalTest { + + @Test + public void testThreadLocalSetAndGet(){ + ThreadLocal tl = new ThreadLocal(); + + //start 2 threads + new Thread(()->{ + tl.set("thread1"); + System.out.println(Thread.currentThread().getName()+" "+tl.get()); + System.out.println(Thread.currentThread().getName()+" "+tl.get()); + System.out.println(Thread.currentThread().getName()+" "+tl.get()); + },"线程1").start(); + + new Thread(()->{ + tl.set("thread2"); + System.out.println(Thread.currentThread().getName()+" "+tl.get()); + System.out.println(Thread.currentThread().getName()+" "+tl.get()); + System.out.println(Thread.currentThread().getName()+" "+tl.get()); + },"线程2").start(); + } +}