master
wenfei 3 months ago
parent 972426019c
commit 85fc23a80e

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

@ -0,0 +1,118 @@
/*
* 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();
}
}

Binary file not shown.

@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

@ -0,0 +1,310 @@
#!/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 "$@"

@ -0,0 +1,182 @@
@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%

@ -0,0 +1,104 @@
<?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.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.rehome</groupId>
<artifactId>weather</artifactId>
<version>1.0.1</version>
<packaging>war</packaging>
<name>weather</name>
<description>weather and storm interface</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--线程池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.30</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-data-redis</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-cache</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

File diff suppressed because it is too large Load Diff

@ -0,0 +1,35 @@
package com.rehome.weather;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-25 9:35
* @description: springboot
*/
@SpringBootApplication
@EnableScheduling
@EnableCaching
public class WeatherApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(WeatherApplication.class, args);
}
/**
* @date 2021-05-18 09:20
* @description: springbootwar springboot
* @Param: SpringApplicationBuilder
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WeatherApplication.class);
}
}

@ -0,0 +1,47 @@
package com.rehome.weather.config.dao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.beans.PropertyVetoException;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-25 9:35
* @description:
*/
@Configuration
public class DataSourceConfiguration {
//驱动
@Value("${jdbc.driver}")
private String jdbcDriver;
//数据库连接url
@Value("${jdbc.url}")
private String jdbcUrl;
//数据库名称
@Value("${jdbc.username}")
private String jdbcUsername;
//数据库密码
@Value("${jdbc.password}")
private String jdbcPassword;
/**
* @date 2021-04-29 10:24
* @description:
* @Param: null
*/
@Bean(name = "dataSouce")
public ComboPooledDataSource createDataSouce() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUsername);
dataSource.setPassword(jdbcPassword);
//关闭连接后不自动commit
dataSource.setAutoCommitOnClose(false);
return dataSource;
}
}

@ -0,0 +1,40 @@
package com.rehome.weather.config.dao;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import lombok.Data;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-28 9:35
* @description: url key
*/
@Configuration
@ConfigurationProperties(prefix = "weather", ignoreUnknownFields = false)
@PropertySource(value="classpath:config/juheweather.properties",encoding = "UTF-8")
@Data
@Component
public class JuheWeatherProperties {
//要查询天气的城市
private String city;
//查询天汽url
private String weatherQueryUrl;
//聚合平台key
private String weatherKey;
//天气支持城市列表url
private String cityListUrl;
//查询天气种类列表url
private String weatherTypeUrl;
//和风开发平台台风key
private String heFengStormKey;
//和风天气开发平台 台风列表url
private String stormListUrl;
//和风天气开发平台 台风预报url
private String stormForecastUrl;
//和风天气开发平台 台风实况和路径url
private String stormTrackUrl;
}

@ -0,0 +1,50 @@
package com.rehome.weather.config.dao;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-25 9:35
* @description: sqlSession
*/
@Configuration
public class SessionFactoryConfiguration {
//mapper映射路径
@Value("${mapper_path}")
private String mapperPath;
//mybatis配置文件
@Value("${mybatis_config_file}")
private String mybatisConfigFilePath;
//数据源
@Autowired
private DataSource dataSouce;
//bean所在的包
@Value("${entity_package}")
private String entityPackage;
/**
* @date 2021-04-29 10:35
* @description: SqlSessionFactoryBean
* @Param: null
*/
@Bean(name="sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
sqlSessionFactoryBean.setDataSource(dataSouce);
sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
return sqlSessionFactoryBean;
}
}

@ -0,0 +1,34 @@
package com.rehome.weather.config.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import javax.sql.DataSource;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-25 9:35
* @description:
*/
@Configuration
@EnableTransactionManagement
public class TransactionManagementConfiguration implements TransactionManagementConfigurer{
//数据源
@Autowired
private DataSource dataSource;
/**
* @date 2021-04-25 10:45
* @description:
* @Param: null
*/
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}

