diff --git a/mq2kb/.gitignore b/mq2kb/.gitignore new file mode 100644 index 0000000..153c933 --- /dev/null +++ b/mq2kb/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### 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/ diff --git a/mq2kb/.mvn/wrapper/MavenWrapperDownloader.java b/mq2kb/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..7f91a56 --- /dev/null +++ b/mq2kb/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +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. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * 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/0.4.2/maven-wrapper-0.4.2.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 direcrory '" + 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 { + 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(); + } + +} diff --git a/mq2kb/.mvn/wrapper/maven-wrapper.jar b/mq2kb/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/mq2kb/.mvn/wrapper/maven-wrapper.jar differ diff --git a/mq2kb/.mvn/wrapper/maven-wrapper.properties b/mq2kb/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..cd0d451 --- /dev/null +++ b/mq2kb/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/mq2kb/mvnw b/mq2kb/mvnw new file mode 100644 index 0000000..8b9da3b --- /dev/null +++ b/mq2kb/mvnw @@ -0,0 +1,286 @@ +#!/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 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)`" + # TODO classpath? +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 + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + 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 command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + 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 + +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 "$@" diff --git a/mq2kb/mvnw.cmd b/mq2kb/mvnw.cmd new file mode 100644 index 0000000..fef5a8f --- /dev/null +++ b/mq2kb/mvnw.cmd @@ -0,0 +1,161 @@ +@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 Maven2 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 key stroke 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 my 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.4.2/maven-wrapper-0.4.2.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% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%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% diff --git a/mq2kb/mysql-connector-java-8.0.16.jar b/mq2kb/mysql-connector-java-8.0.16.jar new file mode 100644 index 0000000..dd45f8c Binary files /dev/null and b/mq2kb/mysql-connector-java-8.0.16.jar differ diff --git a/mq2kb/pom.xml b/mq2kb/pom.xml new file mode 100644 index 0000000..95826e2 --- /dev/null +++ b/mq2kb/pom.xml @@ -0,0 +1,123 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.5.RELEASE + + + com.shunzhi + mqtt2kanban + 1.0.0 + mqtt2kanban + 推送mqtt消息到看板 + + + 1.8 + + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + 2.0.1 + + + + mysql + mysql-connector-java + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + + + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + commons-codec + commons-codec + 1.10 + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.1.0 + + + org.apache.httpcomponents + httpclient + 4.5.2 + + + com.alibaba + fastjson + 1.2.28 + + + com.aliyun.openservices + ons-client + 1.3.2.Final + + + org.fusesource.mqtt-client + mqtt-client + 1.0 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/ApplicationRunnerImpl.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/ApplicationRunnerImpl.java new file mode 100644 index 0000000..cbbba6c --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/ApplicationRunnerImpl.java @@ -0,0 +1,170 @@ +package com.shunzhi.mqtt2kanban; + +import com.shunzhi.mqtt2kanban.service.UserSeerviceImp; +import com.shunzhi.mqtt2kanban.utils.Tools; +import org.eclipse.paho.client.mqttv3.*; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.util.HashSet; +import java.util.Set; + +@Component +public class ApplicationRunnerImpl implements ApplicationRunner { + + private static String accessKey; + + private static String sign; + + public static MqttClient mqttClient; + + public static String groupId; + + public static String topic; + + private static int qosLevel; + + public static boolean isConnect; + + private Set set = new HashSet(); + + @Autowired + UserSeerviceImp userSeerviceImp; + + @Override + public void run(ApplicationArguments args) throws Exception { + + initMq(); + + } + + /** + * 初始化MQ + */ + private void initMq() { + final String brokerUrl = "tcp://post-cn-4590mq2hr03.mqtt.aliyuncs.com:1883"; + groupId = "GID_HFJSIURFHAQO110"; + topic = "Topic_Quene_Test"; + qosLevel = 1; + final Boolean cleanSession = false; + String clientId = groupId + "@@@9ED96FB6D72C1698"; + accessKey = "UimvLVp0Wj90P88u"; + String secretKey = "TE4rZenITG27tiQqHx9qINjx71Nws7"; + final MemoryPersistence memoryPersistence = new MemoryPersistence(); + if (null == mqttClient) { + try { + mqttClient = new MqttClient(brokerUrl, clientId, memoryPersistence); + } catch (MqttException e) { + e.printStackTrace(); + } + MqttConnectOptions connOpts = new MqttConnectOptions(); + //cal the sign as password,sign=BASE64(MAC.SHA1(groupId,secretKey)) + try { + sign = Tools.macSignature(clientId.split("@@@")[0], secretKey); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + connOpts.setUserName(accessKey); + connOpts.setPassword(sign.toCharArray()); + connOpts.setCleanSession(cleanSession); + connOpts.setKeepAliveInterval(90); + connOpts.setAutomaticReconnect(true); + mqttClient.setCallback(new MqttCallbackExtended() { + @Override + public void connectComplete(boolean reconnect, String serverURI) { + isConnect = true; + System.out.println("connect success"); + } + + @Override + public void connectionLost(Throwable throwable) { + isConnect = false; + System.out.println("connect lost:" + throwable.toString()); + throwable.printStackTrace(); + initMq();//初始化 + } + + @Override + public void messageArrived(String s, MqttMessage mqttMessage) throws Exception { + System.out.println("receive msg from topic " + s + " , body is " + new String(mqttMessage.getPayload())); + } + + @Override + public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { + //this notice make sense when qos >0 +// System.out.println("send msg succeed"); + } + }); + try { + mqttClient.connect(connOpts); + } catch (MqttException e) { + System.out.println("mqtt:" + e.toString()); + e.printStackTrace(); + } + /*while (true){ + sendMessageTest("528C8E6CD4A3C659","zy105387",0); + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + System.out.println("connect success:"+e); + e.printStackTrace(); + } + }*/ + } + } + + + /** + * @param equipmentSN 控制器SN号 + * @param consumerNO userid + * @param inOrOut 进出状态 + */ + public void sendMessage(String equipmentSN, String consumerNO, int inOrOut) { + try { + String recvClientId = groupId + "@@@"; + if (null != Mqtt2kanbanApplication.deviceList) { + for (int i = 0; i < Mqtt2kanbanApplication.deviceList.size(); i++) { + String devices = Mqtt2kanbanApplication.deviceList.get(i); + if (devices.contains(equipmentSN)) + recvClientId += devices.split(",")[0]; + + } + final String p2pSendTopic = topic + "/p2p/" + recvClientId; + String data = "{\"userId\":\"" + consumerNO + "\",\"inOrOut\":" + inOrOut + "}"; + String content = "{\"cmd\":\"34\",\"clientId\":\"\",\"data\":" + data + "}"; + MqttMessage message = new MqttMessage(content.getBytes()); + message.setQos(qosLevel); + System.out.println("发送内容:" + p2pSendTopic); + if (null != mqttClient) + mqttClient.publish(p2pSendTopic, message); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + + public void sendMessageTest(String equipmentSN, String consumerNO, int inOrOut) { + try { + String recvClientId = groupId + "@@@"+equipmentSN; + final String p2pSendTopic = topic + "/p2p/" + recvClientId; + String data = "{\"userId\":\"" + consumerNO + "\",\"inOrOut\":" + inOrOut + "}"; + String content = "{\"cmd\":\"34\",\"clientId\":\"\",\"data\":" + data + "}"; + MqttMessage message = new MqttMessage(content.getBytes()); + message.setQos(qosLevel); + System.out.println("发送内容:" + p2pSendTopic+" "+message); + if (null != mqttClient) + mqttClient.publish(p2pSendTopic, message); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/Mqtt2kanbanApplication.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/Mqtt2kanbanApplication.java new file mode 100644 index 0000000..c370fa5 --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/Mqtt2kanbanApplication.java @@ -0,0 +1,63 @@ +package com.shunzhi.mqtt2kanban; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.client.RestTemplate; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +@SpringBootApplication +@MapperScan("com.shunzhi.mqtt2kanban.mapper") +@EnableScheduling +public class Mqtt2kanbanApplication { + + @Bean + RestTemplate getRestTemplate(){ + return new RestTemplate(); + } + + private String indexPath = "C:\\index.txt";//存放当前取数的记录 + + private String devicePath = "C:\\Users\\Administrator\\Desktop\\device.txt";//存放设备id的路径 + public static void main(String[] args) { + SpringApplication.run(Mqtt2kanbanApplication.class, args); + new Mqtt2kanbanApplication().initFiles(); + } + + public static List deviceList = null; + /** + * 初始化文件 + */ + private void initFiles() { + deviceList = new ArrayList<>(); + try { + BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream(devicePath))); + String length = null; + while ((length = bufferedReader.readLine())!=null){ + deviceList.add(length); + } + System.out.println("deviceList:"+deviceList); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + File fi = new File(indexPath); + if (!fi.exists()){ + try { + fi.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + + +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/Swagger2.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/Swagger2.java new file mode 100644 index 0000000..3448b97 --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/Swagger2.java @@ -0,0 +1,37 @@ +package com.shunzhi.mqtt2kanban; + +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.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableSwagger2 +public class Swagger2 { + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("com.shunzhi.mqtt2kanban.control")) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Spring Boot中使用Swagger2") + .contact("Mr.Tao") + .description("") + .termsOfServiceUrl("") + .version("1.0") + .build(); + } + +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/Attendance.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/Attendance.java new file mode 100644 index 0000000..94be546 --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/Attendance.java @@ -0,0 +1,43 @@ +package com.shunzhi.mqtt2kanban.bean; + +public class Attendance { + + private String user_id; + + private String intime; + + private String systime; + + public String getUser_id() { + return user_id; + } + + public void setUser_id(String user_id) { + this.user_id = user_id; + } + + public String getIntime() { + return intime; + } + + public void setIntime(String intime) { + this.intime = intime; + } + + public String getSystime() { + return systime; + } + + public void setSystime(String systime) { + this.systime = systime; + } + + @Override + public String toString() { + return "Attendance{" + + "user_id='" + user_id + '\'' + + ", intime='" + intime + '\'' + + ", systime='" + systime + '\'' + + '}'; + } +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/User.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/User.java new file mode 100644 index 0000000..bebb559 --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/User.java @@ -0,0 +1,42 @@ +package com.shunzhi.mqtt2kanban.bean; + +public class User { + + private String user_id; + + private String user_name; + + private String addDate; + + public String getUser_name() { + return user_name; + } + + public void setUser_name(String user_name) { + this.user_name = user_name; + } + + public String getAddDate() { + return addDate; + } + + public void setAddDate(String addDate) { + this.addDate = addDate; + } + + public String getUser_id() { + return user_id; + } + + public void setUser_id(String user_id) { + this.user_id = user_id; + } + + @Override + public String toString() { + return "User{" + + "user_name='" + user_name + '\'' + + ", addDate='" + addDate + '\'' + + '}'; + } +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/ValidcardeventBean.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/ValidcardeventBean.java new file mode 100644 index 0000000..6c94e5b --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/bean/ValidcardeventBean.java @@ -0,0 +1,78 @@ +package com.shunzhi.mqtt2kanban.bean; + + + +public class ValidcardeventBean { + + private long ValidEventID; + + private String RecordDateTime;//进出时间 + + private long CardNO; + + private int InOrOut;//进出 + + private String EquipmentSN;//控制器编号 + + private String ConsumerNO;//userid + + public long getValidEventID() { + return ValidEventID; + } + + public void setValidEventID(long validEventID) { + ValidEventID = validEventID; + } + + public String getRecordDateTime() { + return RecordDateTime; + } + + public void setRecordDateTime(String recordDateTime) { + RecordDateTime = recordDateTime; + } + + public long getCardNO() { + return CardNO; + } + + public void setCardNO(long cardNO) { + CardNO = cardNO; + } + + public int getInOrOut() { + return InOrOut; + } + + public void setInOrOut(int inOrOut) { + InOrOut = inOrOut; + } + + public String getEquipmentSN() { + return EquipmentSN; + } + + public void setEquipmentSN(String equipmentSN) { + EquipmentSN = equipmentSN; + } + + public String getConsumerNO() { + return ConsumerNO; + } + + public void setConsumerNO(String consumerNO) { + ConsumerNO = consumerNO; + } + + @Override + public String toString() { + return "ValidcardeventBean{" + + "ValidEventID=" + ValidEventID + + ", RecordDateTime='" + RecordDateTime + '\'' + + ", InOrOut=" + InOrOut + + ", EquipmentSN='" + EquipmentSN + '\'' + + ", ConsumerNO='" + ConsumerNO + '\'' + + ", CardNo=" + CardNO + + '}'; + } +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/control/ValControl.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/control/ValControl.java new file mode 100644 index 0000000..2637f12 --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/control/ValControl.java @@ -0,0 +1,46 @@ +package com.shunzhi.mqtt2kanban.control; + +import com.shunzhi.mqtt2kanban.bean.User; +import com.shunzhi.mqtt2kanban.bean.ValidcardeventBean; +import com.shunzhi.mqtt2kanban.service.ValService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.List; + +@RestController +@RequestMapping(value = "/val/*") +public class ValControl { + + @Autowired + ValService valService; + + @GetMapping("getVal/{id}") + public List getVal(@PathVariable(value = "id") Long id) { + List validcardeventBean = null; + try { + System.out.println("传入id:" + id); + validcardeventBean = valService.select(365960); + System.out.println("获得的值:" + validcardeventBean); + } catch (Exception e) { + System.out.println("报错:" + e); + } + return validcardeventBean; + } + + @GetMapping("getUsers") + public String getUsers() { + List users = new ArrayList<>(); + try { + users = valService.getUser(); + System.out.println("users:" + users); + } catch (Exception e) { + System.out.println("错误:" + e); + } + return users.toString(); + } +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/mapper/UserMapper.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/mapper/UserMapper.java new file mode 100644 index 0000000..187263a --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/mapper/UserMapper.java @@ -0,0 +1,14 @@ +package com.shunzhi.mqtt2kanban.mapper; + +import com.shunzhi.mqtt2kanban.bean.User; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Mapper +public interface UserMapper { +// @Select("SELECT * FROM user") + User selectUser(); +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/mapper/ValMapper.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/mapper/ValMapper.java new file mode 100644 index 0000000..aa986ef --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/mapper/ValMapper.java @@ -0,0 +1,26 @@ +package com.shunzhi.mqtt2kanban.mapper; + +import com.shunzhi.mqtt2kanban.bean.User; +import com.shunzhi.mqtt2kanban.bean.ValidcardeventBean; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * dao层 + */ +@Mapper +@Repository +public interface ValMapper { + + /** + * + * @param index 当前查询到的数据下标 + * @return + */ + List select(@Param("index") int index); + + List selectUser(); +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/UserSeerviceImp.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/UserSeerviceImp.java new file mode 100644 index 0000000..81c0d35 --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/UserSeerviceImp.java @@ -0,0 +1,39 @@ +package com.shunzhi.mqtt2kanban.service; + +import com.shunzhi.mqtt2kanban.bean.Attendance; +import com.shunzhi.mqtt2kanban.bean.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.BeanPropertyRowMapper; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class UserSeerviceImp implements UserService { + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public List getAllUsers(int index) { + + String sql =""; + if (index==1){ + sql = "SELECT * FROM user limit "+2; + }else { + sql = String.format("SELECT * FROM user limit %s,10",index); + } + + return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper(User.class)); + } + + @Override + public List getAttendance(String user_id) { + String sql = "SELECT * FROM SZ_AttendanceRecords201906 where school_id=27 and intime>'2019-06-19 16:00' and intime<'2019-06-19 17:40' and user_id = '"+user_id+"'"; + + return jdbcTemplate.query(sql,new Object[]{},new BeanPropertyRowMapper(Attendance.class)); + } + + +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/UserService.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/UserService.java new file mode 100644 index 0000000..407714f --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/UserService.java @@ -0,0 +1,18 @@ +package com.shunzhi.mqtt2kanban.service; + +import com.shunzhi.mqtt2kanban.bean.Attendance; +import com.shunzhi.mqtt2kanban.bean.User; + +import java.util.List; + +public interface UserService { + + /** + * 获取所有用户 + * @return + */ + List getAllUsers(int index); + + List getAttendance(String user_id); + +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/ValService.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/ValService.java new file mode 100644 index 0000000..cdb1244 --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/ValService.java @@ -0,0 +1,14 @@ +package com.shunzhi.mqtt2kanban.service; + +import com.shunzhi.mqtt2kanban.bean.User; +import com.shunzhi.mqtt2kanban.bean.ValidcardeventBean; + +import java.util.List; + +public interface ValService { + List select(int index); + + List getUser(); + + List getValids(long index); +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/ValServiceImp.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/ValServiceImp.java new file mode 100644 index 0000000..4c142a1 --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/service/ValServiceImp.java @@ -0,0 +1,54 @@ +package com.shunzhi.mqtt2kanban.service; + +import com.shunzhi.mqtt2kanban.ApplicationRunnerImpl; +import com.shunzhi.mqtt2kanban.bean.User; +import com.shunzhi.mqtt2kanban.bean.ValidcardeventBean; +import com.shunzhi.mqtt2kanban.mapper.ValMapper; +import org.apache.ibatis.session.SqlSession; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.BeanPropertyRowMapper; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 实现类 + */ +@Service +public class ValServiceImp implements ValService { + + @Autowired + private ValMapper valMapper; + + @Autowired + private JdbcTemplate jdbcTemplate; + + + @Override + public List select(int index) { + return valMapper.select(index); + } + + @Override + public List getUser() { + return valMapper.selectUser(); + } + + @Override + public List getValids(long index) { + String sql = ""; +// SELECT * FROM t_d_validcardevent order by ValidEventID desc limit 0,1 + System.out.println("当前下标:" + index); + if (index==1){ + sql = "SELECT * FROM t_d_validcardevent order by ValidEventID desc limit 1"; + }else { + sql = String.format("SELECT * FROM t_d_validcardevent val where val.ValidEventID > %s limit 10",index); +// sql = "SELECT * FROM t_d_validcardevent val where val.ValidEventID > 400000 limit 100"; + } +// System.out.println("sql:"+sql); + return jdbcTemplate.query(sql,new Object[]{},new BeanPropertyRowMapper(ValidcardeventBean.class)); + } + + +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/utils/ScheduledTasks.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/utils/ScheduledTasks.java new file mode 100644 index 0000000..d5682be --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/utils/ScheduledTasks.java @@ -0,0 +1,202 @@ +package com.shunzhi.mqtt2kanban.utils; + +import com.shunzhi.mqtt2kanban.ApplicationRunnerImpl; +import com.shunzhi.mqtt2kanban.bean.User; +import com.shunzhi.mqtt2kanban.bean.ValidcardeventBean; +import com.shunzhi.mqtt2kanban.service.UserService; +import com.shunzhi.mqtt2kanban.service.ValService; +import org.apache.http.util.TextUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@Component +public class ScheduledTasks { + + @Autowired + private RestTemplate restTemplate;//网络请求 + + @Autowired + private UserService userService; + + @Autowired + private ValService valService; + + private static long index = 1;//记录取数的下标,第一次取最新一条 + + private boolean isSendFinish = true;//判断是否发送成功; + + private boolean isLast = false; + + private ApplicationRunnerImpl applicationRunner; + + private static final SimpleDateFormat si = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + private String imgPathsStu = "C:\\Users\\Administrator\\Desktop\\imgs\\student";//存放学生人脸图片 + + private String imgPathTea = "C:\\Users\\Administrator\\Desktop\\imgs\\teacher";//存放学生人脸图片 + +// private String imgPaths = "C:\\Users\\taohandong\\Desktop\\img";//存放人脸图片 + + + //每隔5秒取一次数据 + @Scheduled(fixedDelay = 2000) + public void reportCurrentTime() { + System.out.println("任务调度:" + new SimpleDateFormat("HH:mm:ss").format(new Date())); + try { + if (null == applicationRunner) applicationRunner = new ApplicationRunnerImpl(); + if (ApplicationRunnerImpl.isConnect) //MQ是否连接 + getVaild(); + + readImgs(); + // getUser(); + } catch (Exception e) { + getVaild(); + System.out.println("eeeeeeee:" + e.toString()); + e.printStackTrace(); + } + + } + + /** + * 读取图片 + */ + private synchronized void readImgs() { + System.out.println("读取图片:"); + try { + File file = new File(imgPathsStu); + File fileTea = new File(imgPathTea); + if (!file.exists())file.createNewFile(); + if (!fileTea.exists())fileTea.createNewFile(); +// System.out.println("读取图片:"+file.exists()); + if (file.exists()) { + File[] imgs = file.listFiles(); + for (int i = 0; i < imgs.length; i++) { + File imgFile = imgs[i]; + String fileName = imgFile.getName(); + uploadImgs(fileName.split("\\.")[0],imgFile.getAbsolutePath()); + } + } + + if (fileTea.exists()){ + File[] imgsTea = fileTea.listFiles(); + for (int i = 0; i < imgsTea.length; i++) { + File imgFileTea = imgsTea[i]; + String fileTeaName = imgFileTea.getName(); + uploadImgs("teacher"+fileTeaName.split("\\.")[0],imgFileTea.getAbsolutePath()); + } + + } + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + + private void uploadImgs(String card, String filePath) { + String url = "http://localhost:81/facereco/FaceUploadFile"; +// String url = "http://220.189.228.132:81/facereco/FaceUploadFile"; + FileSystemResource resource = new FileSystemResource(filePath); + MultiValueMap map = new LinkedMultiValueMap<>(); + map.add("file", resource); + + + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + headers.set("schoolid", "27"); + headers.set("card", card); + HttpEntity> httpEntity = new HttpEntity<>(map, headers); + String result = restTemplate.postForEntity(url, httpEntity, String.class).getBody(); + if (!TextUtils.isEmpty(result))new File(filePath).delete(); + System.out.println("图片上传结果:" + result); + } + + private void getUser() { + if (isSendFinish) { +// isSendFinish = false; + List list = null; + if (index == 1) { + list = userService.getAllUsers((int) index); + if (list != null && list.size() > 0) + index = Long.parseLong(list.get(1).getUser_id()); + } else { + list = userService.getAllUsers((int) index); + index = 10; + } + System.out.println("user:" + list.size()); + System.out.println("index:" + index); + if (index != 10) + getUser(); +// for (int i = 0; i < list.size(); i++) { +// sendMQ(new ArrayList<>()); +// } + } + + } + + private void getVaild() { + if (isSendFinish) { + isSendFinish = false; + List validcardeventBeanList = null; + if (index == 1) { + validcardeventBeanList = valService.getValids(index); + if (null != validcardeventBeanList && validcardeventBeanList.size() > 0) + index = validcardeventBeanList.get(0).getValidEventID(); +// System.out.println("validcardeventBeanList:" + validcardeventBeanList.toString()); + } else { +// index = 391523; + validcardeventBeanList = valService.getValids(index); +// System.out.println("validcardeventBeanList:" + validcardeventBeanList); + //已经是最后一条了之后返回 + if (null != validcardeventBeanList && validcardeventBeanList.size() > 0 && index == validcardeventBeanList.get(validcardeventBeanList.size() - 1).getValidEventID()) + isLast = true; + else isLast = false; + } + System.out.println("validcardeventBeanList:" + validcardeventBeanList.size()); + if (!isLast) + sendMQ(validcardeventBeanList); + } + } + + /** + * 发送MQ消息 + * + * @param validcardeventBeanList + */ + private void sendMQ(List validcardeventBeanList) { + if (null == validcardeventBeanList) { + isSendFinish = true; + return; + } + if (validcardeventBeanList.size() == 0) { + isSendFinish = true; + return; + } + + for (int i = 0; i < validcardeventBeanList.size(); i++) { + ValidcardeventBean validcardeventBean = validcardeventBeanList.get(i); + applicationRunner.sendMessage(validcardeventBean.getEquipmentSN(), validcardeventBean.getConsumerNO(), validcardeventBean.getInOrOut()); + if (i == validcardeventBeanList.size() - 1) index = validcardeventBeanList.get(i).getValidEventID(); + } + isSendFinish = true; + System.out.println("现在时间:" + si.format(new Date()) + " "); + } + +} diff --git a/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/utils/Tools.java b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/utils/Tools.java new file mode 100644 index 0000000..c0f3ade --- /dev/null +++ b/mq2kb/src/main/java/com/shunzhi/mqtt2kanban/utils/Tools.java @@ -0,0 +1,217 @@ +package com.shunzhi.mqtt2kanban.utils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.IOException; +import java.nio.charset.Charset; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.*; + +/** + * Created by alvin on 17-3-29. + */ +public class Tools { + public static Properties loadProperties() { + Properties properties = new Properties(); + try { + properties.load(ClassLoader.getSystemResourceAsStream("test.properties")); + } catch (IOException e) { + } + return properties; + } + + /** + * 计算签名,参数分别是参数对以及密钥 + * + * @param requestParams 参数对,即参与计算签名的参数 + * @param secretKey 密钥 + * @return 签名字符串 + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + */ + public static String doHttpSignature(Map requestParams, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException { + List paramList = new ArrayList(); + for (Map.Entry entry : requestParams.entrySet()) { + paramList.add(entry.getKey() + "=" + entry.getValue()); + } + Collections.sort(paramList); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < paramList.size(); i++) { + if (i > 0) { + sb.append('&'); + } + sb.append(paramList.get(i)); + } + return macSignature(sb.toString(), secretKey); + } + + /** + * @param text 要签名的文本 + * @param secretKey 阿里云MQ secretKey + * @return 加密后的字符串 + * @throws InvalidKeyException + * @throws NoSuchAlgorithmException + */ + public static String macSignature(String text, String secretKey) throws InvalidKeyException, NoSuchAlgorithmException { + Charset charset = Charset.forName("UTF-8"); + String algorithm = "HmacSHA1"; + Mac mac = Mac.getInstance(algorithm); + mac.init(new SecretKeySpec(secretKey.getBytes(charset), algorithm)); + byte[] bytes = mac.doFinal(text.getBytes(charset)); + return new String(Base64.encodeBase64(bytes), charset); + } + + /** + * 创建HTTPS 客户端 + * + * @return 单例模式的客户端 + * @throws KeyStoreException + * @throws UnrecoverableKeyException + * @throws NoSuchAlgorithmException + * @throws KeyManagementException + */ + private static HttpClient httpClient = null; + + public static HttpClient getHttpsClient() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException { + if (httpClient != null) { + return httpClient; + } + X509TrustManager xtm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[]{}; + } + }; + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, new TrustManager[]{xtm}, null); + SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE); + Registry sfr = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", scsf).build(); + PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sfr); + httpClient = HttpClientBuilder.create().setConnectionManager(pcm).build(); + return httpClient; + } + + public static HttpClient createHttpsClient() throws KeyManagementException, NoSuchAlgorithmException { + X509TrustManager xtm = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[]{}; + } + }; + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, new TrustManager[]{xtm}, null); + SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE); + Registry sfr = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", scsf).build(); + PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sfr); + return HttpClientBuilder.create().setConnectionManager(pcm).build(); + } + + /** + * 发起Https Get请求,并得到返回的JSON响应 + * + * @param url 接口Url + * @param params 参数u对 + * @return + * @throws IOException + * @throws KeyStoreException + * @throws UnrecoverableKeyException + * @throws NoSuchAlgorithmException + * @throws KeyManagementException + */ + public static JSONObject httpsGet(String url, Map params) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException { + HttpClient client = Tools.getHttpsClient(); + JSONObject jsonResult = null; + //发送get请求 + List urlParameters = new ArrayList(); + for (Map.Entry entry : params.entrySet()) { + urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + String paramUrl = URLEncodedUtils.format(urlParameters, Charset.forName("UTF-8")); + HttpGet request = new HttpGet(url + "?" + paramUrl); + HttpResponse response = client.execute(request); + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + String strResult = EntityUtils.toString(response.getEntity()); + jsonResult = JSON.parseObject(strResult); + } + return jsonResult; + } + + /** + * 工具方法,发送一个http post请求,并尝试将响应转换为JSON + * + * @param url 请求的方法名url + * @param params 参数表 + * @return 如果请求成功则返回JSON, 否则抛异常或者返回空 + * @throws IOException + */ + public static JSONObject httpsPost(String url, Map params) throws IOException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + JSONObject jsonResult = null; + //发送get请求 + HttpClient client = getHttpsClient(); + HttpPost request = new HttpPost(url); + List urlParameters = new ArrayList(); + for (Map.Entry entry : params.entrySet()) { + urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + HttpEntity postParams = new UrlEncodedFormEntity(urlParameters); + request.setEntity(postParams); + HttpResponse response = client.execute(request); + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + String strResult = EntityUtils.toString(response.getEntity()); + jsonResult = JSON.parseObject(strResult); + } + return jsonResult; + } +} diff --git a/mq2kb/src/main/resources/application.properties b/mq2kb/src/main/resources/application.properties new file mode 100644 index 0000000..ce3e281 --- /dev/null +++ b/mq2kb/src/main/resources/application.properties @@ -0,0 +1,22 @@ +server.port=10086 + +spring.datasource.url=jdbc:mysql://10.1.16.3:3307/jcacardone?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC +spring.datasource.username=thd +spring.datasource.password=654321 +#spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC +#spring.datasource.username=root +#spring.datasource.password=123456 +#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +#sql +#spring.datasource.username=szjxtuser +#spring.datasource.password=RQminVCJota3H1u8bBYH +#spring.datasource.url=jdbc:sqlserver://116.62.155.137:33419;database=xiaoan +#spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver + + +mybatis.typealiases-package=com.shunzhi.mqtt2kanban.mapper + +mybatis.config-location=classpath:mybatis/mybatis-config.xml +mybatis.mapper-locations=classpath:mybatis/mapper/*.xml + diff --git a/mq2kb/src/main/resources/mybatis/mapper/ValidcardeventMapper.xml b/mq2kb/src/main/resources/mybatis/mapper/ValidcardeventMapper.xml new file mode 100644 index 0000000..88f6cc4 --- /dev/null +++ b/mq2kb/src/main/resources/mybatis/mapper/ValidcardeventMapper.xml @@ -0,0 +1,16 @@ + + + + + + + + + diff --git a/mq2kb/src/main/resources/mybatis/mybatis-config.xml b/mq2kb/src/main/resources/mybatis/mybatis-config.xml new file mode 100644 index 0000000..46e595a --- /dev/null +++ b/mq2kb/src/main/resources/mybatis/mybatis-config.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/mq2kb/src/main/resources/test.properties b/mq2kb/src/main/resources/test.properties new file mode 100644 index 0000000..117b59c --- /dev/null +++ b/mq2kb/src/main/resources/test.properties @@ -0,0 +1,23 @@ +#use the mqtt endpoint in mq console +brokerUrl=tcp://post-cn-4590mq2hr03.mqtt.aliyuncs.com:1883 +#brokerUrl=tcp://127.0.0.1:61613 +sslBrokerUrl=ssl://XXXXX:8883 +#use the mq topic as parent topic +topic=Topic_Quene_Test +#topic=chatgeneral +#use the ak from aliyun ak console +accessKey=UimvLVp0Wj90P88u +#accessKey=admin +#use the sk from aliyun ak console +secretKey=TE4rZenITG27tiQqHx9qINjx71Nws7 +#secretKey=password +#use the groupId from mq console +groupId=GID_HFJSIURFHAQO110 +qos=0 +cleanSession=false +## +##this param is use for mq client send or receive mqtt msg +## +producerId=PID_Producer4008262468 +consumerId=CID_Consumer4008262468 +regionId =post-cn-4590mq2hr03 \ No newline at end of file diff --git a/mq2kb/src/test/java/com/shunzhi/mqtt2kanban/Mqtt2kanbanApplicationTests.java b/mq2kb/src/test/java/com/shunzhi/mqtt2kanban/Mqtt2kanbanApplicationTests.java new file mode 100644 index 0000000..c2a6e8b --- /dev/null +++ b/mq2kb/src/test/java/com/shunzhi/mqtt2kanban/Mqtt2kanbanApplicationTests.java @@ -0,0 +1,17 @@ +package com.shunzhi.mqtt2kanban; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class Mqtt2kanbanApplicationTests { + + @Test + public void contextLoads() { + + } + +} -- libgit2 0.21.0