Commit 5c526ac8 by 涂亚平

start

0 parents
Showing with 4164 additions and 0 deletions
No preview for this file type
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/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/
### VS Code ###
.vscode/
assets/
logs/
\ No newline at end of file
/*
* Copyright 2007-present the original author or authors.
*
* Licensed 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
*
* https://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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
No preview for this file type
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
#!/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
#
# https://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@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 https://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 Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.7.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.zhongzhi</groupId>
<artifactId>zhongzhi</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.8</java.version>
<mybatis-plus.version>3.3.0</mybatis-plus.version>
<generator.version>3.3.2</generator.version>
<swagger2.version>2.9.2</swagger2.version>
<fastjson.version>1.2.58</fastjson.version>
<jhash.version>2.0.0</jhash.version>
<poi-ooxml.version>3.13</poi-ooxml.version>
<dysmsapi.version>1.1.0</dysmsapi.version>
<sdk-core.version>4.0.1</sdk-core.version>
<lang3.version>3.9</lang3.version>
<druid.version>1.1.22</druid.version>
<itext-asian.version>5.2.0</itext-asian.version>
<itextpdf.version>5.4.1</itextpdf.version>
<java-jwt.version>3.10.3</java-jwt.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${generator.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi-ooxml.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>${dysmsapi.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>${sdk-core.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${lang3.version}</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>${itext-asian.version}</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>${itextpdf.version}</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${java-jwt.version}</version>
</dependency>
<!-- 阿里云 对象存储oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.0</version>
</dependency>
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.64</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>central</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<build>
<finalName>template</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
package com.zhongzhi;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@RestController
@MapperScan(basePackages = {"com.zhongzhi.dao"})
@SpringBootApplication
public class ZhongzhiApplication {
public static void main(String[] args) {
SpringApplication.run(ZhongzhiApplication.class, args);
}
}
\ No newline at end of file
package com.zhongzhi.common.configure;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "sms")
public class AliyunSmsProperties {
private String product;
private String domain;
private String accessKeyId;
private String accessKeySecret;
private String cpcode;
private String excode;
private String key;
private String rcsapi;
}
package com.zhongzhi.common.configure;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.zhongzhi.common.handler.MetaHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
/**
* 分页
*
* @return
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDialectType(DbType.MYSQL.getDb());
return page;
}
/**
* 自动填充功能
*
* @return
*/
@Bean
public GlobalConfig globalConfig() {
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setMetaObjectHandler(new MetaHandler());
return globalConfig;
}
}
\ No newline at end of file
package com.zhongzhi.common.configure;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 读取状态码
* </p>
*
* @author DengMin
* @date Created in 2020/08/24
*/
@Component
@ConfigurationProperties(prefix = "c")
@PropertySource(value = "classpath:code.properties", encoding = "UTF-8")
public class RemoteProperties {
private static Map<Integer, String> codeMessage = new HashMap<>();
public static String getMessage(Integer code) {
return codeMessage.get(code);
}
public Map<Integer, String> getCodeMessage() {
return codeMessage;
}
public void setCodeMessage(Map<Integer, String> codeMessage) {
RemoteProperties.codeMessage = codeMessage;
}
}
\ No newline at end of file
package com.zhongzhi.common.configure;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* <p>
* swagger2
* </p>
*
* @author DengMin
* @since 2020/12/8
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.zhongzhi.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(new ApiInfoBuilder()
.title("国泰君安")
.description("接口文档")
.version("1.0")
.build());
}
}
package com.zhongzhi.common.configure;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author: tuyp
* @create: 2020-06-01 16:46
*/
@Component
@Data
@ConfigurationProperties(prefix = "vod")
public class VODConfig {
private String appId;
private String secretId;
private String secretKey;
private String api;
private String region;
private Integer classId;
}
package com.zhongzhi.common.configure;
import com.zhongzhi.common.interceptor.AuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.web.servlet.config.annotation.*;
/**
* @author DengMin
* @date 2020/07/06
**/
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
@Autowired
private AuthenticationInterceptor authenticationInterceptor;
/**
* 跨域支持
*
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.maxAge(3600);
}
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setMaxAge(3600L);
config.addAllowedOrigin("*");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
/**
* Swagger
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
/**
* 鉴权
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor)
.excludePathPatterns("/static/*")
.addPathPatterns("/**");
}
}
\ No newline at end of file
package com.zhongzhi.common.constant;
import lombok.Getter;
@Getter
public enum Code {
USERNAMENOTFOUND(1001, "用户不存在"),
BADCREDENTIALS(1002, "账户或者密码错误"),
ACCOUNTEXPIRED(1003, "账户过期"),
LOCKEDEXCEPTION(1004, "账户已锁定"),
DISABLEDEXCEPTION(1005, "账户已禁用"),
ACCESSDENIED(1006, "无权限访问"),
AUTHENTICATION(1007, "身份验证异常"),
NOHANDLERFOUND(1008, "找不到相应的视图处理器"),
PARAM_INVALID(1009, "参数不合法"),
TOKEN_EXCEPTION(1010, "无效的令牌"),
TOKEN_EXPIRED(1011, "令牌已过期"),
TOKEN_VERIFICATION_FAILED(1012, "令牌验证失败"),
OSS_ERROR(1013, "OSS文件上传异常"),
Network_ERROR(9000, "网络请求失败"),
SERVER_INTERNAL_ERROR(99999, "服务器内部错误"),
;
private final Integer code;
private final String message;
Code(Integer code, String message) {
this.code = code;
this.message = message;
}
}
package com.zhongzhi.common.constant;
/**
* <p>
* 团队成员类型
* </p>
*
* @author DengMin
* @since 2021/6/9
*/
public class MemberType {
/*
团队负责人只能有一个且是项目申请人
*/
public static final String PRINCIPAL = "团队负责人";
public static final String TEAM_MEMBER = "团队成员";
public static final String MENTOR = "指导教师";
}
package com.zhongzhi.common.constant;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PDFCheckBox {
public static String getType(String type, String projectGroup) {
if (StringUtils.isBlank(type) &&
projectGroup.equals(ProjectType.TECHNOLOGY_INNOVATION_GROUP)) {
return "□方案设计类 □模型创意类 □虚拟演示类";
} else if (StringUtils.isBlank(type) &&
projectGroup.equals(ProjectType.CULTURAL_CREATIVE_GROUP)) {
return "□服装与服饰类设计 □视觉传达类 □产品设计类";
}
String[] typeT = {"方案设计类", "模型创意类", "虚拟演示类"};
String typeValue = "";
if (projectGroup.equals(ProjectType.TECHNOLOGY_INNOVATION_GROUP)) {
List<String> typeList = Arrays.stream(typeT).collect(Collectors.toList());
List<String> str = Arrays.stream(type.split(",")).collect(Collectors.toList());
for (String s : typeList) {
if (str.contains(s)) {
typeValue += "■" + s + " ";
} else {
typeValue += "□" + s + " ";
}
}
return typeValue;
} else if (projectGroup.equals(ProjectType.CULTURAL_CREATIVE_GROUP)) {
if (type.equals("服装与服饰类设计")) {
return "■服装与服饰类设计 □视觉传达类 □产品设计类";
} else if (type.equals("视觉传达类")) {
return "□服装与服饰类设计 ■视觉传达类 □产品设计类";
} else if (type.equals("产品设计类")) {
return "□服装与服饰类设计 □视觉传达类 ■产品设计类";
} else {
return "□服装与服饰类设计 □视觉传达类 □产品设计类";
}
}
return "";
}
public static String getRoadshow( String projectGroup) {
if (projectGroup.equals(ProjectType.TECHNOLOGY_INNOVATION_GROUP)) {
return "□模型展示 □数字化演示" +
" □PPT演示 □其他";
} else if (projectGroup.equals(ProjectType.CULTURAL_CREATIVE_GROUP)) {
return "□物化产品展示 □作品模型展示" +
" □数字化演示 □PPT演示 □其他";
}
String[] roadshowT = {"模型展示", "数字化演示", "PPT演示", "其他"};
String[] roadshowC = {"物化产品展示", "作品模型展示", "数字化演示", "PPT演示", "其他"};
// List<String> str = Arrays.stream(roadshow.split(",")).collect(Collectors.toList());
String roadshowValue = "";
if (projectGroup.equals(ProjectType.TECHNOLOGY_INNOVATION_GROUP)) {
List<String> roadshowTList = Arrays.stream(roadshowT).collect(Collectors.toList());
for (String s : roadshowTList) {
// if (str.contains(s)) {
// roadshowValue += "■" + s + " ";
// } else {
// roadshowValue += "□" + s + " ";
// }
}
return roadshowValue;
} else if (projectGroup.equals(ProjectType.CULTURAL_CREATIVE_GROUP)) {
List<String> roadshowCList = Arrays.stream(roadshowC).collect(Collectors.toList());
for (String s : roadshowCList) {
// if (str.contains(s)) {
// roadshowValue += "■" + s + " ";
// } else {
// roadshowValue += "□" + s + " ";
// }
}
return roadshowValue;
}
return "";
}
}
package com.zhongzhi.common.constant;
/**
* <p>
* 平台标识
* </p>
*
* @author DengMin
* @since 2021/6/9
*/
public class Platform {
/*
学生端
*/
public static final String student = "student";
/*
院校端
*/
public static final String school = "school";
/*
中心端
*/
public static final String center = "center";
/*
评审端
*/
public static final String review = "review";
}
package com.zhongzhi.common.constant;
import lombok.Data;
@Data
public class ProjectAssigned {
public static final String ASSIGN_ED = "已分配";
public static final String UN_ASSIGN = "未分配";
}
package com.zhongzhi.common.constant;
public class ProjectProgress {
public static final String REGISTERED = "已注册公司";
public static final String UNREGISTERED = "创意设计阶段";
}
package com.zhongzhi.common.constant;
/**
* <p>
* 项目评审状态
* </p>
*
* @author DengMin
* @since 2021/6/9
*/
public class ProjectReview {
/**
* 评分状态(对于评分)
*/
public static final String SUBMITTED = "已评审";
public static final String TO_SCORE = "待评审";
/**
* 评审状态(对于项目)
*/
public static final String TO_REVIEWED = "待评审";
public static final String ASSIGNED = "已分配";
public static final String UNASSIGNED = "未分配";
public static final String REVIEW = "已评审";
}
package com.zhongzhi.common.constant;
/**
* <p>
* 项目进度
* </p>
*
* @author DengMin
* @since 2021/6/9
*/
public class ProjectSchedule {
//报名阶段
public static final String TO_REVIEW = "待评审";
public static final String REVIEW_ED = "待评审";
// 校内赛
public static final String SCHOOL_REVIEW = "市级初赛项目";
public static final String SEMI_FINAL_REVIEW = "市级复赛项目";
public static final String FINAL_REVIEW = "市级决赛项目";
public static final String PASS = "通过";
public static final String NO_PASS = "不通过";
}
package com.zhongzhi.common.constant;
/**
* <p>
* 项目状态
* </p>
*
* @author DengMin
* @since 2021/6/9
*/
public class ProjectStatus {
public static final String UN_SUBMITTED = "填写中";
public static final String TO_CHECK = "待评审";
public static final String WITHDRAWN = "已撤回";
public static final String SCHOOL_NOT_PASSED = "不予提交市级复赛";
public static final String REGISTER_NOT_PASSED = "报名不通过";
public static final String PRELIMINARY_NOT_PASSED = "不予提交市级初赛";
public static final String REMATCH_WINNING_AWARD = "优胜奖";
public static final String REMATCH_SILVER_AWARD = "二等奖";
public static final String REMATCH_BRONZE_AWARD = "三等奖";
public static final String REMATCH_FINALS_GOLD_AWARD = "一等奖";
public static final String ABANDON = "未通过";
public static final String PASS = "已通过";
}
package com.zhongzhi.common.constant;
/**
* <p>
* 项目组别
* </p>
*
* @author DengMin
* @since 2021/6/9
*/
public class ProjectType {
/**
* 赛道
*/
public static final String MAIN_TRACK = "主赛道";
public static final String SEED_TRACK = "种子赛道";
// public static final String VOCATIONAL = "职教赛道";
/**
* 组别
*/
public static final String TECHNOLOGY_INNOVATION_GROUP = "科技创新";
public static final String CULTURAL_CREATIVE_GROUP = "文化创意";
public static final String VOCATIONAL_GROUP = "高职";
public static final String SECONDARY_GROUP = "中职";
}
package com.zhongzhi.common.constant;
public class SMSTemplate {
/*
项目进度通知
*/
public static final String PROJECT_PROGRESS = "2760175";
/*
项目提交通知
*/
public static final String PROJECT_SUBMIT = "270159";
/*
评审邀请通知 old
*/
public static final String REVIEW_INVITATION_OLD = "2765806";
/**
*
*/
public static final String REVIEW_INVITATION_NEW = "2939771";
/*
撤销评审项目通知
*/
public static final String CANCEL_REVIEW = "229303";
}
package com.zhongzhi.common.constant;
/**
* <p>
* 短信标识
* </p>
*
* @author DengMin
* @since 2021/6/9
*/
public class SmsCode {
/**
* 平台:student(学生端)、school(院校端)、center(中心端)、review(评审端)
*/
public static final String student = "student";
public static final String school = "school";
public static final String center = "center";
public static final String review = "review";
/**
* 行为标识:register(注册标识)、login(登录标识)
*/
public static final String register = "register";
public static final String login = "login";
}
package com.zhongzhi.common.exception;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhongzhi.common.configure.RemoteProperties;
import com.zhongzhi.common.constant.Code;
import com.zhongzhi.common.utils.ResponseData;
import com.zhongzhi.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 自定义异常
*
* @param e
* @return
*/
@ExceptionHandler(value = HttpException.class)
public ResponseVO<T> handlerException(HttpServletRequest request, HttpException e) {
String message = RemoteProperties.getMessage(e.getCode());
if (StringUtils.isBlank(message)) {
message = e.getMessage();
}
String url = request.getRequestURI();
return ResponseData.generateCreatedResponse(e.getCode(), message, url);
}
/**
* 404
*
* @param request
* @return
*/
@ExceptionHandler(value = NoHandlerFoundException.class)
public ResponseVO<T> NoHandlerFoundException(HttpServletRequest request) {
String url = request.getRequestURI();
return ResponseData.generateCreatedResponse(Code.NOHANDLERFOUND.getCode(), Code.NOHANDLERFOUND.getMessage(), url);
}
/**
* 请求方式错误
*
* @param request
* @return
*/
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public ResponseVO<T> HttpRequestMethodNotSupportedException(HttpServletRequest request) {
String url = request.getRequestURI();
return ResponseData.generateCreatedResponse(Code.NOHANDLERFOUND.getCode(), Code.NOHANDLERFOUND.getMessage(), url);
}
/**
* 参数不合法
*
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseVO<T> validateException(MethodArgumentNotValidException e) {
final List<String> errList = new ArrayList<>();
e.getBindingResult().getAllErrors().stream().forEach(x -> {
errList.add(x.getDefaultMessage());
});
return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage(), errList.toString());
}
/**
* JSON 序列化异常
*
* @param e
* @return
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseVO<T> exceptionHandler(HttpMessageNotReadableException e) {
log.error(e.getMessage());
return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage() + ":{" + e.getMessage() + "}");
}
/**
* 校验异常
*
* @param e
* @return
*/
@ExceptionHandler(BindException.class)
public ResponseVO<T> BindException(BindException e) {
final List<String> errList = new ArrayList<>();
e.getBindingResult().getAllErrors().stream().forEach(x -> {
errList.add(x.getDefaultMessage());
});
return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage(), errList.toString());
}
/**
* 服务器内部错误
*
* @return
*/
@ExceptionHandler(value = Exception.class)
public ResponseVO<T> serverInternalError(Exception e, HttpServletRequest request) {
String url = request.getRequestURI();
log.error("path:" + url);
log.error("error:"+ e.getClass());
log.error("error message:"+ e.getLocalizedMessage() + e.getStackTrace()[0] + System.getProperty("line.separator"));
return ResponseData.generateCreatedResponse(Code.SERVER_INTERNAL_ERROR.getCode(), Code.SERVER_INTERNAL_ERROR.getMessage(), url);
}
}
\ No newline at end of file
package com.zhongzhi.common.exception;
import com.zhongzhi.common.configure.RemoteProperties;
/**
* 异常处理
*
* @author DengMin
* @date 2020/08/12
**/
public class HttpException extends RuntimeException {
private Integer code;
private String message;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public HttpException(Integer code) {
super(RemoteProperties.getMessage(code));
String message = RemoteProperties.getMessage(code);
this.message = message;
this.code = code;
}
public HttpException(Integer code, String message) {
this.message = message;
this.code = code;
}
}
package com.zhongzhi.common.generator;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.zhongzhi.model.base.BaseModel;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Scanner;
/**
* <p>
* 项目生成器
* </p>
*
* @author DengMin
*/
public class CodeGenerator {
public static String scanner(String tip) {
StringBuilder help = new StringBuilder();
help.append("1.生成全部表 2.输入需要生成表名");
System.out.println(help);
Scanner scanner = new Scanner(System.in);
Integer ipt = Integer.valueOf(scanner.next());
if (ipt == 1) {
return "";
} else if (ipt == 2) {
StringBuilder help1 = new StringBuilder();
help1.append("请输入" + tip + ":");
System.out.println(help1);
Scanner scanner1 = new Scanner(System.in);
if (scanner1.hasNext()) {
String name = scanner1.next();
if (StringUtils.isNotEmpty(name)) {
return name;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
return scanner(tip);
}
public static void main(String[] args) {
final ResourceBundle rb = ResourceBundle.getBundle("mybatis-generator");
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(System.getProperty("user.dir") + rb.getString("outputDir"));
gc.setOpen(false);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
gc.setAuthor(rb.getString("author"));
gc.setMapperName("%sMapper");
gc.setEntityName("%sDO");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl(rb.getString("url"));
dsc.setDriverName(rb.getString("driverName"));
dsc.setUsername(rb.getString("userName"));
dsc.setPassword(rb.getString("password"));
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(rb.getString("setParent"));
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setEntity("model");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return System.getProperty("user.dir") + rb.getString("mapperPath") + tableInfo.getMapperName() + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass(BaseModel.class);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
String[] tables = scanner("表名,多个英文逗号分割").split(",");
if (StringUtils.isNotBlank(tables[0])) {
strategy.setInclude(tables);
}
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
package com.zhongzhi.common.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* 填充配置
*
* @author DengMin
* @date 2020/07/21
**/
@Component
public class MetaHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
}
}
package com.zhongzhi.common.interceptor;
import com.auth0.jwt.interfaces.Claim;
import com.zhongzhi.common.constant.Code;
import com.zhongzhi.common.constant.SmsCode;
import com.zhongzhi.common.exception.HttpException;
import com.zhongzhi.common.utils.JwtUtil;
import com.zhongzhi.common.utils.Localstorage;
import com.zhongzhi.common.utils.LoginRequired;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
/**
* <p>
* 鉴权拦截器
* </p>
*
* @author DengMin
* @since 2021/4/26
*/
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
if (methodAnnotation != null) {
String authorization = request.getHeader("Authorization");
if (StringUtils.isBlank(authorization)) {
throw new HttpException(Code.TOKEN_EXCEPTION.getCode(), Code.TOKEN_EXCEPTION.getMessage());
}
String token = authorization;
if (authorization.startsWith("Bearer")) {
token = authorization.replace("Bearer ", "");
}
if (token == null || JwtUtil.isExpired(token) || !JwtUtil.verifyToken(token)) {
throw new HttpException(Code.TOKEN_EXCEPTION.getCode(), Code.TOKEN_EXCEPTION.getMessage());
}
Map<String, Claim> claimMap = JwtUtil.getClaims(token);
if (claimMap != null) {
String[] role = methodAnnotation.value();
String type = claimMap.get("type").asString();
if (role.length > 0) {
if (Arrays.asList(role).contains(type)) {
if (SmsCode.student.equals(type)) {
// StudentDO studentDO = studentService.getById(claimMap.get("id").asLong());
// if (studentDO != null) {
// Localstorage.setUser(studentDO, type);
// return true;
// } else {
// Localstorage.remove();
// throw new HttpException(Code.USERNAMENOTFOUND.getCode(), Code.USERNAMENOTFOUND.getMessage());
// }
}
}
throw new HttpException(Code.ACCESSDENIED.getCode(), Code.ACCESSDENIED.getMessage());
}
}
}
return true;
}
}
package com.zhongzhi.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.zhongzhi.common.configure.AliyunSmsProperties;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.zhongzhi.common.constant.SMSTemplate;
import com.zhongzhi.common.exception.HttpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 阿里云短信
* </p>
*
* @author DengMin
* @since 2021/1/27
*/
@Slf4j
@Component
public class AliyunSmsUtil {
@Autowired
private AliyunSmsProperties aliyunSmsProperties;
/**
* 阿里云短信 -- 验证码
* @param phone
* @param code
* @return
*/
public SendSmsResponse send(String phone, int code) {
try {
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessKeySecret());
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", aliyunSmsProperties.getProduct(), aliyunSmsProperties.getDomain());
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号
request.setPhoneNumbers(phone);
//必填:短信签名-可在短信控制台中找到
request.setSignName("双创平台");
//必填:短信模板-可在短信控制台中找到
request.setTemplateCode("SMS_229640297");
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.setTemplateParam("{\"code\":\"" + code + "\"}");
//hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if (sendSmsResponse != null && sendSmsResponse.getCode().equals("OK")) {
return sendSmsResponse;
}
throw new Exception(sendSmsResponse.getMessage());
} catch (Exception e) {
log.error("---短信发送失败:" + e);
throw new HttpException(10011);
}
}
public static void main(String[] args) {
// AliyunSmsUtil.sendNew("15201936167",000123);
}
/**
* 三网平台短信
* @param msg
* @param phone
* @param templateId
*/
public void sendTemplateMsg(String msg, String phone, String templateId) {
Map<String, Object> map = new HashMap<>();
try {
map.put("cpcode", aliyunSmsProperties.getCpcode());
map.put("msg", msg);
map.put("mobiles", phone);
map.put("excode", aliyunSmsProperties.getExcode());
map.put("templetid", templateId);
String md5source = aliyunSmsProperties.getCpcode() + msg + phone + aliyunSmsProperties.getExcode() + templateId + aliyunSmsProperties.getKey();
map.put("sign", makeMD5(new String(md5source.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)).toLowerCase());
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.postForEntity(aliyunSmsProperties.getRcsapi(), map, String.class);
String body = responseEntity.getBody();
JSONObject object = JSON.parseObject(body);
if (Integer.valueOf(object.get("resultcode").toString()) != 0) {
log.error(object.get("resultmsg").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
// /**
// * 三网平台短信 新版本 https://flaginfo-cloud.yuque.com/staff-rozzgq/ofcpak
// * @param msg
// * @param phone
// * @param templateId
// */
// public static void sendTemplateMsgNew(String msg, String phone, String templateId) {
// String info = null;
// try{
// HttpClient httpclient = new HttpClient();
// PostMethod post = new PostMethod("https://opassapi.infocloud.cc/sms/Api/SendGBK.do");//
// post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"gb2312");
// post.addParameter("SpCode", templateId);
// post.addParameter("LoginName", "7db124d0baf189d1e485350xxx");
// post.addParameter("Password", "3df50b24fb8288b9da99d16bf527e9dbf13659748534dca6e0820xxx");
// post.addParameter("MessageContent", msg);
// post.addParameter("UserNumber", phone);
// post.addParameter("SerialNumber", "");
// post.addParameter("f", "1");
// httpclient.executeMethod(post);
// info = new String(post.getResponseBody(),"gbk");
// System.out.println(info);
// }catch (Exception e) {
// e.printStackTrace();
// }
// }
public void sendTemplateMsgP(String msg, String phone, String templateId) {
Map<String, Object> map = new HashMap<>();
try {
map.put("cpcode", aliyunSmsProperties.getCpcode());
map.put("msg", msg);
map.put("mobiles", phone);
map.put("excode", aliyunSmsProperties.getExcode());
map.put("templetid", templateId);
String md5source = aliyunSmsProperties.getCpcode() + msg + phone + aliyunSmsProperties.getExcode() + templateId + aliyunSmsProperties.getKey();
map.put("sign", makeMD5(new String(md5source.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)).toLowerCase());
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.postForEntity(aliyunSmsProperties.getRcsapi(), map, String.class);
String body = responseEntity.getBody();
JSONObject object = JSON.parseObject(body);
if (Integer.valueOf(object.get("resultcode").toString()) != 0) {
log.error(object.get("resultmsg").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String makeMD5(String plainText) {
String re_md5 = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes(StandardCharsets.UTF_8));
byte[] b = md.digest();
int i;
StringBuffer buf = new StringBuffer();
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
re_md5 = buf.toString().toLowerCase();
} catch (Exception e) {
e.printStackTrace();
}
return re_md5;
}
// public static String getByteString( byte[] buff_out )
// {
// StringBuffer strBuf = new StringBuffer(buff_out.length * 3);
// strBuf.append("Length[");
// strBuf.append(buff_out.length);
// strBuf.append("];Content[");
// for ( int i = 0 ; i < buff_out.length ; ++i ) {
// int l = buff_out[i] & 0x0F;
// int h = (buff_out[i] & 0xF0) >> 4;
//
// char ll = (char) (l > 9 ? 'a' + l - 10 : '0' + l);
// char hh = (char) (h > 9 ? 'a' + h - 10 : '0' + h);
//
// strBuf.append(hh);
// strBuf.append(ll);
// strBuf.append(" ");
// }
// strBuf.append("]");
// return strBuf.toString().toUpperCase();
// }
}
\ No newline at end of file
package com.zhongzhi.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
}
package com.zhongzhi.common.utils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Date;
/**
* Date格式工具
*
* @author DengMin
* @date 2020/08/03
**/
public class DateFormatUtil {
public final static String FMT_sdf14_L = "yyyy/MM/dd HH:mm:ss";
public final static String FMT_sdf_yMd = "yyyy/MM/dd";
public final static String FMT_sdf_Hm = "H:mm";
public final static String cron = "s m H d M ? yyyy";
/**
* Date转String,自定义格式
*
* @param date
* @param pattern
* @return
*/
public static String format(Date date, String pattern) {
try {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* String转Date,自定义格式
*
* @param date
* @param pattern
* @return
*/
public static Date parse(String date, String pattern) {
try {
if (StringUtils.isBlank(date)) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.parse(date);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* LocalDate转Date
*
* @param localDate
* @return
*/
public static Date localDateToDate(LocalDate localDate) {
if (localDate == null) {
return null;
}
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
/**
* LocalDate转String
*
* @param localDate
* @return
*/
public static String localDateToString(LocalDate localDate) {
if (localDate == null) {
return null;
}
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
return format(Date.from(zonedDateTime.toInstant()), FMT_sdf_yMd);
}
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
if (localDateTime == null) {
return null;
}
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* date转localDate
*
* @param date
* @return
*/
public static LocalDate dateTOLocalDate(Date date) {
if (date == null) {
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
/**
* String转LocalDate
*
* @param date
* @return
*/
public static LocalDate localDateParse(String date) {
if (StringUtils.isBlank(date)) {
return null;
}
return LocalDate.parse(date);
}
/**
* 时间戳转LocalDate
*
* @param timestamp
* @return
*/
public static LocalDate timestampTOLocalDate(Long timestamp) {
return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(0)).toLocalDate();
}
/**
* 时间字符串转Cron
*
* @param date
* @return
*/
public static String getCron(String date) {
try {
Date d = parse(date, FMT_sdf14_L);
SimpleDateFormat sdf = new SimpleDateFormat(cron);
return sdf.format(d);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 时间戳转日期字符串
*
* @param timestamp 时间戳
* @return 日期字符串
* @author ALiang
*/
public static String timestampToDateString(Long timestamp) {
Date date = new Date(timestamp);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FMT_sdf14_L);
return simpleDateFormat.format(date);
}
/**
* Date转LocalTime
*
* @param date
* @return
*/
public static LocalTime dateToLocalTime(Date date) {
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalTime localTime = instant.atZone(zoneId).toLocalTime();
return localTime;
}
public static LocalDateTime dateToLocalDateTime(Date date) {
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
return localDateTime;
}
}
package com.zhongzhi.common.utils;
import java.lang.annotation.*;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelColumn {
String value() default "";
int col() default 1;
}
package com.zhongzhi.common.utils;
import com.zhongzhi.common.exception.HttpException;
import com.zhongzhi.vo.ExcelFieldVO;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Component
public class ExcelUtil {
private final static String EXCEL2003 = "xls";
private final static String EXCEL2007 = "xlsx";
public static <T> List<T> readExcel(Class<T> cls, MultipartFile file) {
String fileName = file.getOriginalFilename();
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
throw new HttpException(10800);
}
Workbook workbook = null;
List<T> list = new ArrayList<>();
try {
InputStream stream = file.getInputStream();
if (fileName.endsWith(EXCEL2003)) {
workbook = new HSSFWorkbook(stream);
} else if (fileName.endsWith(EXCEL2007)) {
workbook = new XSSFWorkbook(stream);
}
if (workbook != null) {
Map<String, List<Field>> classMap = new HashMap<>();
List<Field> fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());
fields.forEach(field -> {
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null) {
String value = annotation.value();
if (StringUtils.isBlank(value)) {
return;
}
if (!classMap.containsKey(value)) {
classMap.put(value, new ArrayList<>());
}
field.setAccessible(true);
classMap.get(value).add(field);
}
});
boolean title = true;
Map<Integer, List<Field>> reflectionMap = new HashMap<>();
Sheet sheet = workbook.getSheetAt(0);
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (title) {
for (int j = 0; j <= row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
if (cell != null) {
String cellValue = cell.getStringCellValue();
if (StringUtils.isNotBlank(cellValue)) {
if (classMap.containsKey(cellValue)) {
reflectionMap.put(j, classMap.get(cellValue));
} else {
throw new HttpException(10802);
}
}
}
}
title = false;
} else {
if (row == null) {
continue;
}
boolean isBlank = true;
T t = cls.newInstance();
for (int j = 0; j <= row.getLastCellNum(); j++) {
if (reflectionMap.containsKey(j)) {
List<Field> fieldList = reflectionMap.get(j);
for (Field field : fieldList) {
Cell cell = row.getCell(j);
Class<?> type = field.getType();
Object cellValue = getCellValue(cell, type);
if (cellValue != null) {
isBlank = false;
}
handleField(t, cellValue, field);
}
}
}
if (!isBlank) {
list.add(t);
}
}
}
}
} catch (InstantiationException | IOException | IllegalAccessException e) {
e.printStackTrace();
}
return list;
}
public static <T> void writeExcel(String title, List<ExcelFieldVO> fields, List<Map> list) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
AtomicInteger ai = new AtomicInteger();
{
sheet.addMergedRegion(new CellRangeAddress(0,0, 0, 6));
Row t = sheet.createRow(ai.getAndIncrement());
AtomicInteger tat = new AtomicInteger();
Cell tcl = t.createCell(tat.getAndIncrement());
CellStyle style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
Font f = wb.createFont();
f.setFontHeightInPoints((short) 13);
f.setBoldweight(Font.BOLDWEIGHT_NORMAL);
style.setFont(f);
tcl.setCellStyle(style);
tcl.setCellValue(title);
Row row = sheet.createRow(ai.getAndIncrement());
AtomicInteger at = new AtomicInteger();
fields.forEach(field -> {
Cell cell = row.createCell(at.getAndIncrement());
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_NORMAL);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
cell.setCellValue(field.getName());
});
if (list != null) {
for (Map map : list) {
Row r = sheet.createRow(ai.getAndIncrement());
AtomicInteger a = new AtomicInteger();
fields.forEach(field -> {
Object value = map.get(field.getField());
Cell cell = r.createCell(a.getAndIncrement());
if (value != null) {
cell.setCellValue(value.toString());
}
});
}
}
sheet.autoSizeColumn(1);
String fileName = String.valueOf(new Date().getTime());
buildExcelDocument(fileName + "." + EXCEL2007, wb, response);
}
}
public static <T> void writeExcel(List<ExcelFieldVO> fields, List<Map> list) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
AtomicInteger ai = new AtomicInteger();
{
Row row = sheet.createRow(ai.getAndIncrement());
AtomicInteger at = new AtomicInteger();
fields.forEach(field -> {
Cell cell = row.createCell(at.getAndIncrement());
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
cell.setCellValue(field.getName());
});
if (list != null) {
list.forEach(map -> {
Row r = sheet.createRow(ai.getAndIncrement());
AtomicInteger a = new AtomicInteger();
fields.forEach(field -> {
Object value = map.get(field.getField());
Cell cell = r.createCell(a.getAndIncrement());
if (value != null) {
cell.setCellValue(value.toString());
}
});
});
for (int i = 0; i < list.size(); i++) {
sheet.autoSizeColumn(i);
}
}
String fileName = String.valueOf(new Date().getTime());
buildExcelDocument(fileName + "." + EXCEL2007, wb, response);
}
}
public static List<ExcelFieldVO> getField(Class cls) {
List<Field> fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());
List<ExcelFieldVO> list = new ArrayList<>();
fields.forEach(field -> {
ExcelFieldVO excelFieldVO = new ExcelFieldVO();
ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
if (annotation != null) {
String value = annotation.value();
if (StringUtils.isBlank(value)) {
return;
}
excelFieldVO.setField(field.getName());
excelFieldVO.setName(value);
field.setAccessible(true);
list.add(excelFieldVO);
}
});
return list;
}
private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) {
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
response.flushBuffer();
wb.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
private static Object getCellValue(Cell cell, Class<?> type) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (DateUtil.isCellDateFormatted(cell)) {
if ("h:mm".equals(cell.getCellStyle().getDataFormatString()) || "hh:mm".equals(cell.getCellStyle().getDataFormatString())) {
return DateFormatUtil.format(cell.getDateCellValue(), DateFormatUtil.FMT_sdf_Hm);
}
return cell.getDateCellValue();
} else {
if (type != null) {
if (type == String.class) {
cell.setCellType(Cell.CELL_TYPE_STRING);
return cell.getStringCellValue();
} else {
return cell.getNumericCellValue();
}
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
return cell.getStringCellValue();
}
}
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return cell.getCellFormula();
} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else {
return cell;
}
}
private static <T> void handleField(T t, Object value, Field field) {
try {
Class<?> type = field.getType();
if (type == null || type == void.class || value == null) {
return;
}
if (type == Object.class) {
field.set(t, value);
} else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {
if (type == BigDecimal.class) {
field.set(t, new BigDecimal(value.toString()));
} else {
field.set(t, value);
}
} else if (type == Boolean.class) {
field.set(t, BooleanUtils.toBoolean(value.toString()));
} else if (type == Date.class || type == LocalTime.class || type == LocalDateTime.class) {
if (type == Date.class) {
field.set(t, value);
} else if (type == LocalTime.class) {
if (value != null && value != "") {
field.set(t, DateFormatUtil.dateToLocalTime(DateFormatUtil.parse(value.toString(), DateFormatUtil.FMT_sdf_yMd)));
}
} else if (type == LocalDateTime.class) {
if (value != null && value != "") {
field.set(t, DateFormatUtil.dateToLocalDateTime(DateFormatUtil.parse(value.toString(), DateFormatUtil.FMT_sdf_yMd)));
}
}
} else if (type == String.class) {
field.set(t, value.toString());
} else {
Constructor<?> constructor = type.getConstructor(String.class);
field.set(t, constructor.newInstance(value));
}
} catch (Exception e) {
e.printStackTrace();
throw new HttpException(10801);
}
}
}
package com.zhongzhi.common.utils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IpAddressUtil {
public static String getIpAddress(HttpServletRequest request) {
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
}
package com.zhongzhi.common.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import java.util.Date;
import java.util.Map;
/**
* <p>
* Token工具
* </p>
*
* @author DengMin
* @since 2021/4/14
*/
public class JwtUtil {
private static final Long EXPIRE_TIME = 24 * 60 * 60 * 1000L;
private static final String SECRET = "PBKDF2SHA256:64000:18:24:N:GFHZ6Y0PTEUDYCJI3K6SOOXWYEKPOZED:WBWFJMX5DF252E0HR3BF3P/D";
/**
* 生成Token
*
* @param id
* @return
*/
public static String generateToken(Long id, String type) {
Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME);
return JWT.create()
.withClaim("id", id)
.withClaim("type", type)
.withAudience()
.withExpiresAt(expireDate)
.withIssuedAt(new Date())
.sign(Algorithm.HMAC256(SECRET));
}
/**
* 检验token是否正确
*
* @param token
* @return
*/
public static boolean verifyToken(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
verifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 获取用户自定义Claim集合
*
* @param token
* @return
*/
public static Map<String, Claim> getClaims(String token) {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
Map<String, Claim> claims = verifier.verify(token).getClaims();
return claims;
}
/**
* 获取过期时间
*
* @param token
* @return
*/
public static Date getExpiresAt(String token) {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
return JWT
.require(algorithm)
.build()
.verify(token)
.getExpiresAt();
}
/**
* 验证token是否失效
*
* @param token
* @return true: 过期, false: 没过期
*/
public static boolean isExpired(String token) {
try {
final Date expiration = getExpiresAt(token);
return expiration.before(new Date());
} catch (Exception e) {
return true;
}
}
}
package com.zhongzhi.common.utils;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@RestController
public class Localstorage {
private static final ThreadLocal<Object> local = ThreadLocal.withInitial(() -> null);
private static ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
public static void setUser(Object obj, String type) {
Map<String, Object> map = new HashMap<>();
map.put("user", obj);
map.put("type", type);
Localstorage.local.set(map);
}
public static Map<String, Object> getMap() {
return (Map<String, Object>) Localstorage.local.get();
}
public static Object getUser() {
Map<String, Object> map = (Map<String, Object>) Localstorage.local.get();
return map.get("user");
}
public static void remove() {
Localstorage.local.remove();
}
}
package com.zhongzhi.common.utils;
import java.lang.annotation.*;
/**
* <p>
* 自定义验证登陆注解
* </p>
*
* @author DengMin
* @since 2020/12/18
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LoginRequired {
String[] value();
}
\ No newline at end of file
package com.zhongzhi.common.utils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.zhongzhi.common.constant.PDFCheckBox;
import com.zhongzhi.common.constant.ProjectType;
import com.zhongzhi.common.exception.HttpException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Component
public class PDFUtil {
static BaseFont baseFont;
{
try {
baseFont = BaseFont.createFont("https://zhongzhi-cms.oss-cn-shanghai.aliyuncs.com/STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void tableStyle(PdfPTable table, int[] cellsWidth) throws DocumentException {
table.setWidths(cellsWidth);
table.setWidthPercentage(100);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
table.getDefaultCell().setFixedHeight(30);
table.getDefaultCell().setBackgroundColor(BaseColor.BLUE);
table.getDefaultCell().setPadding(0);
table.getDefaultCell().setBorderWidth(0);
}
/**
* 流化下载
*
* @param bytes
* @param filename
*/
public static void renderPdf(final byte[] bytes, final String filename, String type) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
initResponseHeader(response, "application/" + type);
setFileDownloadHeader(response, filename, "." + type);
if (null != bytes) {
try {
response.getOutputStream().write(bytes);
response.getOutputStream().flush();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
/**
* 分析并设置contentType与headers.
*/
private static HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType, final String... headers) {
// 分析headers参数
String encoding = "utf-8";
boolean noCache = true;
for (String header : headers) {
String headerName = StringUtils.substringBefore(header, ":");
String headerValue = StringUtils.substringAfter(header, ":");
if (StringUtils.equalsIgnoreCase(headerName, "utf-8")) {
encoding = headerValue;
} else if (StringUtils.equalsIgnoreCase(headerName, "no-cache")) {
noCache = Boolean.parseBoolean(headerValue);
} else {
throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
}
}
// 设置headers参数
String fullContentType = contentType + ";charset=" + encoding;
response.setContentType(fullContentType);
if (noCache) {
// Http 1.0 header
response.setDateHeader("Expires", 0);
response.addHeader("Pragma", "no-cache");
// Http 1.1 header
response.setHeader("Cache-Control", "no-cache");
}
return response;
}
/**
* 设置让浏览器弹出下载对话框的Header.
*
* @param
*/
public static void setFileDownloadHeader(HttpServletResponse response, String fileName, String fileType) {
try {
// 中文文件名支持
String encodedfileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + fileType + "\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
package com.zhongzhi.common.utils;
import java.util.Date;
import java.util.Random;
public class RandomUtil {
public static int getCode() {
return (int) ((Math.random() * 9 + 1) * 100000);
}
public static String randomPass(Integer count) {
StringBuffer stringBuffer = new StringBuffer();
Random random = new Random(new Date().getTime());
String flag = type[random.nextInt(type.length)];
int length = count;
for (int i = 0; i < length; i++) {
switch (flag) {
case "word":
stringBuffer.append(word[random.nextInt(word.length)]);
break;
case "num":
stringBuffer.append(num[random.nextInt(num.length)]);
break;
case "symbol":
stringBuffer.append(symbol[random.nextInt(symbol.length)]);
break;
default:
break;
}
flag = type[random.nextInt(type.length)];
}
return stringBuffer.toString();
}
public final static String[] type = {
"word", "num", "symbol"
};
public final static String[] word = {
"a", "b", "c", "d", "e", "f", "g",
"h", "j", "k", "m", "n",
"p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G",
"H", "J", "K", "M", "N",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};
public final static String[] num = {
"1", "2", "3", "4", "5", "6", "7", "8", "9"
};
public final static String[] symbol = {
"!", "@", "#", "$", "%", "&"
};
}
package com.zhongzhi.common.utils;
import com.zhongzhi.common.configure.RemoteProperties;
import com.zhongzhi.vo.ResponseVO;
import lombok.Data;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* 返回数据
*
* @author DengMin
* @date 2019/08/27 13:57
**/
@Data
@EnableConfigurationProperties(RemoteProperties.class)
public class ResponseData {
public static <T> ResponseVO<T> generateCreatedResponse(int code) {
return (ResponseVO<T>) ResponseVO.builder()
.code(code)
.message(RemoteProperties.getMessage(code))
.build();
}
public static <T> ResponseVO<T> generateCreatedResponse(int code, String message) {
return (ResponseVO<T>) ResponseVO.builder()
.code(code)
.message(message)
.build();
}
public static <T> ResponseVO<T> generateCreatedResponse(int code, T data) {
return (ResponseVO<T>) ResponseVO.builder()
.code(code)
.message(RemoteProperties.getMessage(code))
.data(data)
.build();
}
public static <T> ResponseVO<T> generateCreatedResponse(int code, String message, T data) {
return (ResponseVO<T>) ResponseVO.builder()
.code(code)
.message(message)
.data(data)
.build();
}
public static <T> ResponseVO<T> generateCreatedResponse(int code, String message, String path) {
return (ResponseVO<T>) ResponseVO.builder()
.code(code)
.message(message)
.path(path)
.build();
}
}
\ No newline at end of file
package com.zhongzhi.common.utils;
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
/**
* @author: tuyp
* @create: 2020-07-29 12:42
*/
public class Signature {
private String secretId;
private String secretKey;
private long currentTime;
private int random;
private int signValidDuration;
private int classId;
private static final String HMAC_ALGORITHM = "HmacSHA1";
private static final String CONTENT_CHARSET = "UTF-8";
public static byte[] byteMerger(byte[] byte1, byte[] byte2) {
byte[] byte3 = new byte[byte1.length + byte2.length];
System.arraycopy(byte1, 0, byte3, 0, byte1.length);
System.arraycopy(byte2, 0, byte3, byte1.length, byte2.length);
return byte3;
}
public String getUploadSignature() throws Exception {
String strSign = "";
String contextStr = "";
long endTime = (currentTime + signValidDuration);
contextStr += "secretId=" + java.net.URLEncoder.encode(secretId, "utf8");
contextStr += "&currentTimeStamp=" + currentTime;
contextStr += "&expireTime=" + endTime;
contextStr += "&random=" + random;
contextStr += "&classId=" + classId;
try {
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
SecretKeySpec secretKey = new SecretKeySpec(this.secretKey.getBytes(CONTENT_CHARSET), mac.getAlgorithm());
mac.init(secretKey);
byte[] hash = mac.doFinal(contextStr.getBytes(CONTENT_CHARSET));
byte[] sigBuf = byteMerger(hash, contextStr.getBytes(StandardCharsets.UTF_8));
strSign = base64Encode(sigBuf);
strSign = strSign.replace(" ", "").replace("\n", "").replace("\r", "");
} catch (Exception e) {
throw e;
}
return strSign;
}
private String base64Encode(byte[] buffer) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(buffer);
}
public void setSecretId(String secretId) {
this.secretId = secretId;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public void setCurrentTime(long currentTime) {
this.currentTime = currentTime;
}
public void setRandom(int random) {
this.random = random;
}
public void setSignValidDuration(int signValidDuration) {
this.signValidDuration = signValidDuration;
}
public void setClassId(int classId){this.classId = classId;}
}
package com.zhongzhi.common.utils;
import java.lang.annotation.*;
/**
* <p>
* 自定义日志注解
* </p>
*
* @author DengMin
* @since 2020/12/18
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
package com.zhongzhi.common.utils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import com.zhongzhi.common.configure.VODConfig;
import com.zhongzhi.common.exception.HttpException;
import org.springframework.stereotype.Component;
/**
* <p>
* 腾讯云 - 云点播API
* </p>
*
* @author DengMin
* @since 2022/8/1
*/
@Component
public class VodUtil {
private static String endpoint = "vod.tencentcloudapi.com";
/**
* 根据视频模版进行转码
* @param vodCode
* @return
*/
public static ProcessMediaResponse processMedia(VODConfig vodConfig, String vodCode) {
try {
//上传后直接转码
Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey());
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint(endpoint);
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
VodClient client = new VodClient(cred, "", clientProfile);
ProcessMediaRequest processMediaRequest = new ProcessMediaRequest();
MediaProcessTaskInput mediaProcessTaskInput1 = new MediaProcessTaskInput();
TranscodeTaskInput[] transcodeTaskInputs1 = new TranscodeTaskInput[1];
TranscodeTaskInput transcodeTaskInput1 = new TranscodeTaskInput();
transcodeTaskInput1.setDefinition(100030L);
transcodeTaskInputs1[0] = transcodeTaskInput1;
mediaProcessTaskInput1.setTranscodeTaskSet(transcodeTaskInputs1);
processMediaRequest.setMediaProcessTask(mediaProcessTaskInput1);
processMediaRequest.setFileId(vodCode);
return client.ProcessMedia(processMediaRequest);
} catch (Exception ex) {
throw new HttpException(50001);
}
}
/**
* 删除腾讯云上原视频
* @param vodCode
*/
public static void deleteMedia(VODConfig vodConfig, String vodCode) {
try {
//删除原视频
Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey());
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint(endpoint);
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
VodClient client = new VodClient(cred, "", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
DeleteMediaRequest req = new DeleteMediaRequest();
req.setFileId(vodCode);
// 返回的resp是一个DeleteMediaResponse的实例,与请求对象对应
client.DeleteMedia(req);
} catch (TencentCloudSDKException e) {
throw new HttpException(99999, e.getMessage());
}
}
/**
* 云点播域名的CDN统计数据
* @param vodConfig
* @param DataType
* @param startTime
* @param endTime
* @return
*/
public static StatDataItem[] DescribeCDNStatDetails(VODConfig vodConfig, String DataType, String startTime, String endTime) {
try {
Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey());
// 实例化一个http选项,可选的,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint(endpoint);
// 实例化一个client选项,可选的,没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
// 实例化要请求产品的client对象,clientProfile是可选的
VodClient client = new VodClient(cred, "", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
DescribeCDNUsageDataRequest req = new DescribeCDNUsageDataRequest();
req.setStartTime(startTime);
req.setEndTime(endTime);
req.setDataType(DataType);
// 返回的resp是一个DescribeCDNUsageDataResponse的实例,与请求对象对应
DescribeCDNUsageDataResponse resp = client.DescribeCDNUsageData(req);
// 返回的resp是一个DescribeCDNStatDetailsResponse的实例,与请求对象对应
return resp.getData();
} catch (TencentCloudSDKException e) {
e.printStackTrace();
throw new HttpException(99999, e.getMessage());
}
}
}
package com.zhongzhi.controller;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.zhongzhi.common.utils.ResponseData;
import com.zhongzhi.vo.ResponseVO;
import com.zhongzhi.vo.oss.GetSecretVO;
import com.zhongzhi.vo.oss.UploadFileVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@Api(tags = "oss")
@RestController
@RequestMapping("/oss")
public class OssController {
public static final String keyId = "LTAI5tPAH7P7WQVeowo517BE";
public static final String secret = "0ueqhIfdAZyw5lWlBVSLpAxTtx37RY";
// @Value("${spring.profiles.active}")
// private String env;
@PostMapping("getSecret")
@ApiOperation("oss秘钥")
public ResponseVO getSecret() {
GetSecretVO getSecretVO = new GetSecretVO();
getSecretVO.setKey(keyId);
getSecretVO.setSecret(secret);
return ResponseData.generateCreatedResponse(0, getSecretVO);
}
// @PostMapping("uploadFile")
// @ApiOperation("上传文件 file")
// public ResponseVO uploadFile(@RequestParam("file") MultipartFile file) {
// // 创建OSSClient实例。
// OSS ossClient = new OSSClientBuilder().build("http://oss-cn-shanghai.aliyuncs.com", keyId, secret);
// UploadFileVO uploadFileVO = new UploadFileVO();
// try {
////
//// if (env.equals("test")) {
//// env = "ykhl-bigger-test";
//// }
//// if (env.equals("prod")) {
//// env = "ykhl-bigger";
//// }
//
//
// // 创建PutObjectRequest对象。
// PutObjectRequest putObjectRequest = new PutObjectRequest("zhongzhi-cms", System.currentTimeMillis() + "_" + file.getOriginalFilename(), file.getInputStream());
// // 设置该属性可以返回response。如果不设置,则返回的response为空。
// putObjectRequest.setProcess("true");
// // 创建PutObject请求。
// PutObjectResult result = ossClient.putObject(putObjectRequest);
// // 如果上传成功,则返回200。
//// System.out.println(result.getResponse().getUri());
// uploadFileVO.setUrl(result.getResponse().getUri());
// } catch (Exception oe) {
// oe.printStackTrace();
// } finally {
// if (ossClient != null) {
// ossClient.shutdown();
// }
// }
// return ResponseData.generateCreatedResponse(0, uploadFileVO);
// }
@PostMapping("uploadFile")
@ApiOperation("分片上传")
public ResponseVO fenpian(@RequestParam("file") MultipartFile file) {
UploadFileVO uploadFileVO = new UploadFileVO();
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-beijing.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = keyId;
String accessKeySecret = secret;
// 填写Bucket名称,例如examplebucket。
String bucketName = "mass-entrepreneurship";
// 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
String objectName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建InitiateMultipartUploadRequest对象。
InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);
// 如果需要在初始化分片时设置请求头,请参考以下示例代码。
ObjectMetadata metadata = new ObjectMetadata();
//
metadata.setContentType(file.getContentType());
if ("pdf".equals(file.getContentType())){
metadata.setContentType("application/x-pcx");
}
metadata.setContentDisposition("inline");
// metadata.setHeader("x-oss-force-download", false);
request.setObjectMetadata(metadata);
// 返回uploadId,它是分片上传事件的唯一标识。您可以根据该uploadId发起相关的操作,例如取消分片上传、查询分片上传等。
// 初始化分片。
InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
String uploadId = upresult.getUploadId();
// partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。
List<PartETag> partETags = new ArrayList<PartETag>();
// 每个分片的大小,用于计算文件有多少个分片。单位为字节。
final long partSize = 1 * 1024 * 1024L; //1 MB。
// 根据上传的数据大小计算分片数。以本地文件为例,说明如何通过File.length()获取上传数据的大小。
// final File sampleFile = new File("D:\\localpath\\examplefile.txt");
// long fileLength = sampleFile.length();
// int partCount = (int) (fileLength / partSize);
// if (fileLength % partSize != 0) {
// partCount++;
// }
long fileLength = file.getSize();
int partCount = (int) (fileLength / partSize);
if (fileLength % partSize != 0) {
partCount++;
}
// 遍历分片上传。
for (int i = 0; i < partCount; i++) {
long startPos = i * partSize;
long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(bucketName);
uploadPartRequest.setKey(objectName);
uploadPartRequest.setUploadId(uploadId);
// 设置上传的分片流。
// 以本地文件为例说明如何创建FIleInputstream,并通过InputStream.skip()方法跳过指定数据。
InputStream instream = file.getInputStream();
instream.skip(startPos);
uploadPartRequest.setInputStream(instream);
// 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。
uploadPartRequest.setPartSize(curPartSize);
// 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出此范围,OSS将返回InvalidArgument错误码。
uploadPartRequest.setPartNumber(i + 1);
// 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。
UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
// 每次上传分片之后,OSS的返回结果包含PartETag。PartETag将被保存在partETags中。
partETags.add(uploadPartResult.getPartETag());
}
// 创建CompleteMultipartUploadRequest对象。
// 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
// 如果需要在完成分片上传的同时设置文件访问权限,请参考以下示例代码。
// completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.Private);
// 指定是否列举当前UploadId已上传的所有Part。仅在Java SDK为3.14.0及以上版本时,支持通过服务端List分片数据来合并完整文件时,将CompleteMultipartUploadRequest中的partETags设置为null。
// Map<String, String> headers = new HashMap<String, String>();
// 如果指定了x-oss-complete-all:yes,则OSS会列举当前UploadId已上传的所有Part,然后按照PartNumber的序号排序并执行CompleteMultipartUpload操作。
// 如果指定了x-oss-complete-all:yes,则不允许继续指定body,否则报错。
// headers.put("x-oss-complete-all","yes");
// completeMultipartUploadRequest.setHeaders(headers);
// 完成分片上传。
CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
uploadFileVO.setUrl(completeMultipartUploadResult.getLocation().replace("http","https"));
uploadFileVO.setRequestId(completeMultipartUploadResult.getRequestId());
System.out.println(completeMultipartUploadResult.getLocation());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
oe.printStackTrace();
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
ce.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return ResponseData.generateCreatedResponse(0, uploadFileVO);
}
}
package com.zhongzhi.model.base;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class BaseModel {
/**
* 创建时间
*/
@JsonIgnore
@TableField(insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER, value = "create_date", fill = FieldFill.INSERT)
private LocalDateTime createDate;
/**
* 更新时间
*/
@JsonIgnore
@TableField(insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER, value = "update_date", fill = FieldFill.UPDATE)
private LocalDateTime updateDate;
/**
* 删除时间
*/
@JsonIgnore
@TableLogic
private LocalDateTime deleteTime;
}
No preview for this file type
package com.zhongzhi.vo;
import lombok.Data;
@Data
public class ExcelFieldVO {
private String field;
private String name;
}
package com.zhongzhi.vo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ResponseVO<T> {
private Integer code;
private String message;
private T data;
private String path;
}
package com.zhongzhi.vo.oss;
import lombok.Data;
@Data
public class GetSecretVO {
private String key;
private String secret;
}
package com.zhongzhi.vo.oss;
import lombok.Data;
@Data
public class UploadFileVO {
private String url;
private String requestId;
}
# 本地环境配置
# 端口号
server.port=23507
# 数据源配置
# 数据源配置
spring.datasource.url=jdbc:mysql://139.224.253.21:3306/lida?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=ykhladmin302
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.druid.useGlobalDataSourceStat=true
# 控制台日志打印
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
\ No newline at end of file
# 生产环境配置
# 端口号
server.port=23507
server.tomcat.connection-timeout=600000
# 数据源配置
spring.datasource.url=jdbc:mysql://rm-uf69w46mo6agw0ahao.mysql.rds.aliyuncs.com:3306/lida?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=ykadmin_new
spring.datasource.password=youkedb608@good
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=600000
spring.datasource.druid.timeBetweenEvictionRunsMillis=600000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.druid.useGlobalDataSourceStat=true
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
\ No newline at end of file
# 环境配置
spring.profiles.active=dev
# 文件编码 UTF8
spring.mandatory-file-encoding=UTF-8
spring.jackson.time-zone=GMT+8
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=50MB
# 404 交给异常处理器处理
spring.mvc.throw-exception-if-no-handler-found=true
# 关闭静态资源的映射
spring.resources.add-mappings=false
# 关闭banner打印
mybatis-plus.global-config.banner=false
# mybatis-plus相关配置
mybatis-plus.mapper-locations=classpath:mapper/*.xml
# 是否开启自动驼峰命名规则映射
mybatis-plus.configuration.map-underscore-to-camel-case=true
# 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
mybatis-plus.configuration.call-setters-on-nulls=true
# 逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=NOW()
mybatis-plus.global-config.db-config.logic-not-delete-value=NULL
#日志配置
logging.config=classpath:logback-spring.xml
# 阿里云短信
sms.product=Dysmsapi
sms.domain=dysmsapi.aliyuncs.com
sms.accessKeyId=LTAI5tPAH7P7WQVeowo517BE
sms.accessKeySecret=0ueqhIfdAZyw5lWlBVSLpAxTtx37RY
sms.rcsapi=http://rcsapi.wo.cn:8000/umcinterface/sendtempletmsg
sms.cpcode=AABNUV
sms.excode=210120
sms.key=49197e89c95c9c6be46a1b420ff0d84d
vod.appId=1302252447
vod.secretId=AKIDOcePHvZ2C5VeYHQGSO5aqtlNxJQLqfz2
vod.secretKey=vjHYRmrfDbw0rWxA7oFcj7F8lDPKCm8E
vod.api=vod.tencentcloudapi.com
vod.region=ap-shanghai
vod.classId=848920
___ ___ __ ___ __ __ ___
|" \/" ||/"| / ")/" | | "\ |" |
\ \ / (: |/ /(: (__) :)|| |
\\ \/ | __/ \/ \/ |: |
/ / (// _ \ // __ \\ \ |___
/ / |: | \ \(: ( ) :)( \_|: \
|___/ (__| \__)\__| |__/ \_______)
c.code-message[0]=成功
c.code-message[10010]=PDF下载失败
c.code-message[10011]=发送失败,获取验证码频繁
# 学生
c.code-message[10020]=手机号已注册
c.code-message[10025]=验证码已过期
c.code-message[10021]=验证码不正确
c.code-message[10022]=输入的手机号和接收验证码手机号不一致
c.code-message[10023]=该身份证号已注册
c.code-message[10024]=手机号未注册
c.code-message[10026]=账号已存在
# 项目
c.code-message[10040]=项目已申请
c.code-message[10041]=项目负责人已存在
c.code-message[10042]=提交失败,您填写的项目信息不完整
c.code-message[10043]=项目已提交,请等待项目审核
c.code-message[10044]=撤回失败,您未申请项目
c.code-message[10045]=撤回失败,您的项目已进入审批状态
c.code-message[10046]=项目不存在
c.code-message[10047]=请选择要分配的项目
c.code-message[10048]=请选择要分配的评委
c.code-message[10049]=项目信息不完整
c.code-message[10050]=您不是该项目的评委
c.code-message[10051]=项目评分已提交
c.code-message[10052]=请先进行预评分
c.code-message[10053]=评委已分配了该项目
c.code-message[10054]=未指定赛事年份
c.code-message[10055]=创建失败,尚未处于大赛规定的报名时间
c.code-message[10056]=项目赛事已结束报名
c.code-message[10057]=赛事暂未开放
c.code-message[10058]=您已超过规定的项目上报数量
c.code-message[10059]=撤回失败,评委已进行了项目评分
c.code-message[10070]=撤回失败,评委不存在
c.code-message[10071]=撤回失败,项目未分配该评委
c.code-message[10072]=您已创建了类型的项目
c.code-message[10073]=撤回失败,项目已评审
c.code-message[10074]=不在评审时间内
c.code-message[10075]=评审已开始,不能撤回评委
c.code-message[10076]=请先设置评审起始时间
c.code-message[10077]=提交失败,有信息尚未填写
c.code-message[10078]=撤回失败,当前时间不在大赛时间段内
c.code-message[10079]=指导老师手机号不能重复
# 院校
c.code-message[10060]=账户不存在
c.code-message[10061]=密码错误
c.code-message[10062]=账户已存在
c.code-message[10063]=院校名称已存在
c.code-message[10064]=学校代码已存在
c.code-message[10065]=项目未分配评审
c.code-message[10066]=上传文件为空
c.code-message[10067]=系统已暂停登录功能
c.code-message[10068]=成员不能是负责人
c.code-message[10018]=不在大赛时间范围内
c.code-message[10019]=最多只能添加1位学校领队
c.code-message[10029]=最多只能添加2位观摩人员
c.code-message[10030]=车牌号已存在
c.code-message[10031]=不在申报时间范围内
c.code-message[10032]=该届赛事已存在
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="LOG_PATH" value="logs/"/>
<property name="APP_NAME" value="springboot-logback"/>
<contextName>${APP_NAME}</contextName>
<jmxConfigurator/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<pattern>%d [%t] %5p %c:%L - %m%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${LOG_PATH}${APP_NAME}-info.log</File>
<encoder>
<pattern>%d [%t] %5p %c:%L - %m%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<FileNamePattern>${LOG_PATH}${APP_NAME}/info/%d{yyyy-MM-dd}-%i.log.gz
</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
</appender>
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${LOG_PATH}${APP_NAME}-error.log</File>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>error</level>
</filter>
<encoder>
<pattern>%d [%t] %5p %c:%L - %m%n</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>256MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<FileNamePattern>${LOG_PATH}${APP_NAME}/error/%d{yyyy-MM-dd}-%i.log.gz
</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
</appender>
<springProfile name="dev">
<logger name="com.zhongzhi" level="error"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="INFO_FILE"/>
<appender-ref ref="ERROR_FILE"/>
</root>
</springProfile>
<springProfile name="pre">
<logger name="com.zhongzhi" level="error"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="INFO_FILE"/>
<appender-ref ref="ERROR_FILE"/>
</root>
</springProfile>
<springProfile name="prod">
<logger name="com.zhongzhi" level="error"/>
<root level="INFO">
<appender-ref ref="ERROR_FILE"/>
</root>
</springProfile>
</configuration>
\ No newline at end of file
# 此处为本项目src所在路径(代码生成器输出路径)
outputDir=/src/main/java/
author=DengMin
# 父的包名
setParent=com.zhongzhi
# mapper.xml文件生成路径
mapperPath=/src/main/resources/mapper/
# 数据库地址
url=jdbc:mysql://139.224.253.21:3306/gtja?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
driverName=com.mysql.cj.jdbc.Driver
userName=root
password=ykhladmin302
\ No newline at end of file
package ${package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* <p>
* ${table.comment!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
}
</#if>
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
<#if chainModel>
import lombok.experimental.Accessors;
</#if>
</#if>
/**
* <p>
* ${table.comment!}
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
<#if chainModel>
@Accessors(chain = true)
</#if>
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>
<#if entitySerialVersionUID>
private static final long serialVersionUID = 1L;
</#if>
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
<#if swagger2>
@ApiModelProperty(value = "${field.comment}")
<#else>
/**
* ${field.comment}
*/
</#if>
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.annotationColumnName}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.annotationColumnName}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循环遍历 ---------->
<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
<#if chainModel>
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
<#else>
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
</#if>
this.${field.propertyName} = ${field.propertyName};
<#if chainModel>
return this;
</#if>
}
</#list>
</#if>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
protected Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#if !entityLombokModel>
@Override
public String toString() {
return "${entity}{" +
<#list table.fields as field>
<#if field_index==0>
"${field.propertyName}=" + ${field.propertyName} +
<#else>
", ${field.propertyName}=" + ${field.propertyName} +
</#if>
</#list>
"}";
}
</#if>
}
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
/**
* <p>
* ${table.comment!} Mapper 接口
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
</#if>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">
<#if enableCache>
<!-- 开启二级缓存 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
</#if>
<#if baseResultMap>
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
<#list table.fields as field>
<#if field.keyFlag><#--生成主键排在第一位-->
<id column="${field.name}" property="${field.propertyName}"/>
</#if>
</#list>
<#list table.commonFields as field><#--生成公共字段 -->
<result column="${field.name}" property="${field.propertyName}"/>
</#list>
<#list table.fields as field>
<#if !field.keyFlag><#--生成普通字段 -->
<result column="${field.name}" property="${field.propertyName}"/>
</#if>
</#list>
</resultMap>
</#if>
<#if baseColumnList>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
<#list table.commonFields as field>
${field.columnName},
</#list>
${table.fieldNames}
</sql>
</#if>
</mapper>
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* <p>
* ${table.comment!} 服务类
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
</#if>
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
/**
* <p>
* ${table.comment!} 服务实现类
* </p>
*
* @author ${author}
* @since ${date}
*/
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
}
</#if>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!