@ -0,0 +1,63 @@
package com.rehome.weather.controller;
import com.rehome.weather.config.dao.JuheWeatherProperties;
import com.rehome.weather.service.StormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-05-08 13:48
* @description:
*/
@RestController
@RequestMapping("/storm/service")
@EnableConfigurationProperties(JuheWeatherProperties.class)
public class StormController {
//台风服务
@Autowired
private StormService stormService ;
/**
*
* @author huangwenfei
* Created DateTime 2021-05-08 14:03
*/
@CrossOrigin
@RequestMapping(value = "/getLocalStormList",method = RequestMethod.GET)
public Map getLocalStormList(@RequestParam(value = "year", required = false) String year){
String currentYear = new SimpleDateFormat("yyyy").format(new Date());
String paramYear = year==null?currentYear:year;
return stormService.getLocalStormList(paramYear);
}
/**
*
* @author huangwenfei
* Created DateTime 2021-05-10 14:15
*/
@CrossOrigin
@ResponseBody
@RequestMapping(value = "/getLocalStormForecastByStormId",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public String getLocalStormForecastByStormId(@RequestParam("stormid") String stormid) {
return stormService.getLocalStormForecastByStormId(stormid);
}
/**
*
* @author huangwenfei
* Created DateTime 2021-05-10 14:17
*/
@CrossOrigin
@ResponseBody
@RequestMapping(value = "/getLocalStormTrackByStormId",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public String getLocalStormTrackByStormId(@RequestParam("stormid") String stormid) {
return stormService.getLocalStormTrackByStormId(stormid);
}
}

@ -0,0 +1,78 @@
package com.rehome.weather.controller;
import com.rehome.weather.config.dao.JuheWeatherProperties;
import com.rehome.weather.entity.CityEntity;
import com.rehome.weather.service.WeatherService;
import com.rehome.weather.service.WeatherTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-25 14:35
* @description:
*/
@RestController
@RequestMapping("/weather/service")
@EnableConfigurationProperties(JuheWeatherProperties.class)
public class WeatherController {
//天气服务
@Autowired
private WeatherService weatherService ;
//天气种类服务
@Autowired
private WeatherTypeService weatherTypeService ;
//聚合数据 配置文件相关参数
@Autowired
JuheWeatherProperties juheWeatherProperties;
/**
* @date 2021-04-29 11:42
* @description: id
* @Param: id id
*/
@RequestMapping(value = "/getCityById/{id}",method = RequestMethod.GET)
public CityEntity getCityById(@PathVariable Integer id){
return weatherService.getById(id);
}
/**
* @date 2021-04-29 11:45
* @description:
* @Param: null
*/
//@RequestMapping(value = "/getJuheWeather",method = RequestMethod.GET)
public String getJuheWeather(){
return weatherService.getJuheWeather();
}
/**
* @date 2021-04-29 11:45
* @description:
* @Param: null
*/
//@RequestMapping(value = "/getWeatherCitySupporList",method = RequestMethod.GET)
public String getWeatherCitySupporList(){
return weatherService.getWeatherCitySupporList();
}
/**
* @date 2021-04-29 11:45
* @description:
* @Param: null
*/
//@RequestMapping(value = "/getWeatherTypesList",method = RequestMethod.GET)
public String getWeatherTypesList(){
return weatherTypeService.getWeatherTypeList();
}
/**
* @date 2021-04-29 11:45
* @description:
* @Param: null
*/
@RequestMapping(value = "/getLocalWeatherByCity",method = RequestMethod.GET)
public Map getLocalWeatherByCity(@RequestParam("city") String city){
return weatherService.getLocalWeatherByCity(city);
}
}

@ -0,0 +1,32 @@
package com.rehome.weather.dao;
import com.rehome.weather.entity.StormEntity;
import com.rehome.weather.entity.StormForecast;
import com.rehome.weather.entity.StormTrack;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* Dao
* @author huangwenfei
* Created DateTime 2021-05-08 14:08
*/
@Mapper
public interface StormDao {
//插入台风数据
int insertStorm(StormEntity stormEntity);
//更新台风数据
int updateStorm(StormEntity stormEntity);
//根据id查台风数据
StormEntity getStormById(String id);
//查本地库台风列表数据
List<StormEntity> getLocalStorms(String year);
//插入台风预报数据
int insertStormForecast(StormForecast stormForecast);
//根据stormid查台风预报数据
StormForecast getStormForecastById(String stormid);
//插入台风实况和路径数据
int insertStormTrack(StormTrack stormTrack);
//根据stormid查台风实况和路径数据
StormTrack getStormTrackById(String stormid);
}

@ -0,0 +1,34 @@
package com.rehome.weather.dao;
import com.rehome.weather.entity.CityEntity;
import com.rehome.weather.entity.WeatherFuture;
import com.rehome.weather.entity.WeatherRealtime;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-25 14:35
* @description: Dao
*/
@Mapper
public interface WeatherDao {
//根据id查城市
CityEntity getById(Integer id);
//插入支持天气查询的城市列表数据
int insertCitys(List<CityEntity> list);
//插入实时天气数据
int insertRealtimeWeather(WeatherRealtime weatherRealtime);
//插入预报天气数据
int insertFutrueWeather(WeatherFuture weatherFuture);
//更新预报天气数据
int updateFutrueWeather(WeatherFuture weatherFuture);
//根据日期查预报天气数据
WeatherFuture getFutrueByDate(String date);
//查本地库实时天气数据
WeatherRealtime getLocalWeatherRealtime(String city);
//查本地库未来五天预报天气数据
List<WeatherFuture> getLocalWeatherFuture(String city);
}

@ -0,0 +1,19 @@
package com.rehome.weather.dao;
import com.rehome.weather.entity.WeatherType;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-25 14:35
* @description: Dao
*/
@Mapper
public interface WeatherTypeDao {
//根据天气种类标识查天气种类数据
WeatherType getByWid(String wid);
//插入天气种类列表数据
int insertWeatherTypes(List<WeatherType> list);
}

@ -0,0 +1,21 @@
package com.rehome.weather.dto;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-29 14:40
* @description: dto
*/
@Setter
@Getter
public class BaseDto implements Serializable {
//响应码请求成功返回0 请求失败返回1
protected Integer error_code ;
//接口请求状态描述
protected String reason ;
}

@ -0,0 +1,23 @@
package com.rehome.weather.dto;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-05-08 11:40
* @description: Dto
*/
@Setter
@Getter
public class BaseStormDto implements Serializable {
//响应码请求成功返回0 请求失败返回1
protected String code ;
//台风数据发布时间
protected String updateTime ;
//台风数据发布时间当前数据的响应式页面,便于嵌入网站或应用
protected String fxLink ;
}

@ -0,0 +1,20 @@
package com.rehome.weather.dto;
import com.rehome.weather.entity.StormEntity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-05-08 11:49
* @description: Dto
*/
@Setter
@Getter
public class StormDto extends BaseStormDto implements Serializable {
//台风列表
private List<StormEntity> storm;
}

@ -0,0 +1,21 @@
package com.rehome.weather.dto;
import com.rehome.weather.entity.CityEntity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-29 14:42
* @description:
*/
@Setter
@Getter
public class WeatherCityListDto extends BaseDto implements Serializable {
//支持天气查询的城市列表
private List<CityEntity> result;
}

@ -0,0 +1,19 @@
package com.rehome.weather.dto;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-29 14:47
* @description: Dto
*/
@Setter
@Getter
public class WeatherQueryDto extends BaseDto implements Serializable {
//天气查询结果,包含实时天气和天气预报
private WeatherQueryResultDto result;
}

@ -0,0 +1,26 @@
package com.rehome.weather.dto;
import com.rehome.weather.entity.WeatherFuture;
import com.rehome.weather.entity.WeatherRealtime;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-29 14:52
* @description: ,
*/
@Setter
@Getter
public class WeatherQueryResultDto implements Serializable {
//城市
private String city ;
//实时天气
private WeatherRealtime realtime;
//天气预报
private List<WeatherFuture> future;
}

@ -0,0 +1,21 @@
package com.rehome.weather.dto;
import com.rehome.weather.entity.WeatherType;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.List;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-29 14:36
* @description: Dto
*/
@Setter
@Getter
public class WeatherTypeListDto extends BaseDto implements Serializable {
//天气种类列表
private List<WeatherType> result;
}

@ -0,0 +1,22 @@
package com.rehome.weather.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
*
*/
@Setter
@Getter
public class CityEntity implements Serializable {
//id
private Integer id ;
//省份
private String province ;
//城市
private String city ;
//区
private String district ;
}

@ -0,0 +1,34 @@
package com.rehome.weather.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-05-08 11:53
* @description:
*/
@Setter
@Getter
public class StormEntity implements Serializable {
//id
private String id ;
//台风名称
private String name ;
//台风所处流域
private String basin ;
//台风所处年份
private String year ;
//台风接入平台
private String platform;
//平台描述
private String platformdesc;
//是否为活跃台风 1:活跃台风 0:台风已停止
private String isActive ;
//最后更新时间
private Timestamp updatetime;
}

@ -0,0 +1,26 @@
package com.rehome.weather.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-05-10 11:04
* @description:
*/
@Setter
@Getter
public class StormForecast implements Serializable {
//id
private Integer id ;
//台风id
private String stormid ;
//台风预报源数据
private String forecast ;
//最后更新时间
private Timestamp updatetime;
}

@ -0,0 +1,26 @@
package com.rehome.weather.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-05-10 11:04
* @description:
*/
@Setter
@Getter
public class StormTrack implements Serializable {
//id
private Integer id ;
//台风id
private String stormid ;
//台风实况和路径源数据
private String track ;
//最后更新时间
private Timestamp updatetime;
}

@ -0,0 +1,37 @@
package com.rehome.weather.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.sql.Timestamp;
/**
*
*/
@Setter
@Getter
public class WeatherFuture implements Serializable{
//id
private Integer id ;
//预报日期
private String date ;
//温度
private String temperature ;
//天气情况
private String weather ;
//白天天气标识id
private String widday ;
//晚上天气标识id
private String widnight ;
//白天天气情况
private String widdayDesc ;
//晚上天气情况
private String widnightDesc ;
//风向
private String direct ;
//城市
private String city ;
//预报天气标识,从聚合数据平台拿到,然后提取出来,不会入库
private WidEntity wid;
//最后更新时间
private Timestamp updatetime;
}

@ -0,0 +1,34 @@
package com.rehome.weather.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
*
*/
@Setter
@Getter
public class WeatherRealtime implements Serializable{
//id
private Integer id ;
//温度,可能为空
private String temperature ;
//湿度,可能为空
private String humidity ;
//天气情况
private String info ;
//天气标识id
private String wid ;
//风向,可能为空
private String direct ;
//风力,可能为空
private String power ;
//空气质量指数,可能为空
private String aqi ;
//城市
private String city ;
//日期
private String date ;
//创建时间
private String createtime ;
}

@ -0,0 +1,19 @@
package com.rehome.weather.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
*
*/
@Setter
@Getter
public class WeatherType implements Serializable{
//id
private Integer id ;
//天气标识id
private String wid ;
//天气种类说明
private String weather ;
}

@ -0,0 +1,16 @@
package com.rehome.weather.entity;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
*
*/
@Setter
@Getter
public class WidEntity implements Serializable{
//白天天气标识id
private String day ;
//晚上天气标识id
private String night ;
}

@ -0,0 +1,64 @@
package com.rehome.weather.service;
import com.alibaba.fastjson.JSON;
import com.rehome.weather.config.dao.JuheWeatherProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 14:35
* @description:
*/
@Slf4j
@Component
@EnableConfigurationProperties(JuheWeatherProperties.class)
public class ScheduledService {
//天气服务层
@Autowired
private WeatherService weatherService ;
//台风服务层
@Autowired
private StormService stormService ;
//聚合数据 配置文件相关参数
@Autowired
JuheWeatherProperties juheWeatherProperties;
/**
* @date 2021-04-29 14:07
* @description: 30
* @Param: null
*/
@Scheduled(cron = "0 0 */1 * * *")//每个小时执行一次
public void scheduled(){
log.info("scheduled");
log.info("=====>>>>>使用cron:"+String.valueOf(System.currentTimeMillis()));
String city = juheWeatherProperties.getCity();
Map map = weatherService.getJuheWeatherByScheduled(city);
String jsonString = JSON.toJSONString(map);
log.info(jsonString);
}
/**
*
* @author huangwenfei
* Created DateTime 2021-05-08 14:50
*/
@Scheduled(cron = "0 0 */3 * * *")//每3个小时执行一次
public void scheduledGetStormList(){
log.info("scheduledGetStormList");
log.info("=====>>>>>使用cron:"+String.valueOf(System.currentTimeMillis()));
String year = new SimpleDateFormat("yyyy").format(new Date());
Map map = stormService.getStormListByScheduled(year);
String jsonString = JSON.toJSONString(map);
log.info(jsonString);
}
}

@ -0,0 +1,24 @@
package com.rehome.weather.service;
import java.util.Map;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 14:35
* @description:
*/
public interface StormService {
//从和风天气开发平台获取台风列表数据并入库
public Map getStormListByScheduled(String year);
//从和风天气开发平台获取台风预报并入库
public String getStormForecastByScheduled(String stormid);
//从和风天气开发平台获取台风实况和路径并入库
public String getStormTrackByScheduled(String stormid);
//从本地数据库查台风列表
public Map getLocalStormList(String year);
//从本地数据库查台风预报
public String getLocalStormForecastByStormId(String stormid);
//从本地数据库查台风实况和路径
public String getLocalStormTrackByStormId(String stormid);
}

@ -0,0 +1,30 @@
package com.rehome.weather.service;
import com.rehome.weather.entity.CityEntity;
import java.util.Map;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 14:35
* @description:
*/
public interface WeatherService {
//根据城市id查询城市数据
public CityEntity getById(Integer id);
//直接向聚合数据查询天气数据
public String getJuheWeather();
//获取支持天气查询的城市列表数据,同时入库
public String getWeatherCitySupporList();
//根据城市查询天气数据,然后把获取到的实时天气和预报天气入库
public Map getJuheWeatherByScheduled(String cityInput);
//从本地数据库查实时天气和预报天气数据,然后返回给前端
public Map getLocalWeatherByCity(String city);
}
/**
* mysql
* SELECT * from a where id = (SELECT max(id) FROM a);
* select * FROM ORDER BY id DESC LIMIT 0,1 ;
* SELECT * from a where id = (SELECT max(id) FROM a) and city = ;
*/

@ -0,0 +1,16 @@
package com.rehome.weather.service;
import com.rehome.weather.entity.WeatherType;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 14:35
* @description:
*/
public interface WeatherTypeService {
//根据天气标识ID查天气种类数据
public WeatherType getByWId(String wid);
//获取天气种类列表,然后入库
public String getWeatherTypeList();
}

@ -0,0 +1,220 @@
package com.rehome.weather.service.impl;
import com.alibaba.fastjson.JSON;
import com.rehome.weather.config.dao.JuheWeatherProperties;
import com.rehome.weather.dao.StormDao;
import com.rehome.weather.dto.BaseStormDto;
import com.rehome.weather.dto.StormDto;
import com.rehome.weather.entity.*;
import com.rehome.weather.service.StormService;
import com.rehome.weather.utils.WeatherUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-05-08 13:54
* @description:
*/
@Slf4j
@Service
@EnableConfigurationProperties(JuheWeatherProperties.class)
public class StormServiceImpl implements StormService {
//台风dao
@Autowired
private StormDao stormDao ;
//聚合数据 配置文件相关参数
@Autowired
JuheWeatherProperties juheWeatherProperties;
/**
*
* @author huangwenfei
* Created DateTime 2021-05-08 17:29
*/
@Override
public Map getStormListByScheduled(String year) {
String stormListUrl = juheWeatherProperties.getStormListUrl();
String heFengStormKey=juheWeatherProperties.getHeFengStormKey();
String url=stormListUrl+"?key="+heFengStormKey+"&basin=NP&year="+year;
String stormJson = WeatherUtil.analysisUrlGzip(url);
log.info(url);
log.info(stormJson);
StormDto stormDto = JSON.parseObject(stormJson, StormDto.class);
Map map = new HashMap<String,Object>();
if(stormDto!=null&&stormDto.getCode().equals("200")){
List<StormEntity> storm=stormDto.getStorm();
if(storm.size()>0){
for (StormEntity stormEntity : storm) {
stormEntity.setPlatform("hefeng");
stormEntity.setPlatformdesc("和风天气开发平台");
StormEntity stormEntityDb=stormDao.getStormById(stormEntity.getId());
if(stormEntityDb==null){
//数据库不存在这条台风数据 插入这条台风数据,
//同时调用台风预报接口数据并入库,
//同时调用台风实况和路径接口数据并入库,
log.info("数据库不存在这条台风数据 插入这条台风数据,");
int resultId=stormDao.insertStorm(stormEntity);
log.info("插入台风数据成功,id:"+String.valueOf(resultId));
this.getStormForecastByScheduled(stormEntity.getId());
this.getStormTrackByScheduled(stormEntity.getId());
}else{
//数据库存在这条台风数据
if(stormEntity.getIsActive().equals("1")){
//台风处于活跃状态
//同时调用台风预报接口数据并入库,
//同时调用台风实况和路径接口数据并入库
log.info("台风处于活跃状态");
this.getStormForecastByScheduled(stormEntity.getId());
this.getStormTrackByScheduled(stormEntity.getId());
}
if(stormEntity.getIsActive().equals("0")){
//台风已停止状态
if(stormEntityDb.getIsActive().equals("1")){
//数据库里台风还处于活跃状态,更新台风状态
//同时调用台风预报接口数据并入库,
//同时调用台风实况和路径接口数据并入库
log.info("数据库里台风还处于活跃状态,更新台风状态");
//获得系统时间.
Date date = new Date();
//将时间格式转换成符合Timestamp要求的格式.
String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
//把时间转换
Timestamp updatetime =Timestamp.valueOf(nowTime);
stormEntity.setUpdatetime(updatetime);
int resultId=stormDao.updateStorm(stormEntity);
log.info("更新台风数据成功,id:"+String.valueOf(resultId));
this.getStormForecastByScheduled(stormEntity.getId());
this.getStormTrackByScheduled(stormEntity.getId());
}
}
}
}
}
map.put("reason","从和风天气开发平台查询台风列表数据成功!");
map.put("code","200");
map.put("storm",storm);
}else{
if(stormDto!=null){
map.put("code",stormDto.getCode());
}else{
map.put("code","10000");
map.put("reason","从和风天气开发平台获取台风列表数据失败!");
}
}
return map;
}
/**
*
* @author huangwenfei
* Created DateTime 2021-05-10 16:02
*/
@Override
public String getStormForecastByScheduled(String stormid) {
String stormForecastUrl = juheWeatherProperties.getStormForecastUrl();
String heFengStormKey=juheWeatherProperties.getHeFengStormKey();
String url=stormForecastUrl+"?key="+heFengStormKey+"&stormid="+stormid;
String stormJson = WeatherUtil.analysisUrlGzip(url);
log.info(url);
log.info(stormJson);
BaseStormDto baseStormDto = JSON.parseObject(stormJson, BaseStormDto.class);
if(baseStormDto.getCode().equals("200")){
StormForecast stormForecast = new StormForecast();
stormForecast.setStormid(stormid);
stormForecast.setForecast(stormJson);
int resultId=stormDao.insertStormForecast(stormForecast);
log.info("插入台风预报数据成功,id:"+String.valueOf(resultId));
}
return stormJson;
}
/**
*
* @author huangwenfei
* Created DateTime 2021-05-10 16:03
*/
@Override
public String getStormTrackByScheduled(String stormid) {
String stormTrackUrl = juheWeatherProperties.getStormTrackUrl();
String heFengStormKey=juheWeatherProperties.getHeFengStormKey();
String url=stormTrackUrl+"?key="+heFengStormKey+"&stormid="+stormid;
String stormJson = WeatherUtil.analysisUrlGzip(url);
log.info(url);
log.info(stormJson);
BaseStormDto baseStormDto = JSON.parseObject(stormJson, BaseStormDto.class);
if(baseStormDto.getCode().equals("200")){
StormTrack stormTrack = new StormTrack();
stormTrack.setStormid(stormid);
stormTrack.setTrack(stormJson);
int resultId=stormDao.insertStormTrack(stormTrack);
log.info("插入台风实况和路径数据成功,id:"+String.valueOf(resultId));
}
return stormJson;
}
/**
*
* @author huangwenfei
* Created DateTime 2021-05-10 14:18
*/
@Override
public Map getLocalStormList(String year) {
Map map = new HashMap<String,Object>();
List<StormEntity> storm=stormDao.getLocalStorms(year);
List stormEmpty=new ArrayList<StormEntity>();
if(storm==null){
map.put("storm",stormEmpty);
}else{
map.put("storm",storm);
}
map.put("code","200");
return map;
}
/**
*
* @author huangwenfei
* Created DateTime 2021-05-10 14:17
*/
@Override
public String getLocalStormForecastByStormId(String stormid) {
StormForecast stormForecast = stormDao.getStormForecastById(stormid);
if(stormForecast!=null){
return stormForecast.getForecast();
}
Map map = new HashMap<String,Object>();
map.put("code","10000");
map.put("reason","查询不到数据");
String jsonString = JSON.toJSONString(map);
return jsonString;
}
/**
*
* @author huangwenfei
* Created DateTime 2021-05-10 14:18
*/
@Override
public String getLocalStormTrackByStormId(String stormid) {
StormTrack stormTrack = stormDao.getStormTrackById(stormid);
if (stormTrack!=null){
return stormTrack.getTrack();
}
Map map = new HashMap<String,Object>();
map.put("code","10000");
map.put("reason","查询不到数据");
String jsonString = JSON.toJSONString(map);
return jsonString;
}
}

@ -0,0 +1,208 @@
package com.rehome.weather.service.impl;
import com.alibaba.fastjson.JSON;
import com.rehome.weather.config.dao.JuheWeatherProperties;
import com.rehome.weather.dao.WeatherDao;
import com.rehome.weather.dao.WeatherTypeDao;
import com.rehome.weather.dto.WeatherCityListDto;
import com.rehome.weather.dto.WeatherQueryDto;
import com.rehome.weather.dto.WeatherQueryResultDto;
import com.rehome.weather.entity.*;
import com.rehome.weather.service.WeatherService;
import com.rehome.weather.utils.WeatherUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 14:35
* @description:
*/
@Slf4j
@Service
@EnableConfigurationProperties(JuheWeatherProperties.class)
public class WeatherServiceImpl implements WeatherService {
//天气dao
@Autowired
private WeatherDao weatherDao ;
//聚合数据 配置文件相关参数
@Autowired
JuheWeatherProperties juheWeatherProperties;
//天气种类dao
@Autowired
private WeatherTypeDao weatherTypeDao;
/**
* @date 2021-04-29 13:47
* @description: id
* @Param: id id
*/
@Override
public CityEntity getById(Integer id) {
return weatherDao.getById(id);
}
/**
* @date 2021-04-29 13:48
* @description:
* @Param: null
*/
@Override
public String getJuheWeather() {
String city = juheWeatherProperties.getCity();
String weatherQueryUrl = juheWeatherProperties.getWeatherQueryUrl();
String weatherKey=juheWeatherProperties.getWeatherKey();
String url=weatherQueryUrl+"?key="+weatherKey+"&city="+city;
System.out.println(url);
String weather = WeatherUtil.analysisUrl(url);
return weather;
}
/**
* @date 2021-04-29 13:50
* @description:
* @Param: null
*/
@Override
public String getWeatherCitySupporList() {
String cityListUrl = juheWeatherProperties.getCityListUrl();
String weatherKey=juheWeatherProperties.getWeatherKey();
String url=cityListUrl+"?key="+weatherKey;
System.out.println(url);
String cityListJson = WeatherUtil.analysisUrl(url);
WeatherCityListDto cityList = JSON.parseObject(cityListJson, WeatherCityListDto.class);
List<CityEntity> weatherCitySupper=cityList.getResult();
Map map = new HashMap<String,Object>();
if(weatherCitySupper.size()>0){
CityEntity cityEntity=weatherCitySupper.get(0);
CityEntity cityEntityDB=weatherDao.getById(cityEntity.getId());
if(cityEntityDB!=null){
map.put("reason","查询成功!没有插入数据");
map.put("error_code",0);
map.put("result",weatherCitySupper);
}else{
weatherDao.insertCitys(weatherCitySupper);
map.put("reason","插入数据成功!");
map.put("error_code",0);
map.put("result",weatherCitySupper);
}
}
String jsonString = JSON.toJSONString(map);
return jsonString;
}
/**
* @date 2021-04-29 13:54
* @description:
* @Param: cityInput
*/
@Override
public Map getJuheWeatherByScheduled(String cityInput) {
String city = juheWeatherProperties.getCity();
String weatherQueryUrl = juheWeatherProperties.getWeatherQueryUrl();
String weatherKey=juheWeatherProperties.getWeatherKey();
String url=weatherQueryUrl+"?key="+weatherKey+"&city="+city;
String weatherJson = WeatherUtil.analysisUrl(url);
log.info(weatherJson);
WeatherQueryDto weatherQueryEntiry = JSON.parseObject(weatherJson, WeatherQueryDto.class);
Map map = new HashMap<String,Object>();
if(weatherQueryEntiry!=null&&weatherQueryEntiry.getError_code()==0){
WeatherQueryResultDto result=weatherQueryEntiry.getResult();
WeatherQueryResultDto resultToClient = new WeatherQueryResultDto();
resultToClient.setCity(result.getCity());
/*
*/
WeatherRealtime realtime=result.getRealtime();
realtime.setCity(result.getCity());
SimpleDateFormat formatYYYY = new SimpleDateFormat("YYYY-MM-dd");
realtime.setDate(formatYYYY.format(new Date()));
weatherDao.insertRealtimeWeather(realtime);
resultToClient.setRealtime(realtime);
/*
*/
List<WeatherFuture> future=result.getFuture();
if(future.size()>0){
for (WeatherFuture weatherFuture : future) {
weatherFuture.setCity(result.getCity());
WeatherType weatherTypeDayDB=weatherTypeDao.getByWid(weatherFuture.getWid().getDay());
WeatherType weatherTypeNightDB=weatherTypeDao.getByWid(weatherFuture.getWid().getNight());
if(weatherTypeDayDB!=null){
weatherFuture.setWidday(weatherFuture.getWid().getDay());
weatherFuture.setWiddayDesc(weatherTypeDayDB.getWeather());
}
if(weatherTypeNightDB!=null){
weatherFuture.setWidnight(weatherFuture.getWid().getNight());
weatherFuture.setWidnightDesc(weatherTypeNightDB.getWeather());
}
//插入单条预报数据
WeatherFuture weatherFutureDB=weatherDao.getFutrueByDate(weatherFuture.getDate());
if(weatherFutureDB==null){
weatherDao.insertFutrueWeather(weatherFuture);
}else{
//获得系统时间.
Date date = new Date();
//将时间格式转换成符合Timestamp要求的格式.
String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
//把时间转换
Timestamp updatetime =Timestamp.valueOf(nowTime);
weatherFuture.setUpdatetime(updatetime);
weatherDao.updateFutrueWeather(weatherFuture);
}
}
resultToClient.setFuture(future);
map.put("reason","插入数据成功!");
map.put("error_code",0);
map.put("result",resultToClient);
}
}else{
map.put("reason","超过每日可允许请求次数");
map.put("error_code",10012);
}
return map;
}
/**
* @date 2021-04-29 13:58
* @description:
* @Param: city
*/
@Override
public Map getLocalWeatherByCity(String city) {
String cityConfig = juheWeatherProperties.getCity();
Map map = new HashMap<String,Object>();
if(cityConfig.equals(city)){
WeatherQueryResultDto resultToClient = new WeatherQueryResultDto();
resultToClient.setCity(city);
WeatherRealtime weatherRealtime=weatherDao.getLocalWeatherRealtime(city);
if(weatherRealtime!=null){
resultToClient.setRealtime(weatherRealtime);
}
List<WeatherFuture> future = weatherDao.getLocalWeatherFuture(city);
if(future!=null&&future.size()>0){
// 反转lists
Collections.reverse(future);
resultToClient.setFuture(future);
}
map.put("reason","查询数据成功!");
map.put("error_code",0);
map.put("result",resultToClient);
}else{
map.put("reason","查询数据失败!无当前查询的城市天气数据");
map.put("error_code",1);
}
log.info("从数据库存读取");
return map;
}
}

@ -0,0 +1,76 @@
package com.rehome.weather.service.impl;
import com.alibaba.fastjson.JSON;
import com.rehome.weather.config.dao.JuheWeatherProperties;
import com.rehome.weather.dao.WeatherTypeDao;
import com.rehome.weather.dto.WeatherTypeListDto;
import com.rehome.weather.entity.WeatherType;
import com.rehome.weather.service.WeatherTypeService;
import com.rehome.weather.utils.WeatherUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 14:35
* @description:
*/
@Service
@EnableConfigurationProperties(JuheWeatherProperties.class)
public class WeatherTypeServiceImpl implements WeatherTypeService {
//天气种类dao
@Autowired
private WeatherTypeDao weatherTypeDao;
//聚合数据 配置文件相关参数
@Autowired
JuheWeatherProperties juheWeatherProperties;
/**
* @date 2021-04-29 14:14
* @description: ID
* @Param: wid ID
*/
@Override
public WeatherType getByWId(String wid) {
return weatherTypeDao.getByWid(wid);
}
/**
* @date 2021-04-29 14:17
* @description:
* @Param: null
*/
@Override
public String getWeatherTypeList() {
String weatherTypeUrl = juheWeatherProperties.getWeatherTypeUrl();
String weatherKey=juheWeatherProperties.getWeatherKey();
String url=weatherTypeUrl+"?key="+weatherKey;
System.out.println(url);
String weatherTypeListJson = WeatherUtil.analysisUrl(url);
WeatherTypeListDto weatherTypeList = JSON.parseObject(weatherTypeListJson, WeatherTypeListDto.class);
List<WeatherType> weatherTypes=weatherTypeList.getResult();
Map map = new HashMap<String,Object>();
if(weatherTypes.size()>0){
WeatherType weatherType=weatherTypes.get(0);
WeatherType weatherTypeDB=weatherTypeDao.getByWid(weatherType.getWid());
if(weatherTypeDB!=null){
map.put("reason","查询成功!没有插入数据");
map.put("error_code",0);
map.put("result",weatherTypes);
}else{
weatherTypeDao.insertWeatherTypes(weatherTypes);
map.put("reason","插入数据成功!");
map.put("error_code",0);
map.put("result",weatherTypes);
}
}
String jsonString = JSON.toJSONString(map);
return jsonString;
}
}

@ -0,0 +1,91 @@
package com.rehome.weather.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-27 9:35
* @description: http
*/
public class HttpURLConnectionUtil {
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: urlStr geturl
*/
public static String getNetData(String urlStr) {
HttpURLConnection conn = null;
//连接成功后我们是要读取数据的 所以要有一个输入流
InputStream inputStream = null;
// 因为读取的都是文本信息 所以使用BufferedReader
BufferedReader bufferedReader = null;
//StringBuilder来把接收到的数据拼接起来
StringBuilder result = new StringBuilder();
try {
// 读取初始url 并且创建对象
URL url = new URL(urlStr);
//打开url连接
conn = (HttpURLConnection) url.openConnection();
//设置连接
//请求的方法
conn.setRequestMethod("GET");
//设置主机连接超时(单位:毫秒)
// 发送请求端 连接到 url目标地址端的时间 受距离长短和网络速度的影响
conn.setConnectTimeout(15000);
//设置从主机读取数据超时(单位:毫秒)
// 连接成功后 获取数据的时间 受数据量和服务器处理数据的影响
conn.setReadTimeout(60000);
//设置请求参数 可以指定接收json参数 服务端的key为content-type
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//获取响应码 如果响应码不为200 表示请求不成功
if (conn.getResponseCode() != 200) {
//todo 此处应该增加异常处理手段
return "请求失败!!!";
}
//获取响应码 如果响应码为200 表示请求成功 然后可以读取数据
//获取输入流 然后读取数据
inputStream = conn.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
//逐行读取数据
String line;//用来读取数据
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
//System.out.print(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭各种流
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
}

@ -0,0 +1,67 @@
package com.rehome.weather.utils;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
/**
* @author huangwenfei
* @version v1.0.0.0
* Created DateTime 2021-04-26 9:35
* @description: http
*/
public class WeatherUtil {
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: url geturl
*/
public static String analysisUrl(String url){
HttpURLConnection httpConnection = null;
String output = "";
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type",
"application/json");
InputStreamReader isr = new InputStreamReader(httpConnection
.getInputStream(),"utf-8");
BufferedReader responseBuffer = new BufferedReader(isr);
output = responseBuffer.readLine();
} catch (Exception e) {
} finally {
httpConnection.disconnect();
}
return output;
}
/**
* @date 2021-04-29 11:23
* @description: get
* @Param: url geturl
*/
public static String analysisUrlGzip(String url){
HttpURLConnection httpConnection = null;
String output = "";
try {
URL targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type", "application/json");
InputStream stream = new GZIPInputStream(httpConnection.getInputStream());
output = IOUtils.toString(stream,"utf-8");
} catch (Exception e) {
} finally {
httpConnection.disconnect();
}
return output;
}
}

@ -0,0 +1,41 @@
#1.项目启动的端口
server.port=28902
#2.数据库连接参数
#2.1jdbc驱动示数据库厂商决定这是mysql的驱动
#jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.driver=com.mysql.jdbc.Driver
#2.2数据库连接url包括ip(127.0.0.1)、端口(3306)、数据库名(testdb)
jdbc.url=jdbc:mysql://127.0.0.1:3306/weather?useUnicode=true&characterEncoding=utf-8&useSSL=false
#2.3数据库账号名
jdbc.username=root
#2.4数据库密码
jdbc.password=Skyinno251,
#3.Mybatis配置
#3.1 mybatis配置文件所在路径
mybatis_config_file=mybatis-config.xml
#3.2 mapper文件所在路径这样写可匹配mapper目录下的所有mapper包括其子目录下的
mapper_path=/mapper/**/**.xml
#3.3 entity所在包
entity_package=com.rehome.weather.entity
## Redis数据库索引默认为0
#spring.redis.database=0
## Redis服务器地址
#spring.redis.host=192.168.1.28
## Redis服务器连接端口
#spring.redis.port=6379
## Redis服务器连接密码默认为空
#spring.redis.password=
## 连接池最大连接数(使用负值表示没有限制)
#spring.redis.jedis.pool.max-active=20
## 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.jedis.pool.max-wait=-1
## 连接池中的最大空闲连接
#spring.redis.jedis.pool.max-idle=10
## 连接池中的最小空闲连接
#spring.redis.jedis.pool.min-idle=0
## 连接超时时间(毫秒)
#spring.redis.timeout=2000

@ -0,0 +1,18 @@
#要查询天气的城市,
weather.city=珠海
#聚合数据查询天气url
weather.weatherQueryUrl=http://apis.juhe.cn/simpleWeather/query
#聚合数据天气API key,天气接口共用
weather.weatherKey=ca980faee365078cb2bbb912c00f317e
#聚合数据 支持天气查询的城市列表url
weather.cityListUrl=http://apis.juhe.cn/simpleWeather/cityList
#聚合数据 获取天气种类的url
weather.weatherTypeUrl=http://apis.juhe.cn/simpleWeather/wids
#和风天气开发平台 台风key
weather.heFengStormKey=c06d26b86ff9424688b45f45906cab1d
#和风天气开发平台 台风列表url
weather.stormListUrl=https://api.qweather.com/v7/tropical/storm-list
#和风天气开发平台 台风预报url
weather.stormForecastUrl=https://api.qweather.com/v7/tropical/storm-forecast
#和风天气开发平台 台风实况和路径url
weather.stormTrackUrl=https://api.qweather.com/v7/tropical/storm-track

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--日志文件主目录:这里${user.home}为当前服务器用户主目录-->
<property name="LOG_HOME" value="${user.home}/weather_log"/>
<!--日志文件主目录:这里${user.home}为当前服务器用户主目录-->
<property name="APP_NAME" value="weather"/>
<!--输出日志到 命令行-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!--输出日志到 日志文件-->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!--设置策略-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件路径:这里%d{yyyyMMdd}表示按天分类日志-->
<FileNamePattern>${LOG_HOME}/%d{yyyyMMdd}/${APP_NAME}.log</FileNamePattern>
<!--日志保留天数-->
<MaxHistory>15</MaxHistory>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>50MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!--此处可以调整输出日志级别 改为debug可以看到更多日志包括hiber..、system debug类型以上的的日志-->
<root level="info">
<appender-ref ref="STDOUT"/>
<appender-ref ref="FILE"/>
</root>
</configuration>

@ -0,0 +1,40 @@
<?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="com.rehome.weather.dao.StormDao">
<!-- 根据主键查询-->
<select id="getStormById" resultType="com.rehome.weather.entity.StormEntity" parameterType="java.lang.String" >
select *
from storm_data
where id = #{id}
</select>
<insert id="insertStorm" parameterType="com.rehome.weather.entity.StormEntity">
insert into storm_data (id,name,basin,year,platform,platformdesc,isActive)
values (#{id},#{name},#{basin},#{year},#{platform},#{platformdesc},#{isActive});
</insert>
<update id="updateStorm" parameterType="com.rehome.weather.entity.StormEntity">
update storm_data set isActive=#{isActive},updatetime=#{updatetime} where id=#{id}
</update>
<select id="getLocalStorms" resultType="com.rehome.weather.entity.StormEntity" parameterType="java.lang.String" >
select *
from storm_data
where year = #{year} ORDER BY id DESC
</select>
<insert id="insertStormForecast" parameterType="com.rehome.weather.entity.StormForecast">
insert into storm_forecast (stormid,forecast)
values (#{stormid}, #{forecast});
</insert>
<select id="getStormForecastById" resultType="com.rehome.weather.entity.StormForecast" parameterType="java.lang.String" >
select *
from storm_forecast
where stormid = #{stormid} ORDER BY id DESC LIMIT 0,1
</select>
<insert id="insertStormTrack" parameterType="com.rehome.weather.entity.StormTrack">
insert into storm_track (stormid,track)
values (#{stormid}, #{track});
</insert>
<select id="getStormTrackById" resultType="com.rehome.weather.entity.StormTrack" parameterType="java.lang.String" >
select *
from storm_track
where stormid = #{stormid} ORDER BY id DESC LIMIT 0,1
</select>
</mapper>

@ -0,0 +1,44 @@
<?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="com.rehome.weather.dao.WeatherDao">
<!-- 根据主键查询-->
<select id="getById" resultType="com.rehome.weather.entity.CityEntity" parameterType="java.lang.Integer" >
select *
from weather_city
where id = #{id}
</select>
<insert id="insertCitys" parameterType="com.rehome.weather.entity.CityEntity">
insert into weather_city (id, province, city,district)
values
<foreach collection="list" item="city" index="index" separator=",">
(#{city.id,jdbcType=INTEGER}, #{city.province,jdbcType=VARCHAR}, #{city.city,jdbcType=VARCHAR},
#{city.district,jdbcType=VARCHAR})
</foreach>
</insert>
<insert id="insertRealtimeWeather" parameterType="com.rehome.weather.entity.WeatherRealtime">
insert into weather_realtime (temperature,humidity,info,wid,direct,power,aqi,city,date)
values (#{temperature}, #{humidity}, #{info},#{wid},#{direct},#{power},#{aqi},#{city},#{date});
</insert>
<select id="getLocalWeatherRealtime" resultType="com.rehome.weather.entity.WeatherRealtime" parameterType="java.lang.String" >
select *
from weather_realtime
where city = #{city} and id = (SELECT max(id) FROM weather_realtime)
</select>
<insert id="insertFutrueWeather" parameterType="com.rehome.weather.entity.WeatherFuture">
insert into weather_future (date,temperature,weather,widday,widnight,widdayDesc,widnightDesc,direct,city)
values (#{date},#{temperature}, #{weather}, #{widday},#{widnight},#{widnightDesc},#{widnightDesc},#{direct},#{city});
</insert>
<update id="updateFutrueWeather" parameterType="com.rehome.weather.entity.WeatherFuture">
update weather_future set temperature=#{temperature},weather=#{weather},widday=#{widday},widnight=#{widnight},widdayDesc=#{widdayDesc},widnightDesc=#{widnightDesc},direct=#{direct},updatetime=#{updatetime} where date=#{date}
</update>
<select id="getFutrueByDate" resultType="com.rehome.weather.entity.WeatherFuture" parameterType="java.lang.String" >
select *
from weather_future
where date = #{date}
</select>
<select id="getLocalWeatherFuture" resultType="com.rehome.weather.entity.WeatherFuture" parameterType="java.lang.String" >
select *
from weather_future
where city = #{city} ORDER BY id DESC LIMIT 0,5
</select>
</mapper>

@ -0,0 +1,18 @@
<?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="com.rehome.weather.dao.WeatherTypeDao">
<!-- 根据主键查询-->
<select id="getByWid" resultType="com.rehome.weather.entity.WeatherType" parameterType="java.lang.String" >
select *
from weather_type
where wid = #{wid}
</select>
<insert id="insertWeatherTypes" parameterType="com.rehome.weather.entity.WeatherType">
insert into weather_type (wid, weather)
values
<foreach collection="list" item="weatherType" index="index" separator=",">
(#{weatherType.wid,jdbcType=VARCHAR}, #{weatherType.weather,jdbcType=VARCHAR})
</foreach>
</insert>
</mapper>

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 配置文件的根元素 -->
<configuration>
<!--配置全局属性-->
<settings>
<!--使用jdbc的getGeneratedKeys获取数据库自增主键值-->
<setting name="useGeneratedKeys" value="true"/>
<!--使用列标签替换列别名 默认未true-->
<setting name="useColumnLabel" value="true" />
<!--开启驼峰式命名转换Table{create_time} -> Entity{createTime}-->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>

@ -0,0 +1,61 @@
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50734
Source Host : localhost:3306
Source Database : weather
Target Server Type : MYSQL
Target Server Version : 50734
File Encoding : 65001
Date: 2021-05-11 16:04:46
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for storm_data
-- ----------------------------
DROP TABLE IF EXISTS `storm_data`;
CREATE TABLE `storm_data` (
`id` varchar(20) NOT NULL COMMENT '平台描述',
`name` varchar(150) NOT NULL,
`basin` varchar(20) NOT NULL,
`year` varchar(20) NOT NULL,
`platform` varchar(30) DEFAULT NULL COMMENT '台风接入平台',
`platformdesc` varchar(50) DEFAULT NULL COMMENT '平台描述',
`isActive` varchar(10) NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='台风列表';
-- ----------------------------
-- Table structure for storm_forecast
-- ----------------------------
DROP TABLE IF EXISTS `storm_forecast`;
CREATE TABLE `storm_forecast` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stormid` varchar(20) NOT NULL,
`forecast` mediumtext NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='台风预报';
-- ----------------------------
-- Table structure for storm_track
-- ----------------------------
DROP TABLE IF EXISTS `storm_track`;
CREATE TABLE `storm_track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stormid` varbinary(20) NOT NULL,
`track` mediumtext NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='台风实况和路径';

@ -0,0 +1,61 @@
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50734
Source Host : localhost:3306
Source Database : weather
Target Server Type : MYSQL
Target Server Version : 50734
File Encoding : 65001
Date: 2021-05-11 16:04:46
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for storm_data
-- ----------------------------
DROP TABLE IF EXISTS `storm_data`;
CREATE TABLE `storm_data` (
`id` varchar(20) NOT NULL COMMENT '平台描述',
`name` varchar(150) NOT NULL,
`basin` varchar(20) NOT NULL,
`year` varchar(20) NOT NULL,
`platform` varchar(30) DEFAULT NULL COMMENT '台风接入平台',
`platformdesc` varchar(50) DEFAULT NULL COMMENT '平台描述',
`isActive` varchar(10) NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='台风列表';
-- ----------------------------
-- Table structure for storm_forecast
-- ----------------------------
DROP TABLE IF EXISTS `storm_forecast`;
CREATE TABLE `storm_forecast` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stormid` varchar(20) NOT NULL,
`forecast` mediumtext NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='台风预报';
-- ----------------------------
-- Table structure for storm_track
-- ----------------------------
DROP TABLE IF EXISTS `storm_track`;
CREATE TABLE `storm_track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stormid` varbinary(20) NOT NULL,
`track` mediumtext NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='台风实况和路径';

@ -0,0 +1,33 @@
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50734
Source Host : localhost:3306
Source Database : weather
Target Server Type : MYSQL
Target Server Version : 50734
File Encoding : 65001
Date: 2021-05-11 16:09:19
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for storm_data
-- ----------------------------
DROP TABLE IF EXISTS `storm_data`;
CREATE TABLE `storm_data` (
`id` varchar(20) NOT NULL COMMENT '平台描述',
`name` varchar(150) NOT NULL,
`basin` varchar(20) NOT NULL,
`year` varchar(20) NOT NULL,
`platform` varchar(30) DEFAULT NULL COMMENT '台风接入平台',
`platformdesc` varchar(50) DEFAULT NULL COMMENT '平台描述',
`isActive` varchar(10) NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='台风列表';

@ -0,0 +1,29 @@
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50734
Source Host : localhost:3306
Source Database : weather
Target Server Type : MYSQL
Target Server Version : 50734
File Encoding : 65001
Date: 2021-05-11 16:04:53
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for storm_forecast
-- ----------------------------
DROP TABLE IF EXISTS `storm_forecast`;
CREATE TABLE `storm_forecast` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stormid` varchar(20) NOT NULL,
`forecast` mediumtext NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='台风预报';

@ -0,0 +1,29 @@
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 50734
Source Host : localhost:3306
Source Database : weather
Target Server Type : MYSQL
Target Server Version : 50734
File Encoding : 65001
Date: 2021-05-11 16:05:02
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for storm_track
-- ----------------------------
DROP TABLE IF EXISTS `storm_track`;
CREATE TABLE `storm_track` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`stormid` varbinary(20) NOT NULL,
`track` mediumtext NOT NULL,
`createtime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updatetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='台风实况和路径';

File diff suppressed because it is too large Load Diff

@ -0,0 +1,13 @@
package com.rehome.weather;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WeatherApplicationTests {
@Test
void contextLoads() {
}
}
Loading…
Cancel
Save