ffd78d5e by ja

no message

0 parents
Showing 70 changed files with 3089 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
No preview for this file type
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>demo</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="cloudfoundry.standalone.app" version="1.0"/>
</faceted-project>
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# 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
#
# Look for the Apple JDKs first to preserve the existing behaviour, and then look
# for the new JDKs provided by Oracle.
#
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
#
# Apple JDKs
#
export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
#
# Oracle JDKs
#
export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
fi
if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
#
# Apple JDKs
#
export JAVA_HOME=`/usr/libexec/java_home`
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 Migwn, 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
# 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"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
local basedir=$(pwd)
local wdir=$(pwd)
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
wdir=$(cd "$wdir/.."; pwd)
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# 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} "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM 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 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
set MAVEN_CMD_LINE_ARGS=%*
@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="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
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%
\ No newline at end of file
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>kmr_dp_HDP</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>kmr_dp_HDP</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
<!-- https://mvnrepository.com/artifact/wsdl4j/wsdl4j -->
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.3</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
</dependency>
<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
<version>4.0.3</version>
</dependency>
<!--通用Mapper插件-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.wink</groupId>
<artifactId>wink-client</artifactId>
<version>1.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Manifest-Version: 1.0
Class-Path: spring-tx-4.2.5.RELEASE.jar websocket-api-9.2.15.v20160210
.jar spring-boot-starter-1.3.3.RELEASE.jar urlrewritefilter-4.0.3.jar
mybatis-spring-boot-starter-1.0.0.jar spring-boot-starter-jdbc-1.3.3
.RELEASE.jar tomcat-jdbc-8.0.32.jar javax.websocket-api-1.0.jar valid
ation-api-1.1.0.Final.jar aopalliance-1.0.jar xml-apis-1.0.b2.jar asm
-commons-5.0.1.jar jaxb-impl-2.2.1.1.jar jetty-servlet-9.2.15.v201602
10.jar spring-data-mongodb-1.8.4.RELEASE.jar websocket-client-9.2.15.
v20160210.jar jetty-server-9.2.15.v20160210.jar jetty-xml-9.2.15.v201
60210.jar javax-websocket-server-impl-9.2.15.v20160210.jar jackson-an
notations-2.6.5.jar commons-codec-1.9.jar mysql-connector-java-5.1.38
.jar dom4j-1.6.1.jar jetty-util-9.2.15.v20160210.jar commons-pool2-2.
4.2.jar mongo-java-driver-2.13.3.jar jboss-logging-3.3.0.Final.jar co
mmons-logging-1.0.4.jar h2-1.4.191.jar mybatis-spring-1.2.3.jar jaxb-
api-2.2.jar jetty-jndi-9.2.15.v20160210.jar wink-client-1.3.0.jar hib
ernate-validator-5.2.4.Final.jar websocket-server-9.2.15.v20160210.ja
r log4j-over-slf4j-1.7.16.jar mapper-3.3.4.jar json-20140107.jar tomc
at-embed-core-8.0.32.jar asm-tree-5.0.1.jar spring-context-4.2.5.RELE
ASE.jar jsr311-api-1.1.1.jar spring-aop-4.2.5.RELEASE.jar snakeyaml-1
.16.jar javax.annotation-api-1.2.jar wink-common-1.3.0.jar commons-io
-2.1.jar jetty-security-9.2.15.v20160210.jar asm-5.0.1.jar logback-cl
assic-1.1.5.jar tomcat-juli-8.0.32.jar classmate-1.1.0.jar jstl-1.2.j
ar spring-boot-starter-data-mongodb-1.3.3.RELEASE.jar spring-beans-4.
2.5.RELEASE.jar spring-boot-autoconfigure-1.3.3.RELEASE.jar logback-c
ore-1.1.5.jar spring-jdbc-4.2.5.RELEASE.jar slf4j-api-1.7.16.jar comm
ons-lang3-3.3.2.jar jetty-http-9.2.15.v20160210.jar geronimo-annotati
on_1.1_spec-1.0.jar jedis-2.7.3.jar spring-core-4.2.5.RELEASE.jar jet
ty-io-9.2.15.v20160210.jar stax-api-1.0-2.jar spring-boot-starter-web
-1.3.3.RELEASE.jar spring-boot-starter-tomcat-1.3.3.RELEASE.jar jacks
on-databind-2.6.5.jar mybatis-3.3.0.jar commons-httpclient-3.1.jar je
tty-servlets-9.2.15.v20160210.jar jul-to-slf4j-1.7.16.jar javax.servl
et-api-3.1.0.jar jetty-annotations-9.2.15.v20160210.jar jcl-over-slf4
j-1.7.16.jar activation-1.1.jar jetty-webapp-9.2.15.v20160210.jar spr
ing-boot-starter-validation-1.3.3.RELEASE.jar spring-boot-1.3.3.RELEA
SE.jar jackson-core-2.6.5.jar tomcat-embed-websocket-8.0.32.jar sprin
g-boot-starter-jetty-1.3.3.RELEASE.jar spring-context-support-4.2.5.R
ELEASE.jar spring-webmvc-4.2.5.RELEASE.jar spring-boot-starter-loggin
g-1.3.3.RELEASE.jar tomcat-embed-el-8.0.32.jar commons-fileupload-1.2
.2.jar jetty-continuation-9.2.15.v20160210.jar spring-webmvc-portlet-
4.2.5.RELEASE.jar spring-web-4.2.5.RELEASE.jar javax-websocket-client
-impl-9.2.15.v20160210.jar spring-boot-starter-redis-1.3.3.RELEASE.ja
r websocket-servlet-9.2.15.v20160210.jar persistence-api-1.0.jar tomc
at-embed-logging-juli-8.0.32.jar jetty-plus-9.2.15.v20160210.jar spri
ng-data-commons-1.11.4.RELEASE.jar spring-data-redis-1.5.0.RELEASE.ja
r spring-expression-4.2.5.RELEASE.jar websocket-common-9.2.15.v201602
10.jar mybatis-spring-boot-autoconfigure-1.0.0.jar
Main-Class: com.example.DemoApplication
package com.example;
import com.example.filter.CORSFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import javax.servlet.MultipartConfigElement;
@MapperScan(basePackages = {"com.example.mapper"})
@SpringBootApplication
public class DemoApplication extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CORSFilter()).addPathPatterns("/**");
}
}
package com.example.controller;
import com.example.models.ImgInfo;
import com.example.service.ImgInfoService;
import com.example.support.model.MessageEntity;
import com.example.utils.file.DefaultFileUpload;
import com.example.utils.file.FileUploadInfo;
import com.example.utils.md5.MD5Utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
/**
* Created by JA on 17/7/3.
*/
@RequestMapping("/kmr/img")
@RestController
public class ImgInfoController {
@Autowired
private ImgInfoService imgInfoService;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public MessageEntity upload(HttpServletRequest request,@RequestPart final MultipartFile file,@ModelAttribute ImgInfo imgInfo,
String access_token, String state, String timestamp, String rands, String jsondata, String checksum, String secret) {
MessageEntity.Builder builder = new MessageEntity.Builder(request);
String code = "9000";
String openid = imgInfo.getOpenid();
boolean flag = false;
if(StringUtils.isNotBlank(jsondata)){
jsondata = URLDecoder.decode(jsondata);
ObjectMapper objectMapper = new ObjectMapper();
Map map = null;
try {
map = objectMapper.readValue(jsondata, Map.class);
} catch (IOException e) {
e.printStackTrace();
}
if(map != null && map.containsKey("gtmc_code") && map.get("gtmc_code").toString().equals("200")){
String checksum1 = MD5Utils.hash(access_token + openid + state + timestamp + rands + jsondata + secret);
if(checksum1.equals(checksum)){
imgInfo.setGtmcUid(map.get("gtmc_uid").toString());
imgInfo.setGtmcDepartment(map.get("gtmc_department").toString());
imgInfo.setGtmcName(map.get("gtmc_name").toString());
FileUploadInfo info = new DefaultFileUpload().upload("/Users/JA/Documents/img", file);
String url = info.getUrl();
imgInfo.setImgUrl(url);
boolean b = this.imgInfoService.create(imgInfo);
if(b){
code = "2000";
flag = true;
}
}
}
}
return builder.success(flag).content(imgInfo).code(code).create();
}
@RequestMapping("/getbyopenid")
public MessageEntity getbyopenid(HttpServletRequest request, @RequestParam String openid) {
MessageEntity.Builder builder = new MessageEntity.Builder(request);
ImgInfo imgInfo = this.imgInfoService.getNewByOpenid(openid);
return builder.success(true).code("2000").content(imgInfo).create();
}
}
package com.example.controller;
import com.example.mapper.ConfigInfoMapper;
import com.example.models.ConfigInfo;
import com.example.models.ScoreLogInfo;
import com.example.service.ScoreLogInfoService;
import com.example.support.model.MessageEntity;
import com.example.utils.md5.MD5Utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by JA on 17/7/3.
*/
@RequestMapping("/kmr/rank")
@RestController
public class ScoreLogInfoController {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Autowired
private ScoreLogInfoService scoreLogInfoService;
@Autowired
private ConfigInfoMapper configInfoMapper;
@RequestMapping("/save")
public MessageEntity save(HttpServletRequest request, @ModelAttribute ScoreLogInfo scoreLogInfo,
String access_token, String state, String timestamp, String rands, String jsondata, String checksum, String secret) {
MessageEntity.Builder builder = new MessageEntity.Builder(request);
boolean flag = false;
String code = "9000";
String openid = scoreLogInfo.getOpenid();
if(StringUtils.isNotBlank(jsondata)){
jsondata = URLDecoder.decode(jsondata);
ObjectMapper objectMapper = new ObjectMapper();
Map map = null;
try {
map = objectMapper.readValue(jsondata, Map.class);
} catch (IOException e) {
e.printStackTrace();
}
if(map != null && map.containsKey("gtmc_code") && map.get("gtmc_code").toString().equals("200")){
String checksum1 = MD5Utils.hash(access_token +openid +state +timestamp +rands +jsondata +secret);
if(checksum1.equals(checksum)){
scoreLogInfo.setGtmcUid(map.get("gtmc_uid").toString());
scoreLogInfo.setGtmcDepartment(map.get("gtmc_department").toString());
scoreLogInfo.setGtmcName(map.get("gtmc_name").toString());
code = this.scoreLogInfoService.save(scoreLogInfo);
if(code.equals("2000")){
flag = true;
}
}
}
}
return builder.success(flag).code(code).create();
}
@RequestMapping("/ranking")
public MessageEntity ranking(HttpServletRequest request, @RequestParam String openid,@RequestParam(defaultValue = "10") Long limit) {
MessageEntity.Builder builder = new MessageEntity.Builder(request);
Map<String,Object> map = new HashMap<>();
List<Map<String, Object>> rankingList = this.scoreLogInfoService.getRankingList(limit);
Map<String, Object> myRanking = this.scoreLogInfoService.getMyRanking(openid);
map.put("rankingList",rankingList);
map.put("myRanking",myRanking);
return builder.success(true).code("2000").content(map).create();
}
@RequestMapping("/counttoday")
public MessageEntity counttoday(HttpServletRequest request, @RequestParam String openid) {
MessageEntity.Builder builder = new MessageEntity.Builder(request);
long l = this.scoreLogInfoService.countToDay(openid);
ConfigInfo configInfo = configInfoMapper.get();
Long maxTime = configInfo.getMaxTime();
long lastTime = maxTime - l;
return builder.success(true).code("2000").content(lastTime).create();
}
@RequestMapping("/sum")
public MessageEntity sum(HttpServletRequest request, @RequestParam String openid) {
MessageEntity.Builder builder = new MessageEntity.Builder(request);
long l = this.scoreLogInfoService.countSum(openid);
return builder.success(true).code("2000").content(l).create();
}
// public static void main(String[] args) {
// String access_token="4_ei8KYHlVKGE8zLguYGl7iHLEBf28u4nAzxocOMXGvzKoPxpU3Dxr_kq8cQlfDD34qFiJWgQpYxj3k3gobg0hyA";
// String openid="oUmdXt90H2A784gfU7ChtsBsxU48";
// String state="xxxx";
// String timestamp="1511923072";
// String rands="KeXxdzc7gQxkw6sE";
// String jsondata="%7B%22gtmc_code%22%3A404%7D";
// jsondata = URLDecoder.decode(jsondata);
// System.out.println(jsondata);
// String checksum="5d179dbfdb49cafd3f27100df12d3b99";
// String secret="digi-campaign-2015";
// System.out.println(URLEncoder.encode("{\"gtmc_code\":404,\"gtmc_uid\":\"gtmc_uid\",\"gtmc_department\":\"gtmc_department\",\"gtmc_name\":\"gtmc_name\"}"));
// String checksum1 = MD5Utils.hash(access_token +openid +state +timestamp +rands +jsondata +secret);
// System.out.println(checksum);
// System.out.println(checksum1);
// }
}
\ No newline at end of file
package com.example.controller;
import com.example.models.ImgInfo;
import com.example.service.ImgInfoService;
import com.example.service.http.ClientConfigService;
import com.example.service.http.ClientConfigServiceImpl;
import com.example.service.http.HttpPostService;
import com.example.support.model.MessageEntity;
import com.example.utils.file.DefaultFileUpload;
import com.example.utils.file.FileUploadInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.wink.client.ClientResponse;
import org.apache.wink.client.Resource;
import org.apache.wink.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* Created by JA on 17/7/3.
*/
@RequestMapping("/kmr/wx")
@RestController
public class WxController {
// String jssdkurl = "http://gfwp.gac-toyota.com.cn/GTMCfamily/index.php/campaign/api2/getjssdk";
//
// String getopenidurl = "http://gfwp.gac-toyota.com.cn/GTMCfamily/index.php/campaign/api2/getjssdk";
//
// @Autowired
// private HttpPostService httpPostService;
//
//
// @RequestMapping("/getjssdk")
// public MessageEntity getjssdk(HttpServletRequest request, @RequestParam String url) {
// MessageEntity.Builder builder = new MessageEntity.Builder(request);
// String newUrl = jssdkurl + "?url="+ url;
// Map<String, Object> map = null;
// try {
// map = httpPostService.httpPost(newUrl, null);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return builder.success(true).code("2000").content(map).create();
// }
@RequestMapping("/getUser")
public MessageEntity oauth(HttpServletRequest request, @RequestParam String accessToken, String openid) {
MessageEntity.Builder builder = new MessageEntity.Builder(request);
ClientConfigService configService = new ClientConfigServiceImpl();
RestClient restClient = new RestClient(configService.getClientConfig());
Resource resource = restClient.resource("https://api.weixin.qq.com/sns/userinfo");
resource.queryParam("access_token", accessToken);
resource.queryParam("openid", openid);
resource.queryParam("lang", "zh_CN");
ClientResponse response = resource.get();
String responseEntity = response.getEntity(String.class);
Map readValue = null;
// System.out.println("responseEntity:::"+responseEntity);
ObjectMapper mapper = new ObjectMapper();
try {
readValue = mapper.readValue(responseEntity, Map.class);
if (null != readValue.get("errcode")) {
return null;
}
} catch (IOException e) {
e.printStackTrace();;
}
return builder.success(true).code("2000").content(readValue).create();
}
}
package com.example.filter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by caobug on 15/7/29.
*/
public class CORSFilter extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept," +
"Origin,Access-Control-Request-Method,Access-Control-Request-Headers,hdp-application-id," +
"hdp-rest-api-key,hdp_wx_user_info_json,wxu_session");
return super.preHandle(request, response, handler);
}
}
\ No newline at end of file
package com.example.mapper;
import com.example.models.ConfigInfo;
/**
* Created by JA on 17/7/17.
*/
public interface ConfigInfoMapper {
ConfigInfo get();
}
package com.example.mapper;
import com.example.models.ImgInfo;
import org.apache.ibatis.annotations.Param;
/**
* Created by JA on 17/7/17.
*/
public interface ImgInfoMapper {
boolean create(ImgInfo imgInfo);
ImgInfo getNewByOpenid(@Param("openid") String openid);
}
package com.example.mapper;
import com.example.models.ScoreLogInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* Created by JA on 17/7/17.
*/
public interface ScoreLogInfoMapper {
boolean create(ScoreLogInfo scoreLogInfo);
List<Map<String,Object>> getRankingList(@Param("limit") Long limit);
Map<String,Object> getMyRanking(@Param("openid") String openid);
long countByDay(@Param("openid") String openid,@Param("startDate") String startDate,@Param("endDate") String endDate);
long countSum(@Param("openid") String openid);
}
package com.example.models;
import java.util.Date;
/**
* Created by JA on 17/7/17.
*/
public class ConfigInfo {
private Date offTime;
private Double minScore;
private Long maxTime;
public Date getOffTime() {
return offTime;
}
public void setOffTime(Date offTime) {
this.offTime = offTime;
}
public Double getMinScore() {
return minScore;
}
public void setMinScore(Double minScore) {
this.minScore = minScore;
}
public Long getMaxTime() {
return maxTime;
}
public void setMaxTime(Long maxTime) {
this.maxTime = maxTime;
}
}
package com.example.models;
import java.util.Date;
/**
* Created by JA on 17/7/17.
*/
public class ImgInfo {
Long id;
String openid;
String nickname;
String headimgurl;
String imgUrl;
String blessingWords;
String sharingDescribe;
String gtmcUid;
String gtmcName;
String gtmcDepartment;
Date createAt;
Date updateAt;
Integer status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getHeadimgurl() {
return headimgurl;
}
public void setHeadimgurl(String headimgurl) {
this.headimgurl = headimgurl;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public Date getUpdateAt() {
return updateAt;
}
public void setUpdateAt(Date updateAt) {
this.updateAt = updateAt;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getBlessingWords() {
return blessingWords;
}
public void setBlessingWords(String blessingWords) {
this.blessingWords = blessingWords;
}
public String getSharingDescribe() {
return sharingDescribe;
}
public void setSharingDescribe(String sharingDescribe) {
this.sharingDescribe = sharingDescribe;
}
public String getGtmcUid() {
return gtmcUid;
}
public void setGtmcUid(String gtmcUid) {
this.gtmcUid = gtmcUid;
}
public String getGtmcName() {
return gtmcName;
}
public void setGtmcName(String gtmcName) {
this.gtmcName = gtmcName;
}
public String getGtmcDepartment() {
return gtmcDepartment;
}
public void setGtmcDepartment(String gtmcDepartment) {
this.gtmcDepartment = gtmcDepartment;
}
}
package com.example.models;
import java.util.Date;
/**
* Created by JA on 17/7/17.
*/
public class ScoreLogInfo {
private Long id;
private String openid;
private String nickname;
private String headimgurl;
String gtmcUid;
String gtmcName;
String gtmcDepartment;
private Double score;
private Date createAt;
private Integer status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getHeadimgurl() {
return headimgurl;
}
public void setHeadimgurl(String headimgurl) {
this.headimgurl = headimgurl;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getGtmcUid() {
return gtmcUid;
}
public void setGtmcUid(String gtmcUid) {
this.gtmcUid = gtmcUid;
}
public String getGtmcName() {
return gtmcName;
}
public void setGtmcName(String gtmcName) {
this.gtmcName = gtmcName;
}
public String getGtmcDepartment() {
return gtmcDepartment;
}
public void setGtmcDepartment(String gtmcDepartment) {
this.gtmcDepartment = gtmcDepartment;
}
}
package com.example.service;
import com.example.models.ImgInfo;
/**
* Created by JA on 17/7/17.
*/
public interface ImgInfoService {
boolean create(ImgInfo imgInfo);
ImgInfo getNewByOpenid(String openid);
}
package com.example.service;
import com.example.mapper.ImgInfoMapper;
import com.example.models.ImgInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* Created by JA on 17/11/22.
*/
@Service
public class ImgInfoServiceImpl implements ImgInfoService {
@Autowired
private ImgInfoMapper imgInfoMapper;
@Override
public boolean create(ImgInfo imgInfo) {
imgInfo.setStatus(1);
imgInfo.setCreateAt(new Date());
imgInfo.setUpdateAt(new Date());
return this.imgInfoMapper.create(imgInfo);
}
@Override
public ImgInfo getNewByOpenid(String openid) {
return this.imgInfoMapper.getNewByOpenid(openid);
}
}
package com.example.service;
import com.example.models.ScoreLogInfo;
import java.util.List;
import java.util.Map;
/**
* Created by JA on 17/11/21.
*/
public interface ScoreLogInfoService {
String save(ScoreLogInfo scoreLogInfo);
List<Map<String,Object>> getRankingList(Long limit);
Map<String,Object> getMyRanking(String openid);
long countToDay(String openid);
long countSum(String openid);
}
package com.example.service;
import com.example.mapper.ConfigInfoMapper;
import com.example.mapper.ScoreLogInfoMapper;
import com.example.models.ConfigInfo;
import com.example.models.ScoreLogInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* Created by JA on 17/11/22.
*/
@Service
public class ScoreLogInfoServiceImpl implements ScoreLogInfoService {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Autowired
private ScoreLogInfoMapper scoreLogInfoMapper;
@Autowired
private ConfigInfoMapper configInfoMapper;
@Override
public String save(ScoreLogInfo scoreLogInfo) {
String code = "2000";
ConfigInfo configInfo = configInfoMapper.get();
Date offTime = configInfo.getOffTime();
Long maxTime = configInfo.getMaxTime();
Double minScore = configInfo.getMinScore();
Date now = new Date();
long nowTime = now.getTime();
long offTimeTime = offTime.getTime();
if(nowTime > offTimeTime){
code = "9901";
}else{
long count = this.countToDay(scoreLogInfo.getOpenid());
if(count >= maxTime){
code = "9902";
}else{
Double score = scoreLogInfo.getScore();
if(minScore > score){
code = "9903";
}else{
scoreLogInfo.setCreateAt(new Date());
scoreLogInfo.setStatus(1);
boolean b = this.scoreLogInfoMapper.create(scoreLogInfo);
if(!b){
code = "9904";
}
}
}
}
return code;
}
@Override
public List<Map<String, Object>> getRankingList(Long limit) {
return this.scoreLogInfoMapper.getRankingList(limit);
}
@Override
public Map<String, Object> getMyRanking(String openid) {
return this.scoreLogInfoMapper.getMyRanking(openid);
}
@Override
public long countToDay(String openid) {
Date date = new Date();
String format = sdf.format(date);
String startDate = format + " 00:00:00";
String endDate = format + " 23:59:59";
return this.scoreLogInfoMapper.countByDay(openid,startDate,endDate);
}
@Override
public long countSum(String openid) {
return this.scoreLogInfoMapper.countSum(openid);
}
}
package com.example.service.http;
import org.apache.wink.client.ClientConfig;
/**
* Created by caobug on 15/5/12.
*/
public interface ClientConfigService {
ClientConfig getClientConfig();
}
\ No newline at end of file
package com.example.service.http;
import org.apache.wink.client.ClientConfig;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
/**
* Created by caobug on 15/5/12.
*/
public class ClientConfigServiceImpl implements ClientConfigService {
public ClientConfig getClientConfig() {
ClientConfig myConfig = new ClientConfig();
SSLContext sc;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, getTrustManager(), new java.security.SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
return null;
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
myConfig.setBypassHostnameVerification(true);
myConfig.connectTimeout(100000);
myConfig.readTimeout(100000);
myConfig.followRedirects(false);
return myConfig;
}
private TrustManager[] getTrustManager() {
return new TrustManager[]{new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}};
}
}
\ No newline at end of file
package com.example.service.http;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2015/10/10-16:56.
*
* 派加积分HTTP POST接口
*/
public interface HttpPostService {
void httpPostAsync(String url, Map<String, Object> postData);
Map<String, Object> httpPost(String url, Map<String, Object> postData) throws JsonProcessingException, IOException;
Map<String, Object> httpPostList(String url, List<Map<String, Object>> postData) throws JsonProcessingException, IOException;
String httpPostString(String url, Map<String, Object> postData);
List<Map<String, Object>> httpPostXml(String url, String postData);
}
package com.example.service.http;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.wink.client.*;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2015/10/10-17:00.
*/
@Service("HttpPostService")
public class HttpPostServiceImpl implements HttpPostService {
private final ClientConfig CONFIG = new ClientConfigServiceImpl().getClientConfig();
private final ClientConfig ASYNC_CONFIG = new ClientConfigServiceImpl().getClientConfig();
@Override
@Async
public void httpPostAsync(String url, Map<String, Object> postData) {
// logger.debug("http post start [url:{}] [param:{}]", url, postData);
// logger.debug("http post postData:{}", postData);
ObjectMapper objectMapper = new ObjectMapper();
try {
String postDataString = objectMapper.writeValueAsString(postData);
String responseEntity = post(url, postDataString, ASYNC_CONFIG);
} catch (JsonProcessingException e) {
} catch (ClientRuntimeException e) {
}
}
/**
*
*
*
* @param url 请求的url
* @param postData post的数据
* @return 请求响应内容(解析后的结果)
*/
@Override
public Map<String, Object> httpPost(String url, Map<String, Object> postData) {
// logger.debug("http post start url:{}", url);
// logger.debug("http post postData:{}", postData);
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> readValue = null;
try {
String postDataString = objectMapper.writeValueAsString(postData);
String responseEntity = post(url, postDataString, CONFIG);
readValue = objectMapper.readValue(responseEntity, new TypeReference<Map<String, Object>>() {
});
} catch (JsonProcessingException e) {
} catch (IOException e) {
} catch (ClientRuntimeException e) {
}
return readValue;
}
/**
*
*
*
* @param url 请求的url
* @param postData post的数据
* @return 请求响应内容(解析后的结果)
*/
@Override
public String httpPostString(String url, Map<String, Object> postData) {
String responseEntity = null;
try {
responseEntity = postString(url, postData, CONFIG);
} catch (Exception e){
e.printStackTrace();
}
return responseEntity;
}
/**
*
*
*
* @param url 请求的url
* @param postData post的数据
* @return 请求响应内容(解析后的结果)
*/
@Override
public Map<String, Object> httpPostList(String url, List<Map<String, Object>> postData) {
// logger.debug("http post start url:{}", url);
// logger.debug("http post postData:{}", postData);
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> readValue = null;
try {
String postDataString = objectMapper.writeValueAsString(postData);
String responseEntity = post(url, postDataString, CONFIG);
readValue = objectMapper.readValue(responseEntity, new TypeReference<Map<String, Object>>() {
});
} catch (JsonProcessingException e) {
} catch (IOException e) {
} catch (ClientRuntimeException e) {
}
return readValue;
}
private String post(String url, String postParams, ClientConfig config) {
//创建http访问
Resource resource = new RestClient(config).resource(url);
resource.contentType("application/json;charset=UTF-8");
ClientResponse response = resource.post(postParams);
String responseEntity = response.getEntity(String.class);
return responseEntity;
}
/**
*
*
*
* @param url 请求的url
* @param postData post的数据
* @return 请求响应内容(解析后的结果)
*/
@Override
public List<Map<String, Object>> httpPostXml(String url, String postData) {
// logger.debug("http post start url:{}", url);
// logger.debug("http post postData:{}", postData);
List<Map<String, Object>> list = null;
try {
String responseEntity = post(url, postData, CONFIG);
System.out.println(responseEntity);
list = resolveXml(responseEntity);
} catch (Exception e) {
}
return list;
}
@SuppressWarnings("unchecked")
public static List<Map<String, Object>> resolveXml(String xmlString) {
List<Map<String, Object>> result = new ArrayList<>();
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
Element rootElement = document.getRootElement();
re(result,rootElement);
} catch (DocumentException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
@SuppressWarnings("unchecked")
private static List<Map<String, Object>> re(List<Map<String, Object>> pMap,Element rootElement){
List<Map<String, Object>> result = new ArrayList<>();
Map<String, Object> m = new HashMap<>();
for (Element element : (Iterable<Element>) rootElement.elements()) {
if(element.elements() != null && element.elements().size() != 0){
re(result,element);
m.put(element.getName(),result);
}else{
m.put(element.getName(), element.getStringValue());
}
}
pMap.add(m);
return pMap;
}
private String postXml(String url, String postParams, ClientConfig config) {
//创建http访问
Resource resource = new RestClient(config).resource(url);
resource.contentType("application/xml;charset=UTF-8");
ClientResponse response = resource.post(postParams);
String responseEntity = response.getEntity(String.class);
return responseEntity;
}
private String postString(String url, Map<String,Object> postParams, ClientConfig config) {
//创建http访问
Resource resource = new RestClient(config).resource(url);
if(postParams != null){
for(String key:postParams.keySet()){
resource.queryParam(key,postParams.get(key));
}
}
ClientResponse response = resource.post(null);
String responseEntity = response.getEntity(String.class);
return responseEntity;
}
}
package com.example.support.model;
import org.apache.commons.lang3.RandomStringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
/**
* 响应的消息实体,使用例子如下:
*
* @FormToken(produce = true)
* @ResponseBody
* @RequestMapping(value = "/create/test", method = RequestMethod.GET)
* public Object test(HttpServletRequest request) throws JsonProcessingException {
* Object map = new HashMap<>();
* map.put("redirect", "http://www.baidu.com/");
* return new MessageEntity.Builder(request).code(MessageCodeEnum.ALREADY_EXISTS).
* msg("账户已存在").content(map).success(false).create();
* }
* <p/>
* 构造对此对象时,消息不传时会默认初始化一些值。以下键值对左边表示属性,右边表示默认值:requestId=null, msg=null, seccuess=false
* , code=0, content=null,而resubmitToken已内置在构造器中,无需担忧默认为空。通常该值是从 SESSION 中取,为了防止TOKEN 重复提交功能生效,
* 请勿自定义resubmitToken值。正确的做法是传入request
*/
public class MessageEntity implements Serializable {
private static final long serialVersionUID = 5165069341805388402L;
private final String msg; // 消息
private final boolean success; // 操作成功与否
private final String resubmitToken; // post token
private final String code; // 状态码
private final Object content; // 内容主体
/**
* 请选构造 MessageEntity.Builder 对象
*
* @param builder
*/
public MessageEntity(Builder builder) {
this.msg = builder.msg;
this.success = builder.success;
this.resubmitToken = builder.resubmitToken;
this.code = builder.code;
this.content = builder.content;
}
public String getMsg() {
return msg;
}
public boolean isSuccess() {
return success;
}
public String getResubmitToken() {
return resubmitToken;
}
public String getCode() {
return code;
}
public Object getContent() {
return content;
}
@Override
public String toString() {
return "MessageEntity{" +
", msg='" + msg + '\'' +
", success=" + success +
", resubmitToken='" + resubmitToken + '\'' +
", code=" + code +
", content=" + content +
'}';
}
public static class Builder {
private final String resubmitToken; // post token
private String msg; // 消息
private boolean success; // 操作成功与否
private String code; // 状态码
private Object content; // 内容主体
/**
* 新 token
*
* @param request
*/
public Builder(HttpServletRequest request) {
if (null != request) {
this.resubmitToken = getToken();
// request.getSession().setAttribute(FormTokenInterceptor.TOKEN_NAME, this.resubmitToken);
} else {
this.resubmitToken = null;
}
}
/**
* 消息,需要解决国际化问题
*
* @param msg
* @return
*/
public Builder msg(String msg) {
this.msg = msg;
return this;
}
/**
* 是否成功
*
* @param success
* @return
*/
public Builder success(boolean success) {
this.success = success;
return this;
}
public Builder code(String code) {
this.code = code;
return this;
}
/**
* 消息主体,根据前端需求构造
*
* @param content
* @return
*/
public Builder content(Object content) {
this.content = content;
return this;
}
public MessageEntity create() {
return new MessageEntity(this);
}
public String getToken() {
return RandomStringUtils.random(32, 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
}
}
}
\ No newline at end of file
package com.example.utils;
import java.util.UUID;
/**
* RandomStringUtils
* <p/>
* Created by caobug on 15/6/23.
*/
public class RandomStringUtils extends org.apache.commons.lang3.RandomStringUtils {
public static final String ARTICLE_KEY_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String getString() {
return UUID.randomUUID().toString().replace("-", "");
}
/**
* 根据字母表生成指定位数随机字符串
*
* @param length 随机长度
* @return 随机字符串
*/
public static String getString(int length) {
return random(length, ARTICLE_KEY_ALPHABET);
}
}
\ No newline at end of file
package com.example.utils.check;
import javax.servlet.http.HttpServletRequest;
/**
* Created by Administrator on 2017/4/1.
*/
public class CheckRefererUtils {
public static boolean checkReferer(HttpServletRequest request){
return true;
// String referer = request.getHeader("REFERER");
// String host = "lucky.csair.com";
//
// System.out.println("开始校验 referer:"+referer);
// if(referer == null || referer.indexOf(host) < 0){
// System.out.println("referer错误 referer:"+referer);
// return false;
// }
// return true;
}
}
package com.example.utils.file;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* Created by JA on 17/7/3.
*/
public class DefaultFileUpload {
/**
* 快速上传,等同于调用另外一个uplaod方法
*
* @param file MultipartFile 对象,不能为空
* @return FileUploadInfo
*/
public static FileUploadInfo directUpload(String home, MultipartFile file) {
return new DefaultFileUpload().upload(home,file);
}
public FileUploadInfo upload(String home,MultipartFile file) {
try {
InputStream inputStream = file.getInputStream();
String savePath = home;
String originFileName = file.getOriginalFilename();
String suffix = FileType.getSuffixByFilename(originFileName);
String url = savePath + "/" + getRandomString() + suffix;
File filePath = new File(url);
File parentFile = filePath.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs(); // create dirs
}
// filePath.createNewFile();
inputstreamtofile(inputStream,filePath);
// file.transferTo(filePath);
return new FileUploadInfo(true, originFileName, file.getSize(), url.replace(home, ""), suffix);
} catch (IOException e) {
e.printStackTrace();
// logger.error("file upload fail!", e);
FileUploadInfo fileUploadInfo = new FileUploadInfo(false, null, 0, null, null);
fileUploadInfo.setStateMsg(e.getMessage());
return fileUploadInfo;
}
}
public FileUploadInfo uploadBase64(String home,String base64) {
try {
BASE64Decoder decoder = new BASE64Decoder();
String savePath = home;
String suffix = base64.substring(base64.indexOf('/') + 1, base64.indexOf(';'));
String str1 = base64.split(",")[1];
base64 = str1;
String url = savePath + "/" + getRandomString()+"." + suffix;
// File filePath = new File(url);
// filePath.createNewFile();
//对字节数组字符串进行Base64解码并生成图片
if (base64 == null){
FileUploadInfo fileUploadInfo = new FileUploadInfo(false, null, 0, null, null);
fileUploadInfo.setStateMsg("");
return fileUploadInfo;
}
//Base64解码
byte[] bytes = decoder.decodeBuffer(base64);
OutputStream out = new FileOutputStream(url);
out.write(bytes);
out.flush();
out.close();
// file.transferTo(filePath);
return new FileUploadInfo(true, "", 0, url.replace(home, ""), suffix);
} catch (Exception e) {
e.printStackTrace();
// logger.error("file upload fail!", e);
FileUploadInfo fileUploadInfo = new FileUploadInfo(false, null, 0, null, null);
fileUploadInfo.setStateMsg(e.getMessage());
return fileUploadInfo;
}
}
public static void inputstreamtofile(InputStream ins,File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private String getDateTime(String format) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(new Date());
}
private String getRandomString() {
return UUID.randomUUID().toString().replace("-", "");
}
}
\ No newline at end of file
package com.example.utils.file;
import java.util.HashMap;
import java.util.Map;
/**
* Created by caobug on 15/5/22.
*/
public class FileType {
public static final String JPG = "JPG";
private static final Map<String, String> types = new HashMap<String, String>() {{
put(FileType.JPG, ".jpg");
}};
public static String getSuffix(String key) {
return FileType.types.get(key);
}
/**
* 根据给定的文件名,获取其后缀信息
*
* @param filename
* @return
*/
public static String getSuffixByFilename(String filename) {
return filename.substring(filename.lastIndexOf(".")).toLowerCase();
}
/**
* 根据给定的文件名,获取文件类型
*
* @param filename
* @return
*/
public static String getFileType(String filename) {
return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
}
}
package com.example.utils.file;
/**
* Created by JA on 17/7/3.
*/
/**
* 文件上传信息
* <p/>
* Created by caobug on 15/5/22.
*/
public class FileUploadInfo {
private boolean state; // 上传状态
private String stateMsg;// 状态消息
private String originalName; // 原始文件名
private long size; // 文件大小
private String url; // 文件保存路径
private String suffix; // 后缀
public FileUploadInfo(boolean state, String originalName, long size, String url, String suffix) {
this.state = state;
this.originalName = originalName;
this.size = size;
this.url = url;
this.suffix = suffix;
}
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
public String getOriginalName() {
return originalName;
}
public void setOriginalName(String originalName) {
this.originalName = originalName;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getStateMsg() {
return stateMsg;
}
public void setStateMsg(String stateMsg) {
this.stateMsg = stateMsg;
}
}
package com.example.utils.md5;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
/**
* Created by caobug on 14/11/20.
*/
public class MD5Utils {
public static String hash(String str) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(str.getBytes());
StringBuilder sb = new StringBuilder();
for (byte anArray : array) {
sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException ignored) {
}
return "";
}
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
public static String getMd5ByFile(File file) throws FileNotFoundException {
String value = null;
FileInputStream in = new FileInputStream(file);
try {
MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(byteBuffer);
BigInteger bi = new BigInteger(1, md5.digest());
value = bi.toString(16);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
\ No newline at end of file
package com.example.utils.mybatis;
import com.example.utils.mybatis.pageable.MybatisPageableInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
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;
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
@Autowired
DataSource dataSource;
@Value("${mybatis.mapperLocations}")
private String mybatismapperLocations;
@Autowired
MybatisPageableInterceptor mybatisPageableInterceptor;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
System.out.println("sqlSessionFactory=============");
System.out.println("sqlSessionFactory=============");
System.out.println("sqlSessionFactory=============");
System.out.println("sqlSessionFactory=============");
System.out.println("sqlSessionFactory=============");
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//添加分页插件
bean.setPlugins(new Interceptor[]{mybatisPageableInterceptor});
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
// SqlSessionFactory sqlSessionFactory = bean.getObject();
// org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
// //支持驼峰
// configuration.setMapUnderscoreToCamelCase(true);
bean.setMapperLocations(resolver.getResources(mybatismapperLocations));
SqlSessionFactory sqlSessionFactory = bean.getObject();
sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);// 开启驼峰映射
return sqlSessionFactory;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
\ No newline at end of file
package com.example.utils.mybatis.pageable;
public class Dialect {
public boolean supportsLimit() {
return false;
}
public boolean supportsLimitOffset() {
return supportsLimit();
}
/**
* 将sql变成分页sql语句,直接使用offset,limit的值作为占位符.</br> 源代码为:
* getLimitString(sql,offset
* ,String.valueOf(offset),limit,String.valueOf(limit))
*/
public String getLimitString(String sql, int offset, int limit) {
return getLimitString(sql, offset, Integer.toString(offset), limit,
Integer.toString(limit));
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符(placeholder)替换.
* <p/>
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset,
String offsetPlaceholder, int limit, String limitPlaceholder) {
throw new UnsupportedOperationException("paged queries not supported");
}
/**
* 将sql转换为总记录数SQL
*
* @param sql SQL语句
* @return 总记录数的sql
*/
public String getCountString(String sql) {
return "select count(1) from (" + sql + ") tmp_count";
}
/**
* 将sql转换为带排序的SQL
*
* @param sql
* SQL语句
* @return 总记录数的sql
*/
// public String getSortString(String sql, List<Order> orders) {
// if (orders == null || orders.isEmpty()) {
// return sql;
// }
//
// StringBuffer buffer = new StringBuffer("select * from (").append(sql)
// .append(") temp_order order by ");
// for (Order order : orders) {
// if (order != null) {
// buffer.append(order.toString()).append(", ");
// }
//
// }
// buffer.delete(buffer.length() - 2, buffer.length());
// return buffer.toString();
// }
}
package com.example.utils.mybatis.pageable;
public class MySQLDialect extends Dialect {
public boolean supportsLimitOffset() {
return true;
}
public boolean supportsLimit() {
return true;
}
public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
if (offset > 0) {
return sql + " limit " + offsetPlaceholder + "," + limitPlaceholder;
} else {
return sql + " limit " + limitPlaceholder;
}
}
}
\ No newline at end of file
package com.example.utils.mybatis.pageable;
public class OracleDialect extends Dialect {
public boolean supportsLimit() {
return true;
}
public boolean supportsLimitOffset() {
return true;
}
public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
sql = sql.trim();
boolean isForUpdate = false;
if (sql.toLowerCase().endsWith(" for update")) {
sql = sql.substring(0, sql.length() - 11);
isForUpdate = true;
}
StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);
if (offset > 0) {
pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
} else {
pagingSelect.append("select * from ( ");
}
pagingSelect.append(sql);
if (offset > 0) {
// int end = offset+limit;
String endString = offsetPlaceholder + "+" + limitPlaceholder;
pagingSelect.append(" ) row_ ) where rownum_ <= " + endString + " and rownum_ > " + offsetPlaceholder);
} else {
pagingSelect.append(" ) where rownum <= " + limitPlaceholder);
}
if (isForUpdate) {
pagingSelect.append(" for update");
}
return pagingSelect.toString();
}
}
package com.example.utils.mybatis.pageable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* 分页对象, 存放单页数据
*/
public class Page<T> {
private static final long serialVersionUID = 867755909294344406L;
private final List<T> content = new ArrayList<T>();
private final Pageable pageable;
private final long total;
public Page(List<T> content, Pageable pageable, long total) {
if (null == content) {
throw new IllegalArgumentException("Content must not be null!");
}
this.content.addAll(content);
this.total = total;
this.pageable = pageable;
}
public Page(List<T> content) {
this(content, null, null == content ? 0 : content.size());
}
/**
* 请求页面
*
* @return
*/
public int getNumber() {
return pageable == null ? 0 : pageable.getPageNumber();
}
/**
* page size
*
* @return
*/
public int getSize() {
return pageable == null ? 0 : pageable.getPageSize();
}
/**
* 总页数
*
* @return
*/
public int getTotalPages() {
return getSize() == 0 ? 1 : (int) Math.ceil((double) total / (double) getSize());
}
/**
* 当前页记录条数
*
* @return
*/
public int getNumberOfElements() {
return content.size();
}
/**
* 总记录条数
*
* @return
*/
public long getTotalElements() {
return total;
}
/**
* 是否有上一页
*
* @return
*/
public boolean hasPreviousPage() {
return getNumber() > 0;
}
/**
* 是否首页
*
* @return
*/
public boolean isFirstPage() {
return !hasPreviousPage();
}
/**
* 是否有下一页
*
* @return
*/
public boolean hasNextPage() {
return getNumber() + 1 < getTotalPages();
}
/**
* 是否末页
*
* @return
*/
public boolean isLastPage() {
return !hasNextPage();
}
/**
* 下一页请求对象
*
* @return
*/
public Pageable nextPageable() {
return hasNextPage() ? pageable.next() : null;
}
/**
* 上一页请求对象
*
* @return
*/
public Pageable previousPageable() {
if (hasPreviousPage()) {
return pageable.previousOrFirst();
}
return null;
}
/**
* 迭代器
*
* @return
*/
public Iterator<T> iterator() {
return content.iterator();
}
/**
* 当前页元素列表
*
* @return
*/
public List<T> getContent() {
return Collections.unmodifiableList(content);
}
/**
* 当前页是否有元素
*
* @return
*/
public boolean hasContent() {
return !content.isEmpty();
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
String contentType = "UNKNOWN";
if (content.size() > 0) {
contentType = content.get(0).getClass().getName();
}
return String.format("Page %s of %d containing %s instances", getNumber(), getTotalPages(), contentType);
}
}
package com.example.utils.mybatis.pageable;
/**
* 分页请求对象
*/
public class Pageable {
private static final long serialVersionUID = 7280485938848398236L;
private final int page;
private final int size;
/**
* 是否查询总记录数
*/
private final boolean countable;
/**
* @param page the page no you want to request, start from 0
* @param size page size
*/
public Pageable(int page, int size) {
this(page, size, true);
}
/**
* @param page the page no you want to request, start from 0
* @param size page size
* @param countable whether count total numbers
*/
public Pageable(int page, int size, boolean countable) {
if (page < 0) {
throw new IllegalArgumentException("Page index must not be less than zero!");
}
if (size < 0) {
throw new IllegalArgumentException("Page size must not be less than zero!");
}
this.page = page;
this.size = size;
this.countable = countable;
}
public boolean getCountable() {
return countable;
}
public int getPageSize() {
return size;
}
public int getPageNumber() {
return page;
}
public int getOffset() {
return page * size - size;
}
public boolean hasPrevious() {
return page > 0;
}
public Pageable next() {
return new Pageable(page + 1, size);
}
public Pageable previousOrFirst() {
return hasPrevious() ? new Pageable(page - 1, size) : this;
}
public Pageable first() {
return new Pageable(0, size);
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("Page request [number: %d, size %d, sort: %s]", page, size);
}
}
#data source
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)
#mybatis
mybatis.mapperLocations=classpath*:mappers/*.xml
mybatis.configLocation=classpath:/mybatis-config.xml
#port
server.port=9092
\ No newline at end of file
<!-- Logback configuration. See http://logback.qos.ch/manual/index.html -->
<configuration scan="true" scanPeriod="10 seconds">
<!-- Simple file output -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- encoder defaults to ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
<encoder>
<pattern>
[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily 配置日志所生成的目录以及生成文件名的规则 -->
<fileNamePattern>logs/catalina-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- or whenever the file size reaches 64 MB -->
<maxFileSize>64 MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<!-- Safely log to the same file from multiple JVMs. Degrades performance! -->
<prudent>true</prudent>
</appender>
<!-- Console output -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoder defaults to ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
<encoder>
<pattern>
[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n
</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- Only log level WARN and above -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
</appender>
<!-- Enable FILE and STDOUT appenders for all log messages.
By default, only log at level INFO and above. -->
<root level="INFO">
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
</root>
<!-- For loggers in the these namespaces, log at all levels. -->
<logger name="pedestal" level="ALL" />
<logger name="hammock-cafe" level="ALL" />
<logger name="user" level="ALL" />
</configuration>
\ No newline at end of file
<?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.example.mapper.ConfigInfoMapper">
<select id="get" resultType="com.example.models.ConfigInfo">
select * from t_kmr_config_info limit 1;
</select>
</mapper>
\ No newline at end of file
<?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.example.mapper.ImgInfoMapper">
<select id="getNewByOpenid" resultType="com.example.models.ImgInfo">
select * from t_kmr_img_info where openid = #{openid} and status = 1 order by id desc limit 1;
</select>
<insert id="create">
insert into `t_kmr_img_info` (
`openid`,
`nickname`,
`headimgurl`,
`img_url`,
blessing_words,
sharing_describe,
gtmc_uid,
gtmc_name,
gtmc_department,
`create_at`,
`update_at`,
`status`
)
values(
#{openid},
#{nickname},
#{headimgurl},
#{imgUrl},
#{blessingWords},
#{sharingDescribe},
#{gtmcUid},
#{gtmcName},
#{gtmcDepartment},
#{createAt},
#{updateAt},
#{status}
);
</insert>
</mapper>
\ No newline at end of file
<?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.example.mapper.ScoreLogInfoMapper">
<insert id="create">
insert into `t_kmr_score_log_info` (
`openid`,
`nickname`,
`headimgurl`,
gtmc_uid,
gtmc_name,
gtmc_department,
`score`,
`create_at`,
`status`
)
values(
#{openid},
#{nickname},
#{headimgurl},
#{gtmcUid},
#{gtmcName},
#{gtmcDepartment},
#{score},
#{createAt},
#{status}
);
</insert>
<select id="getRankingList" resultType="map">
select(@i:= @i+ 1) r,
a.*
from(
select openid, min(score) score, nickname, headimgurl
from t_kmr_score_log_info
where status= 1
GROUP BY openid) a,
(
select @i:= 0) t2
order by a.score
limit #{limit};
</select>
<select id="getMyRanking" resultType="map">
select b.*
from(
select(@i:= @i+ 1) r, a.*
from(
select openid, min(score) score, nickname, headimgurl
from t_kmr_score_log_info
where status= 1
GROUP BY openid) a,(
select @i:= 0) t2
order by a.score) b
where b.openid= #{openid}
</select>
<select id="countByDay" resultType="long">
select count(*) c
from `t_kmr_score_log_info`
where create_at BETWEEN #{startDate} and #{endDate}
and openid= #{openid};
</select>
<select id="countSum" resultType="long">
select count(*) c
from `t_kmr_score_log_info`
where openid= #{openid};
</select>
</mapper>
\ No newline at end of file
<?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>
<!--该配置影响的所有映射器中配置的二级缓存的全局开关。-->
<setting name="cacheEnabled" value="false"/>
<!--延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--是否允许单一语句返回多结果集(需要兼容驱动)。-->
<setting name="multipleResultSetsEnabled" value="true"/>
<!--使用列标签代替列名。不同的驱动在这方面会有不同的表现,具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。-->
<setting name="useColumnLabel" value="true"/>
<!--允许 JDBC 支持自动生成主键,需要驱动兼容。如果设置为 true 则这个设置强制使用自动生成主键,尽管一些驱动不能兼容但仍可正常工作(比如 Derby)。-->
<setting name="useGeneratedKeys" value="false"/>
<!--指定 MyBatis 是否以及如何自动映射指定的列到字段或属性。NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。FULL 会自动映射任意复杂的结果集(包括嵌套和其他情况)。-->
<setting name="autoMappingBehavior" value="PARTIAL"/>
<!--配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements);BATCH 执行器将重用语句并执行批量更新。-->
<setting name="defaultExecutorType" value="SIMPLE"/>
<!--设置超时时间,它决定驱动等待数据库响应的秒数。-->
<setting name="defaultStatementTimeout" value="25"/>
<!--允许在嵌套语句中使用行分界(RowBounds)。-->
<setting name="safeRowBoundsEnabled" value="false"/>
<!--是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。-->
<setting name="localCacheScope" value="SESSION"/>
<!--当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。-->
<setting name="jdbcTypeForNull" value="OTHER"/>
<!--指定哪个对象的方法触发一次延迟加载。-->
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
<plugins>
<!-- 分页 -->
<plugin interceptor="com.example.utils.pageable.MybatisPageableInterceptor">
<property name="dialectClass" value="com.example.utils.pageable.MySQLDialect"/>
</plugin>
<!-- / 分页 -->
</plugins>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<urlrewrite>
<rule>
<note>默认加载 /index.html</note>
<from>^/([a-zA-Z0-9]+)/$</from>
<to>/Users/joe/Documents/self/src/jia51/case_new_by_luo/$1/html/$1.html</to>
</rule>
</urlrewrite>
\ No newline at end of file
package com.example;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@WebAppConfiguration
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}