Commit 122cd1e7 authored by aiden's avatar aiden

Default Changelist

parents
Pipeline #340 failed with stages
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.pvuv</groupId>
<artifactId>pvuv</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>pvuv</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<selenium.version>2.42.2</selenium.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>com.movitech.apollo</groupId>
<artifactId>apollo-framework</artifactId>
<version>0.6-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.pvuv.pvuv;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PvuvApplication {
public static void main(String[] args) {
SpringApplication.run(PvuvApplication.class, args);
}
}
package com.pvuv.pvuv;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.pvuv.pvuv.model.MiniprogramUv;
import com.pvuv.pvuv.util.DateUtil;
import com.pvuv.pvuv.util.SystemConstant;
import com.pvuv.pvuv.util.WechatUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class Uvpv {
private static String webDriver = "webdriver.chrome.driver";
private static String webDriverPath ="D:\\google\\chromedriver.exe";
private static String taobaourl = "https://sycm.taobao.com/portal/home.htm";
private static String jdurl = "https://sz.jd.com/sz/view/indexs.html";
private static String redurl = "https://ark.xiaohongshu.com/";
private static String umengurl = "https://passport.umeng.com/login";
private static WebDriver driver = null;
public static List<String> getUP(int shopid) {
String userName = "";
String passWord = "";
switch (shopid) {
case 1:
userName = "charleskeith箱包旗舰店";
passWord = "ckshsuperbag@2019";
break;
case 2:
userName = "charleskeith旗舰店";
passWord = "ckshshoesbags8@2020";
break;
case 3:
userName = "social.china@charleskeith.com";
passWord = "Charleskeith@2019";
break;
case 4:
userName = " jd_clk";
passWord = "ckshjd@1996";
break;
case 13:
userName = "ck_red@163.com";
passWord = "ckshred@1808";
break;
case 15:
userName = "social.china@charleskeith.com";
passWord = "Charleskeith@2019";
break;
case 16:
userName = "pedro旗舰店";
passWord = "pedro@2019";
break;
case 18:
userName = "pedro_red@163.com";
passWord = "pedrored@2020";
break;
case 19:
userName = "pedro旗舰店";
passWord = "newjd@2020";
break;
case 20:
userName = "616509";
passWord = "CKsh@0810";
break;
case 21:
userName = "616509";
passWord = "CKsh@0810";
break;
}
List<String> list = new ArrayList<>();
list.add(userName);
list.add(passWord);
return list;
}
private static String filePath = "D:\\pvuv.txt";
public static void writeFile(String content) {
try {
FileUtils.writeByteArrayToFile(new File(filePath), content.getBytes(), true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File file = new File(filePath);
if (file.exists()) {
FileUtils.deleteQuietly(file);
}
// int[] intArray = new int[]{3,15};
// int[] intArray = new int[]{13,18};
// int[] intArray = new int[]{4,19};
// int[] intArray = new int[]{13,18,3,15};
int[] intArray = new int[]{13,18,4,19,3,15};
// int[] intArray = new int[]{1,2,3,4,13,15,16,18,19};
for (int shopid : intArray) {
start(shopid);
}
if (driver != null) {
driver.quit();
}
}
/**
* 方法描述: 启动
*
* @throws
* @author tarzan Liu
* @date 2020年08月07日 12:42:02
* @param shopid
*/
public static void start(int shopid) {
try {
if (Objects.isNull(driver) && shopid != 3 && shopid != 15) {
System.setProperty(webDriver, webDriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("Accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
options.addArguments("Accept-Encoding=gzip, deflate, sdch");
options.addArguments("Accept-Language=zh-CN,zh;q=0.8");
options.addArguments("Connection=keep-alive");
options.addArguments("Host=activityunion-marketing.meituan.com");
options.addArguments("Upgrade-Insecure-Requests=1");
options.addArguments("User-Agent=Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4");
// options.setExperimentalOption("debuggerAddress", "127.0.0.1:9222");
List<String> excludeSwitches = Lists.newArrayList("enable-automation");
options.setExperimentalOption("excludeSwitches", excludeSwitches);
driver = new ChromeDriver(options);
String title = "shopid,uv,pv,miniUV,miniPV\r\n";
System.out.println(title);
writeFile(title);
}
Map<String,String> map = new HashMap<>();
if (shopid == 1 || shopid == 2 || shopid == 16) {
getTaoBaoPv(driver, map, shopid);
// if (shopid == 3 || shopid == 15)
// getEsitePv(driver, map, shopid);
}
if (shopid == 4 || shopid == 19 ) {
getJDPv(driver, map, shopid);
}
if (shopid == 13 || shopid == 18 ) {
getREDPv(driver, map, shopid);
}
if (shopid == 3 || shopid == 15) {
FirefoxProfile profile = new ProfilesIni().getProfile("default");
WebDriver driverEsite = new FirefoxDriver(profile);
getEsitePv(driverEsite, map, shopid);
}
String uv = map.get("uv") == null ? "" : map.get("uv");
String pv = map.get("pv") == null ? "" : map.get("pv");
String miniUV = map.get("miniUV") == null ? "" : map.get("miniUV");
String miniPV = map.get("miniPV") == null ? "" : map.get("miniPV");
String content = shopid + "," + uv + "," + pv + "," + miniUV + "," + miniPV + "\r\n";
System.out.println(content);
writeFile(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (Objects.nonNull(driver)) {
// driver.close();
}
}
}
/**
* 获取 小红书 pv uv
*/
private static void getREDPv(WebDriver webDriver, Map<String, String> map, int shopid) throws Exception{
userLogin(driver, shopid);
// if(driver.findElements(By.xpath("/html/body/div[6]/div/div/div/div[2]/div/div[2]/div/div[2]/button[1]/span")).size() > 0){
// WebElement bulletFrame = driver.findElement(By.xpath("/html/body/div[6]/div/div/div/div[2]/div/div[2]/div/div[2]/button[1]/span"));
// bulletFrame.click();
// } else {
// System.out.println("");
// }
Thread.sleep(3000);
WebElement dateWebElement = driver.findElement(By.xpath("//a[contains(@href,'/ark/sale-data/item')]"));
dateWebElement.click();
Thread.sleep(3000);
try {
WebElement flowWebElement = driver.findElement(By.xpath("//a[contains(@href,'/ark/sale-data/item/traffic-data')]"));
flowWebElement.click();
}catch (Exception e){
}
Thread.sleep(1000);
webDriver.manage().timeouts().implicitlyWait(1000, TimeUnit.SECONDS);
String pv_value = webDriver.findElement(By.xpath("//*[@id=\"app\"]/div/div[1]/div/div/div/div/div/div/div/div[3]/div[2]/div/div/span")).getText();
String uv_value = webDriver.findElement(By.xpath("//*[@id=\"app\"]/div/div[1]/div/div/div/div/div/div/div/div[3]/div[1]/div/div/span")).getText();
map.put("uv",uv_value.replace(",", ""));
map.put("pv",pv_value.replace(",", ""));
WebElement arrowWebElement = driver.findElement(By.className("user-info"));
arrowWebElement.click();
WebElement btnWebElement = driver.findElement(By.xpath("//*[text()='退出']"));
btnWebElement.click();
Thread.sleep(3000);
}
/**
* 获取 京东 pv uv
*/
private static void getJDPv(WebDriver webDriver, Map<String, String> map, int shopid) throws Exception{
userLogin(driver, shopid);
Thread.sleep(10000);
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String pv_value = webDriver.findElement(By.xpath("//*[@id=\"coreIndex\"]/div[2]/div[1]/ul/li[2]/div[2]/div")).getText();
String uv_value = webDriver.findElement(By.xpath("//*[@id=\"coreIndex\"]/div[2]/div[1]/ul/li[1]/div[2]/div")).getText();
map.put("uv",uv_value.replace(",", ""));
map.put("pv",pv_value.replace(",", ""));
// WebElement arrowWebElement = driver.findElement(By.className("user awe-angel-down"));
WebElement arrowWebElement = driver.findElement(By.xpath("//span[contains(@class,'user awe-angel-down')]"));
arrowWebElement.click();
WebElement btnWebElement = driver.findElement(By.xpath("//a[contains(@href,'logout')]"));
btnWebElement.click();
Thread.sleep(3000);
}
/**
* 获取淘宝pv uv
*
* */
private static void getTaoBaoPv(WebDriver webDriver, Map<String, String> map, int shopid) throws Exception {
userLogin(driver, shopid);
Thread.sleep(15000);
driver.get("https://sycm.taobao.com/portal/home.htm");
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(3000);
String pv_value = webDriver.findElement(By.xpath("//*[@id=\"live-survey-false\"]/div[2]/div/div[2]/div/div[1]/div[2]/p[3]/span[2]")).getText();
String uv_value = webDriver.findElement(By.xpath("//*[@id=\"live-survey-false\"]/div[2]/div/div[2]/div/div[3]/div[2]/p[2]/span[2]")).getText();
map.put("uv",uv_value.replace(",", ""));
map.put("pv",pv_value.replace(",", ""));
WebElement btnWebElement = driver.findElement(By.xpath("//*[@id=\"app\"]/div/div[1]/div[1]/section[1]/div/div[3]/a"));
btnWebElement.click();
Thread.sleep(3000);
}
// static String strHead = "<html><head></head><body><pre style=\"word-wrap: break-word; white-space: pre-wrap;\">";
static String strHead = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><link title=\"将较长的行自动换行\" href=\"resource://gre-resources/plaintext.css\" type=\"text/css\" rel=\"alternate stylesheet\" /></head><body><pre>";
static String strLast = "</pre></body></html>";
/**
* 获取官网pv uv
*
* */
private static void getEsitePv(WebDriver webDriver, Map<String, String> map, int shopid) throws Exception {
userLogin(webDriver, shopid);
if (shopid == 3) {
Thread.sleep(1000);
webDriver.get("https://web.umeng.com/main.php?c=site&a=frame&siteid=1258653523");
Thread.sleep(5000L);
webDriver.get("https://web.umeng.com/main.php?c=site&a=overview&ajax=module%3Dsummary&siteid=1258653523&_=1584329985806");
String json = webDriver.getPageSource();
String jsonStr = json.substring(strHead.length(), json.length() - strLast.length());
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
if (null != jsonObject) {
Object o = jsonObject.get("data");
if (null != o) {
JSONObject res = (JSONObject) o;
Object summary = res.get("summary");
if (null != summary) {
JSONObject summaryJSON = (JSONObject) summary;
if (null != summaryJSON) {
JSONArray jsonArray = summaryJSON.getJSONArray("items");
if (null != jsonArray) {
JSONObject result = (JSONObject) jsonArray.get(1);
String pv_value = result.getString("pv");
String uv_value = result.getString("uv");
map.put("uv",uv_value);
map.put("pv",pv_value);
}
}
}
}
}
webDriver.get("http://api.umeng.com/yesterday_data?appkey=5537103667e58eb776001821&auth_token=n8FodCvgRIqBdX1JEztt");
String jsonIos = webDriver.getPageSource();
String jsonStrIos = jsonIos.substring(strHead.length(), jsonIos.length() - strLast.length());
JSONObject jsonObjectIos = JSONObject.fromObject(jsonStrIos);
if (null != jsonObjectIos) {
String uvIos = jsonObjectIos.getString("active_users");
String puIos = jsonObjectIos.getString("launches");
if (null != uvIos) {
if (map.get("uv") != null && map.get("pv") != null) {
map.put("uv", String.valueOf(Integer.parseInt(map.get("uv")) + Integer.parseInt(uvIos)));
map.put("pv", String.valueOf(Integer.parseInt(map.get("pv")) + Integer.parseInt(puIos)));
}
webDriver.get("http://api.umeng.com/yesterday_data?appkey=552ca86efd98c5f44100000c&auth_token=n8FodCvgRIqBdX1JEztt");
String jsonAd = webDriver.getPageSource();
String jsonStrAd = jsonAd.substring(strHead.length(), jsonAd.length() - strLast.length());
JSONObject jsonObjectAd = JSONObject.fromObject(jsonStrAd);
if (null != jsonObjectAd) {
String uvAd = jsonObjectAd.getString("active_users");
String puAd = jsonObjectAd.getString("launches");
if (null != uvAd) {
if (map.get("uv") != null && map.get("pv") != null) {
map.put("uv", String.valueOf(Integer.parseInt(map.get("uv")) + Integer.parseInt(uvAd)));
map.put("pv", String.valueOf(Integer.parseInt(map.get("pv")) + Integer.parseInt(puAd)));
}
}
}
}
}
String ckWechatDate = WechatUtils.getWeChatData(WechatUtils.getAccessToken(), DateUtil.format(DateUtil.getYesterday(), SystemConstant.FORMAT_DATE_YYMMDD),DateUtil.format(DateUtil.getYesterday(),SystemConstant.FORMAT_DATE_YYMMDD));
parseJson(ckWechatDate, map);
} else if (shopid == 15) {
webDriver.get("https://web.umeng.com/main.php?c=site&a=frame&siteid=1263531609");
Thread.sleep(5000L);
webDriver.get("https://web.umeng.com/main.php?c=site&a=overview&ajax=module%3Dsummary&siteid=1263531609&_=1470274565304");
String json = webDriver.getPageSource();
String jsonStr = json.substring(strHead.length(), json.length() - strLast.length());
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
if (null != jsonObject) {
Object o = jsonObject.get("data");
if (null != o) {
JSONObject res = (JSONObject) o;
Object summary = res.get("summary");
if (null != summary) {
JSONObject summaryJSON = (JSONObject) summary;
JSONArray jsonArray = summaryJSON.getJSONArray("items");
if (null != jsonArray) {
JSONObject result = (JSONObject) jsonArray.get(1);
String pv_value = result.getString("pv");
String uv_value = result.getString("uv");
webDriver.get("http://api.umeng.com/yesterday_data?appkey=592f6da245297d3eed001496&auth_token=n8FodCvgRIqBdX1JEztt");
String jsonApp = webDriver.getPageSource();
String jsonAppStr = jsonApp.substring(strHead.length(), jsonApp.length() - strLast.length());
JSONObject jsonObjectApp = JSONObject.fromObject(jsonAppStr);
if (null != jsonObjectApp) {
String uvIos = jsonObjectApp.getString("active_users");
String launchesIos = jsonObjectApp.getString("launches");
webDriver.get("http://api.umeng.com/yesterday_data?appkey=592f6e5a3eae255a0b000355&auth_token=n8FodCvgRIqBdX1JEztt");
String jsonAD = webDriver.getPageSource();
String jsonStrAD = jsonAD.substring(strHead.length(), jsonAD.length() - strLast.length());
JSONObject jsonObjectAD = JSONObject.fromObject(jsonStrAD);
if (null != jsonObjectAD) {
String UvAD = jsonObjectAD.getString("active_users");
String launchesAD = jsonObjectAD.getString("launches");
map.put("uv", String.valueOf(Integer.valueOf(uv_value) + Integer.valueOf(uvIos) + Integer.valueOf(UvAD)));
map.put("pv", String.valueOf(Integer.valueOf(pv_value) + Integer.valueOf(launchesIos) + Integer.valueOf(launchesAD)));
}
}
}
}
}
}
String pedroWechatDate = WechatUtils.getPedroWeChatData(WechatUtils.getPedroAccessToken(), DateUtil.format(DateUtil.getYesterday(), SystemConstant.FORMAT_DATE_YYMMDD),DateUtil.format(DateUtil.getYesterday(),SystemConstant.FORMAT_DATE_YYMMDD));
parseJson(pedroWechatDate, map);
}
if (map.get("uv") != null && map.get("pv") != null && map.get("miniUV") != null && map.get("miniPV") != null) {
map.put("uv", String.valueOf(Integer.parseInt(map.get("uv")) + Integer.parseInt(map.get("miniUV"))));
map.put("pv", String.valueOf(Integer.parseInt(map.get("pv")) + Integer.parseInt(map.get("miniPV"))));
}
webDriver.quit();
}
static void parseJson(String wechatDate, Map<String,String> map) {
try{
MiniprogramUv mini = new Gson().fromJson(wechatDate, MiniprogramUv.class);
map.put("miniUV", String.valueOf(mini.getList().get(0).getVisit_uv()));
map.put("miniPV", String.valueOf(mini.getList().get(0).getVisit_pv()));
} catch (Exception e){
map.put("miniUV", String.valueOf(0));
map.put("miniPV", String.valueOf(0));
}
}
/**
* 登录模块
*/
private static void userLogin(WebDriver driver, int shopid) throws Exception {
List<String> userPass = getUP(shopid);
if (shopid == 1 || shopid == 2 || shopid == 16) {
driver.get(taobaourl);
Thread.sleep(200);//等待0.2秒
driver.switchTo().frame(0);
WebElement usernameWebElement = driver.findElement(By.xpath("//*[@id=\"fm-login-id\"]"));
usernameWebElement.sendKeys(userPass.get(0));
WebElement passwordWebElement = driver.findElement(By.xpath("//*[@id=\"fm-login-password\"]"));
passwordWebElement.sendKeys(userPass.get(1));
//模拟滑动
Thread.sleep(5000);
WebElement btnWebElement = driver.findElement(By.xpath("//button[@class='fm-button fm-submit password-login']"));
btnWebElement.click();
// WebElement draggable = driver.findElement(By.id("nc_1_n1z"));//定位元素
// Actions bu = new Actions(driver); // 声明action对象
// bu.clickAndHold(draggable).build().perform(); // clickAndHold鼠标左键按下draggable元素不放
// bu.moveByOffset(380, 2).perform(); // 平行移动鼠标
// Thread.sleep(200);
// bu.moveByOffset(400, 2).perform(); // 平行移动鼠标
// Thread.sleep(200);
// bu.moveByOffset(420, 2).perform(); // 平行移动鼠标
// Thread.sleep(3000);
// if (shopid == 1) {
// WebElement btnWebElement1 = driver.findElement(By.xpath("/html/body/div[6]/div/div/div/div/span[4]/span"));
// btnWebElement1.click();
// } else if (shopid == 16) {
// WebElement btnWebElement16 = driver.findElement(By.xpath("/html/body/div[6]/div/div/div/div/span[3]/span"));
// btnWebElement16.click();
// }
Thread.sleep(3000);
}else if (shopid == 4 || shopid == 19){
driver.get(jdurl);
Thread.sleep(200);//等待0.2秒
WebElement loginWebElement = driver.findElement(By.xpath("//*[@id=\"main\"]/div[1]/div[1]/div/div/div[2]/a[5]"));
loginWebElement.click();
Thread.sleep(5000);//等待5秒
driver.switchTo().frame(0);
WebElement userLoginWebElement = driver.findElement(By.xpath("/html/body/div[2]/div[2]/a"));
userLoginWebElement.click();
Thread.sleep(5000);//等待5秒
WebElement usernameWebElement = driver.findElement(By.xpath("//*[@id=\"loginname\"]"));
usernameWebElement.clear();
usernameWebElement.sendKeys(userPass.get(0));
WebElement passwordWebElement = driver.findElement(By.xpath("//*[@id=\"nloginpwd\"]"));
passwordWebElement.clear();
passwordWebElement.sendKeys(userPass.get(1));
WebElement btnWebElement = driver.findElement(By.xpath("//*[@id=\"loginsubmit\"]"));
btnWebElement.click();
Thread.sleep(5000);
//模拟滑动
// Thread.sleep(1000);
// WebElement draggable = driver.findElement(By.xpath("//*[@id=\"JDJRV-wrap-loginsubmit\"]/div/div/div/div[2]/div[3]"));//定位元素
// Actions bu = new Actions(driver); // 声明action对象
// bu.clickAndHold(draggable).build().perform(); // clickAndHold鼠标左键按下draggable元素不放
// bu.moveByOffset(380, 2).perform(); // 平行移动鼠标
// Thread.sleep(200);
// bu.moveByOffset(400, 2).perform(); // 平行移动鼠标
// Thread.sleep(200);
// bu.moveByOffset(420, 2).perform(); // 平行移动鼠标
Thread.sleep(3000);
}else if (shopid == 13 || shopid == 18){
driver.get(redurl);
Thread.sleep(1000);//等待0.2秒
WebElement usernameWebElement = driver.findElement(By.xpath("//input[contains(@placeholder,'邮箱')]"));
usernameWebElement.sendKeys(userPass.get(0));
WebElement passwordWebElement = driver.findElement(By.xpath("//input[contains(@placeholder,'密码')]"));
passwordWebElement.sendKeys(userPass.get(1));
WebElement btnWebElement = driver.findElement(By.xpath("//button[contains(@owl,'login-submit')]"));
btnWebElement.click();
Thread.sleep(5000);
}else if (shopid == 3 || shopid == 15){
Thread.sleep(1000);
driver.get(umengurl);
}
}
}
package com.pvuv.pvuv.model;
import java.math.BigDecimal;
import java.util.List;
/**
* Created by allen on 2018/4/3.
*/
public class MiniprogramUv {
private List<PUv> list;
public List<PUv> getList() {
return list;
}
public void setList(List<PUv> list) {
this.list = list;
}
public class PUv{
/**
* 日期
*/
private String ref_date;
/**
* session次数
*/
private Integer session_cnt;
/**
* pv数据
*/
private Integer visit_pv;
/**
* uv数据
*/
private Integer visit_uv;
/**
* 新uv数据
*/
private Integer visit_uv_new;
/**
* 次均停留时长
*/
private BigDecimal stay_time_uv;
/**
* stay_time_session
*/
private BigDecimal stay_time_session;
/**
* 访问深度
*/
private BigDecimal visit_depth;
/**
*
* @return
*/
public String getRef_date() {
return ref_date;
}
public void setRef_date(String ref_date) {
this.ref_date = ref_date;
}
public Integer getSession_cnt() {
return session_cnt;
}
public void setSession_cnt(Integer session_cnt) {
this.session_cnt = session_cnt;
}
public Integer getVisit_pv() {
return visit_pv;
}
public void setVisit_pv(Integer visit_pv) {
this.visit_pv = visit_pv;
}
public Integer getVisit_uv() {
return visit_uv;
}
public void setVisit_uv(Integer visit_uv) {
this.visit_uv = visit_uv;
}
public Integer getVisit_uv_new() {
return visit_uv_new;
}
public void setVisit_uv_new(Integer visit_uv_new) {
this.visit_uv_new = visit_uv_new;
}
public BigDecimal getStay_time_uv() {
return stay_time_uv;
}
public void setStay_time_uv(BigDecimal stay_time_uv) {
this.stay_time_uv = stay_time_uv;
}
public BigDecimal getStay_time_session() {
return stay_time_session;
}
public void setStay_time_session(BigDecimal stay_time_session) {
this.stay_time_session = stay_time_session;
}
public BigDecimal getVisit_depth() {
return visit_depth;
}
public void setVisit_depth(BigDecimal visit_depth) {
this.visit_depth = visit_depth;
}
}
}
package com.pvuv.pvuv.util;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* 日期工具类
*/
public class DateUtil {
public static Date getBillDate(String time) throws Exception{
time = time + " 00:00:00";
DateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sf.parse(time);
}
//根据时间获取当月月初和月末时间
public static Map<String,String> getMonthTime(Date dealDate){
Map<String,String> map = new HashMap<String,String>();
SimpleDateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat toFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
Calendar calendar = Calendar.getInstance();
calendar.setTime(dealDate);
calendar.add(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
String fromDate = fromFormat.format(calendar.getTime());
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 0);
String toDate = toFormat.format(calendar.getTime());
map.put("fromDate",fromDate);
map.put("toDate",toDate);
return map;
}
//根据时间获取上月月初和月末时间
public static Map<String,String> getLastMonthTime(Date dealDate){
Map<String,String> map = new HashMap<String,String>();
SimpleDateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat toFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
Calendar calendar = Calendar.getInstance();
calendar.setTime(dealDate);
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
String fromDate = fromFormat.format(calendar.getTime());
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 0);
String toDate = toFormat.format(calendar.getTime());
map.put("fromDate",fromDate);
map.put("toDate",toDate);
return map;
}
/**
* 将Date类型转换为字符串
*
* @param date 日期类型
* @return 日期字符串
*/
public static String format(Date date) {
return format(date, SystemConstant.FORMAT_DATE_YMDHMS);
}
/**
* 将Date类型转换为字符串
*
* @param date 日期类型
* @param pattern 字符串格式
* @return 日期字符串
*/
public static String format(Date date, String pattern) {
if (date == null) {
return "null";
}
if (pattern == null || pattern.equals("") || pattern.equals("null")) {
pattern = SystemConstant.FORMAT_DATE_YMDHMS;
}
return new SimpleDateFormat(pattern).format(date);
}
/**
* 将Date类型转换为字符串
*
* @param date 日期类型
* @param pattern 字符串格式
* @return 日期字符串
*/
public static String formatNull(Date date, String pattern) {
if (date == null) {
return null;
}
if (pattern == null || pattern.equals("") || pattern.equals("null")) {
pattern = SystemConstant.FORMAT_DATE_YMDHMS;
}
return new SimpleDateFormat(pattern).format(date);
}
/**
* 将字符串转换为Date类型
*
* @param date 字符串类型
* @return 日期类型
*/
public static Date format(String date) {
return format(date, null);
}
/**
* 将字符串转换为Date类型
*
* @param date 字符串类型
* @param pattern 格式
* @return 日期类型
*/
public static Date format(String date, String pattern) {
if (pattern == null || pattern.equals("") || pattern.equals("null")) {
pattern = SystemConstant.FORMAT_DATE_YMDHMS;
}
if (date == null || date.equals("") || date.equals("null")) {
return new Date();
}
Date d = null;
try {
d = new SimpleDateFormat(pattern).parse(date);
} catch (ParseException pe) {
}
return d;
}
/**
* 得到年月日时分秒字符串
*
* @return 字符串
*/
public static String getDateYmdHms() {
Date date = new Date();
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMddHHmmss");
String now = formatter1.format(date);
return now;
}
public static Date getLastMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, -1);
date = c.getTime();
return date;
}
public static Date getNextDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, 1);
date = c.getTime();
return date;
}
public static Date getNextHour(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.HOUR_OF_DAY, 1);
date = c.getTime();
return date;
}
public static Date getNextTenMin(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MINUTE, 10);
date = c.getTime();
return date;
}
public static Date getNextIMinute(Date date,int i) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MINUTE, i);
date = c.getTime();
return date;
}
public static int getPreviousMonth() {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, -1);
return c.get(Calendar.MONTH);
}
public static int getCurrentMonth() {
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 0);
return c.get(Calendar.MONTH);
}
public static Date getPreviousWeek(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, -7);
date = c.getTime();
return date;
}
//获得当前月的最后一天
public static Date getLastDayOfMonth() {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1号
lastDate.add(Calendar.MONTH, 1);//加一个月,变为下月的1号
lastDate.add(Calendar.DATE, -1);//减去一天,变为当月最后一天
return strToDate(sdf.format(lastDate.getTime()), dateFormat);
}
//获得当前月的最后一天
public static String getLastDayOfMonthStr() {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1号
lastDate.add(Calendar.MONTH, 1);//加一个月,变为下月的1号
lastDate.add(Calendar.DATE, -1);//减去一天,变为当月最后一天
return sdf.format(lastDate.getTime());
}
//获得上月的第一天
public static String getFirstDayOfPreviousMonth() {
String dateFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1号
lastDate.add(Calendar.MONTH,-1);//变为上月的1号
lastDate.set(Calendar.HOUR_OF_DAY, 0);
lastDate.set(Calendar.MINUTE, 0);
lastDate.set(Calendar.SECOND, 0);
lastDate.set(Calendar.MILLISECOND, 0);
// lastDate.add(Calendar.DATE, -1);//减去一天,变为当月最后一天
return sdf.format(lastDate.getTime());
}
//获得当上月的最后一天
public static String getLastDayOfBeforeMonth() {
String dateFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1号
lastDate.add(Calendar.MONTH, 0);//变为当月的1号
lastDate.add(Calendar.DATE, -1);//减去一天,变为当月最后一天
lastDate.set(Calendar.HOUR_OF_DAY, 23);
lastDate.set(Calendar.MINUTE, 59);
lastDate.set(Calendar.SECOND, 59);
lastDate.set(Calendar.MILLISECOND, 999);
return sdf.format(lastDate.getTime());
}
//获得上月的第一天
public static String getFirstDayOfBeforePreviousMonth() {
String dateFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1号
lastDate.add(Calendar.MONTH,-2);//变为上上月的1号
lastDate.set(Calendar.HOUR_OF_DAY, 0);
lastDate.set(Calendar.MINUTE, 0);
lastDate.set(Calendar.SECOND, 0);
lastDate.set(Calendar.MILLISECOND, 0);
// lastDate.add(Calendar.DATE, -1);//减去一天,变为当月最后一天
return sdf.format(lastDate.getTime());
}
//获得当上月的最后一天
public static String getLastDayOfBeforeMonthYMD() {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1号
lastDate.add(Calendar.MONTH, 0);//变为当月的1号
lastDate.add(Calendar.DATE, -1);//减去一天,变为当月最后一天
return sdf.format(lastDate.getTime());
}
//获取当天时间
public static String getNowDate() {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
return sdf.format(lastDate.getTime());
}
public static String getNowDatehms() {
String dateFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
return sdf.format(lastDate.getTime());
}
public static String getToday() {
String dateFormat = SystemConstant.FORMAT_DATE_YYMMDD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
return sdf.format(lastDate.getTime());
}
public static String getTodayYMD() {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
return sdf.format(lastDate.getTime());
}
public static String getTodaydetail() {
String dateFormat = SystemConstant.FORMAT_DATE_YMDHMS_STRING;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
return sdf.format(lastDate.getTime());
}
//获取当月第一天
public static Date getFirstDayOfMonth() {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1号
return strToDate(sdf.format(lastDate.getTime()), dateFormat);
}
//获取当月第一天
public static Date getFirstDayOfMonth(String pattern) {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
if(null != pattern && !pattern.isEmpty()) {
dateFormat = pattern;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1);//设为当前月的1号
return strToDate(sdf.format(lastDate.getTime()), dateFormat);
}
//获取当月第一天
public static String getFirstDayOfTheMonth(int i) {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.set(Calendar.DATE, 1+i);//设为当前月的1号
return sdf.format(lastDate.getTime());
}
//获取上月第一天
public static String getFirstDayOfTheBefordeMonth(int i) {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH,-1);//变为上月
lastDate.set(Calendar.DATE, 1+i);
return sdf.format(lastDate.getTime());
}
//获取本月
public static String getFirstmonth() {
String dateFormat = SystemConstant.FORMAT_MONTH;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH,+0);
return sdf.format(lastDate.getTime());
}
//获取未来一年
public static String getEndDaymonth() {
String dateFormat = SystemConstant.FORMAT_MONTH;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH,+12);
return sdf.format(lastDate.getTime());
}
//获取下个月最后一天
public static String getEndDayOfTheNextMonth(int i) {
String dateFormat = SystemConstant.FORMAT_DATE_YMD;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Calendar lastDate = Calendar.getInstance();
lastDate.add(Calendar.MONTH,+i);//
lastDate.set(Calendar.DATE, 29);
return sdf.format(lastDate.getTime());
}
//获取当天时间
public static Date getNowTime(String dateformat) {
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);//可以方便地修改日期格式
return strToDate(dateFormat.format(now), dateformat);
}
//获取当天的开始时间
public static String getStartTime(String date){
String dateFromFormat = SystemConstant.FORMAT_DATE_YMD;
String dateToFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat dateFormatFrom = new SimpleDateFormat(dateFromFormat);
SimpleDateFormat dateFormatTo = new SimpleDateFormat(dateToFormat);
Calendar todayStart = Calendar.getInstance();
try{
Date parsedDate = dateFormatFrom.parse(date);
todayStart.setTime(parsedDate);
todayStart.set(Calendar.HOUR_OF_DAY, 0);
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
}catch (ParseException ex){
ex.printStackTrace();
}
return dateFormatTo.format(todayStart.getTime()) ;
}
//获取当天的开始时间
public static String getDayStartTime(String date,String dateFromFormat, String dateToFormat){
// String dateFromFormat = SystemConstant.FORMAT_DATE_YMD;
// String dateToFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat dateFormatFrom = new SimpleDateFormat(dateFromFormat);
SimpleDateFormat dateFormatTo = new SimpleDateFormat(dateToFormat);
Calendar todayStart = Calendar.getInstance();
try{
Date parsedDate = dateFormatFrom.parse(date);
todayStart.setTime(parsedDate);
todayStart.set(Calendar.HOUR_OF_DAY, 0);
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
}catch (ParseException ex){
ex.printStackTrace();
}
return dateFormatTo.format(todayStart.getTime()) ;
}
//获取当天的结束时间
public static String getEndTime(String date){
String dateFromFormat = SystemConstant.FORMAT_DATE_YMD;
String dateToFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat dateFormatFrom = new SimpleDateFormat(dateFromFormat);
SimpleDateFormat dateFormatTo = new SimpleDateFormat(dateToFormat);
Calendar todayEnd = Calendar.getInstance();
try{
Date parsedDate = dateFormatFrom.parse(date);
todayEnd.setTime(parsedDate);
todayEnd.set(Calendar.HOUR_OF_DAY, 23);
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
}catch (ParseException ex){
ex.printStackTrace();
}
return dateFormatTo.format(todayEnd.getTime());
}
public static String getEndTime(Date date){
String dateFromFormat = SystemConstant.FORMAT_DATE_YMD;
String dateToFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat dateFormatFrom = new SimpleDateFormat(dateFromFormat);
SimpleDateFormat dateFormatTo = new SimpleDateFormat(dateToFormat);
Calendar todayEnd = Calendar.getInstance();
try{
todayEnd.setTime(date);
todayEnd.set(Calendar.HOUR_OF_DAY, 23);
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
}catch (Exception ex){
ex.printStackTrace();
}
return dateFormatTo.format(todayEnd.getTime());
}
//获取当天的结束时间
public static String getDayEndTime(String date,String dateFromFormat, String dateToFormat){
// String dateFromFormat = SystemConstant.FORMAT_DATE_YMD;
// String dateToFormat = SystemConstant.FORMAT_DATE_YMDHMS;
SimpleDateFormat dateFormatFrom = new SimpleDateFormat(dateFromFormat);
SimpleDateFormat dateFormatTo = new SimpleDateFormat(dateToFormat);
Calendar todayEnd = Calendar.getInstance();
try{
Date parsedDate = dateFormatFrom.parse(date);
todayEnd.setTime(parsedDate);
todayEnd.set(Calendar.HOUR_OF_DAY, 23);
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
}catch (ParseException ex){
ex.printStackTrace();
}
return dateFormatTo.format(todayEnd.getTime());
}
public static Date getYesterday() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
public static Map<String,String> getFirstAndLastDayOfWeek(Integer year, Integer week) {
week=week-1;
Map<String,String> map=new HashMap<String, String>();
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);
Calendar cal = (GregorianCalendar) c.clone();
cal.add(Calendar.DATE, week * 7);
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(cal.getTime());
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
map.put("first_day",format(c.getTime(), SystemConstant.FORMAT_DATE_YMDHMS));
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()+6);
map.put("last_day",format(c.getTime(), SystemConstant.FORMAT_DATE_YMDHMS));
return map;
}
public static String getYesterdayStr() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
String yesterday = new SimpleDateFormat(SystemConstant.FORMAT_DATE_YMD).format(cal.getTime());
return yesterday;
}
public static String getYesterdayStrHDS() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
String yesterday = new SimpleDateFormat(SystemConstant.FORMAT_DATE_YMDHMS_STRING).format(cal.getTime());
return yesterday;
}
public static String getYesterdayStr(int i) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1-i);
String yesterday = new SimpleDateFormat(SystemConstant.FORMAT_DATE_YMD).format(cal.getTime());
return yesterday;
}
public static String getHistoryByNumStr(int i) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.add(Calendar.DATE, -1 - i);
String yesterday = new SimpleDateFormat(SystemConstant.FORMAT_DATE_YMDHMS).format(cal.getTime());
return yesterday;
}
public static Date getElevenFifthEveryDayCheck(int hour,int minute) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,minute);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
public static Date getJDEveryDayCheck() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,14);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
public static Date getLastWeekSunday(Date date) {
Date a = DateUtils.addDays(date, -1);
Calendar cal = Calendar.getInstance();
cal.setTime(a);
cal.set(Calendar.DAY_OF_WEEK, 1);
return cal.getTime();
}
public static Date getJDEveryDayCheckEnd() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,15);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
public static String getDateBefore(String date) {
Date dates = format(date, SystemConstant.FORMAT_DATE_YMDHMS);
Calendar cal = Calendar.getInstance();
cal.setTime(dates);
cal.add(Calendar.DATE, -1);
String yesterday = new SimpleDateFormat(SystemConstant.FORMAT_DATE_YMD).format(cal.getTime());
return yesterday;
}
public static Date getDateBefore(Date date, int hour) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hour);
return cal.getTime();
}
public static Date computeDate(Date date, int diffDay) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, diffDay);
date = c.getTime();
return date;
}
public static String dateToString(Date d) {
return dateToString(d, SystemConstant.FORMAT_DATE_YMD);
}
public static String dateToString(Date d, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(d);
}
public static Date strToDate(String dateStr) {
return strToDate(dateStr, "MM/dd/yyyy");
}
public static Date strParseDate(String dateStr) {
return strParseDate(dateStr, "yyyy-MM-dd");
}
public static Date strToDate(String dateStr, String format) {
if (StringUtils.isEmpty(dateStr)) {
return null;
}
SimpleDateFormat dateFmt = new SimpleDateFormat(format);
dateFmt.setLenient(false);
ParsePosition pos = new ParsePosition(0);
return dateFmt.parse(dateStr, pos);
}
public static Date strParseDate(String dateStr, String format) {
if (StringUtils.isEmpty(dateStr)) {
return null;
}
SimpleDateFormat dateFmt = new SimpleDateFormat(format);
try {
return dateFmt.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static boolean compareDate(Date date1, Date date2){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(date1).equals(simpleDateFormat.format(date2));
}
public static String getDayOfWeek(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
String DayOfWeek = "";
switch(dayOfWeek){
case 1:{DayOfWeek = "Sun";break;}
case 2:{DayOfWeek = "Mon";break;}
case 3:{DayOfWeek = "Tue";break;}
case 4:{DayOfWeek = "Wed";break;}
case 5:{DayOfWeek = "Thu";break;}
case 6:{DayOfWeek = "Fri";break;}
case 7:{DayOfWeek = "Sat";break;}
}
return DayOfWeek;
}
public static String getDayOfWeek(String date){
String DayOfWeek = "week";
try{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(format.parse(date));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
switch(dayOfWeek){
case 1:{DayOfWeek = "Sun";break;}
case 2:{DayOfWeek = "Mon";break;}
case 3:{DayOfWeek = "Tue";break;}
case 4:{DayOfWeek = "Wed";break;}
case 5:{DayOfWeek = "Thu";break;}
case 6:{DayOfWeek = "Fri";break;}
case 7:{DayOfWeek = "Sat";break;}
}
}catch (Exception e){
return DayOfWeek;
}
return DayOfWeek;
}
public static Integer getIndexOfDayOfWeek(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
return dayOfWeek;
}
public static Integer getWeekOfYear(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.WEEK_OF_YEAR);
}
public static Integer getWeekOfYear(String date){
Calendar c = Calendar.getInstance();
try{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
c.setTime(format.parse(date));
}catch (Exception e){
return 100;
}
return c.get(Calendar.WEEK_OF_YEAR);
}
public static Date getWeekBeginFromWk(int week){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return calendar.getTime();
}
public static Date getWeekEndFromWk(int week){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.add(Calendar.DAY_OF_WEEK, 6);
return calendar.getTime();
}
/**
* 判断当前日期是星期几
*
* @param pTime 修要判断的时间
* @return dayForWeek 判断结果
* @Exception 发生异常
*/
public static int dayForWeek(String pTime) {
int dayForWeek = 100;
try{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(format.parse(pTime));
if(c.get(Calendar.DAY_OF_WEEK) == 1){
dayForWeek = 7;
}else{
dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
}
}catch (Exception ex){
return dayForWeek;
}
return dayForWeek;
}
public static Date getWeekBegin() {
Calendar cal = Calendar.getInstance();
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
return cal.getTime();
}
public static Date getWeekEnd() {
Calendar cal = Calendar.getInstance();
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
cal.add(Calendar.DATE, 6);
return cal.getTime();
}
public static Date getLastDayBegin() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_MONTH, -1);
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
return calendar.getTime();
}
public static Date getLastDayEnd() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_MONTH, -1);
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,59);
calendar.set(Calendar.MILLISECOND,999);
return calendar.getTime();
}
public static Date getLastWeekBegin() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.WEEK_OF_YEAR, -1);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return calendar.getTime();
}
public static Date getLastMonthBegin() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
public static Date getLastYearBegin() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
public static Date getYearBegin() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.getTime();
}
public static Date getLastYearYesterday() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
calendar.add(Calendar.DAY_OF_MONTH, -1);
return calendar.getTime();
}
public static Date getLastWeekEnd() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.WEEK_OF_YEAR, -1);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(calendar.getTime());
calendar.add(Calendar.WEEK_OF_YEAR, 1);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return calendar.getTime();
}
public static Date getLastMonthEnd() {
Calendar calendar = Calendar.getInstance();
// calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, 0);
return calendar.getTime();
}
public static int getCurrentYear() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}
public static int getYearByDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static Date dateIncrement(Date date,int m){
Calendar begin=Calendar.getInstance();
begin.setTime(date);
for(int i=0;i<m;i++){
begin.add(Calendar.DAY_OF_YEAR, 1);
}
return begin.getTime();
}
public static Date getWeekBeginByDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
return cal.getTime();
}
public static Date getWeekEndByDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 2;
cal.add(Calendar.DATE, -day_of_week);
cal.add(Calendar.DATE, 6);
return cal.getTime();
}
public static boolean isSameDate(Date date1, Date date2) {
if(null != date1 && null != date2){
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
boolean isSameYear = cal1.get(Calendar.YEAR) == cal2
.get(Calendar.YEAR);
boolean isSameMonth = isSameYear
&& cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
boolean isSameDate = isSameMonth
&& cal1.get(Calendar.DAY_OF_MONTH) == cal2
.get(Calendar.DAY_OF_MONTH);
return isSameDate;
}
return false;
}
/**
* JAVA获取某段时间内的所有日期字符串 格式化YYYY-MM-DD
*/
public static List<String> findDatesStr(String startDate, String endDate) throws ParseException {
List<String> datesStr=new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dBegin = sdf.parse(startDate);
Date dEnd = sdf.parse(endDate);
List<Date> lDate = findDates(dBegin, dEnd);
for (Date date : lDate) {
datesStr.add(sdf.format(date));
}
return datesStr;
}
/**
* JAVA获取某段时间内的所有日期
*/
public static List<Date> findDates(Date dBegin, Date dEnd) {
List lDate = new ArrayList();
lDate.add(dBegin);
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(dEnd);
// 测试此日期是否在指定日期之后
while (dEnd.after(calBegin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
lDate.add(calBegin.getTime());
}
return lDate;
}
/**
* 根据传入的时间往前推4周
* @param date
* @return
*/
public static Date getFourWeekEnd(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.WEEK_OF_YEAR,-4);
cal.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
cal.set(Calendar.HOUR_OF_DAY,23);
cal.set(Calendar.MINUTE,59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
// java判断某个时间是否是在当前时间的七天之内
public static boolean isLatestWeek(Date date, Date now){
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.setTime(now);//把当前时间赋给日历
calendar.add(Calendar.DAY_OF_MONTH, -7); //设置为7天前
Date before7days = calendar.getTime(); //得到7天前的时间
if(before7days.getTime() < date.getTime()){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
// String exchangeStatus = "1";;
// String syncStatus = "2";
// String waitConfirmExchangeTradeSql= "SELECT ceptrade.* from csexchange,ceptrade where csexchange.ordercode = ceptrade.taobaotid and csexchange.shopid= ceptrade.shopid " +
// "and csexchange.`status`='%s' and ceptrade.syncstatus='%s' and starttime>date_sub(curdate(),interval 7 day) and csexchange.shopid=%s";
// waitConfirmExchangeTradeSql = String.format(waitConfirmExchangeTradeSql,exchangeStatus,syncStatus,2);
listDate("2018-01-01","2018-02-01");
System.out.println(getLastMonthEnd());
// String startTime = "2017-02-16";
// Date startDate = DateUtil.format(startTime,SystemConstant.FORMAT_DATE_YMD);
// Date now = DateUtil.format("2017-02-22 00:00:00",SystemConstant.FORMAT_DATE_YMDHMS);
// System.out.println(startDate);
//
//
// /**
// * 判断日期是否在七天之内
// */
// System.out.println(DateUtil.isLatestWeek(startDate, now));
}
public static Date getOneSecondAgo(String syncStartTime, String dateFormat) {
Calendar cal = Calendar.getInstance();
cal.setTime(Utils.convertStringToDate(syncStartTime,dateFormat));
cal.add(Calendar.SECOND,-1);
return cal.getTime();
}
public static Date getOneDayAgo(Date syncStartTime) {
Calendar cal = Calendar.getInstance();
cal.setTime(syncStartTime);
cal.add(Calendar.HOUR,-24);
return cal.getTime();
}
/***
*
* @param date 时间
* @return cron类型的日期
*/
public static String getCron(Date date){
SimpleDateFormat sdf = new SimpleDateFormat(SystemConstant.CRON_DATE_FORMAT);
String formatTimeStr = "";
if (date != null) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
}
/***
*
* @param cron Quartz cron的类型的日期
* @return Date日期
*/
public static Date getDate(String cron) {
if(cron == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(SystemConstant.CRON_DATE_FORMAT);
Date date = null;
try {
date = sdf.parse(cron);
} catch (ParseException e) {
return null;// 此处缺少异常处理
}
return date;
}
public static List<String> listDate(String startDate, String endDate) {
List<String> result = new ArrayList<String>();
Calendar c = Calendar.getInstance();
DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
//开始时间必须小于结束时间
Date beginDate = null;
Date endDate_ = null;
try {
beginDate = dateFormat1.parse(startDate);
endDate_ = dateFormat1.parse(endDate);
Date date = beginDate;
result.add(format(beginDate,SystemConstant.FORMAT_DATE_YMD));
while (!date.equals(endDate_)) {
c.setTime(date);
c.add(Calendar.DATE, 1); // 日期加1天
date = c.getTime();
result.add(format(c.getTime(),SystemConstant.FORMAT_DATE_YMD));
}
if (!beginDate.equals(endDate_)&&!result.contains(format(endDate_,SystemConstant.FORMAT_DATE_YMD))) {
result.add(format(endDate_,SystemConstant.FORMAT_DATE_YMD));
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* @description: 获取前一天的截止时间
* @author Ethan
* @date 2019/4/8 14:35
*/
public static Date getYesterdayEndTime() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, -1);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
return cal.getTime();
}
/**
* @description: 获取前一天的开始时间
* @author Ethan
* @date 2019/4/8 14:35
*/
public static Date getYesterdayStartTime() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, -1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* @description: 时间字符串转为yyy-MM-dd HH:mm:ss格式的日期
* @author Ethan
* @date 2019/4/8 23:57
*/
public static Date parseDateTime(String str) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.parse(str);
}
/**
* 获取i秒之后的时间
* @param date
* @param i
* @return
*/
public static Date getNextISecond(Date date,int i) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.SECOND, i);
date = c.getTime();
return date;
}
/**
* 获取时间是今年第几周
* @param date
* @return
*/
public static int getDateWeek(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(date);
return calendar.get(Calendar.WEEK_OF_YEAR);
}
/**
* 获取周一
* @param date
* @return
*/
public static String getMonday(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);//周一
return format(calendar.getTime(),SystemConstant.FORMAT_DATE_YMD);
}
/**
* 获取月份
* @param date
* @return
*/
public static int getMonth(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
/**
* 转化为美国太平洋时间
* @param date
* @return
*/
public static String getUSATime(Date date) {
Instant instant = date.toInstant();
ZoneId zone = ZoneId.of("America/Los_Angeles");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zone);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(SystemConstant.FORMAT_DATE_YMDHMS);
return zonedDateTime.format(formatter);
}
/**
* 转化为北京时间
* @param date
* @return
*/
public static Date getCNTime(String date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(SystemConstant.FORMAT_DATE_YMDHMS);
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date date_ = null;
try {
date_ = sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
if (date_ != null) {
Instant instant = date_.toInstant();
ZoneId zone = ZoneId.of("Asia/Shanghai");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zone);
return Date.from(zonedDateTime.toInstant());
}
return null;
}
}
package com.pvuv.pvuv.util;
import org.apache.http.Consts;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.CodingErrorAction;
/**
* Created by villiam on 17/6/8.
*/
public class HttpClientConnectionPool {
private static final Logger LOG = LoggerFactory.getLogger(HttpClientConnectionPool.class);
static final int timeOut = 50 * 1000;
static PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
static {
connectionManager.setMaxTotal(2000);
connectionManager.setDefaultMaxPerRoute(1000);
connectionManager.setDefaultSocketConfig(getSocketConfig());
connectionManager.setDefaultConnectionConfig(getConnectionConfig());
}
public static CloseableHttpClient getClient(){
return HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(getRequestConfig())
.build();
}
private static RequestConfig getRequestConfig() {
// 配置请求的超时设置
return RequestConfig.custom()
.setConnectionRequestTimeout(timeOut)
.setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
}
private static SocketConfig getSocketConfig(){
return SocketConfig.custom()
.setTcpNoDelay(true) //是否立即发送数据,设置为true会关闭Socket缓冲,默认为false
.setSoReuseAddress(true) //是否可以在一个进程关闭Socket后,即使它还没有释放端口,其它进程还可以立即重用端口
.setSoTimeout(50000) //接收数据的等待超时时间,单位ms
.setSoLinger(6) //关闭Socket时,要么发送完所有数据,要么等待60s后,就关闭连接,此时socket.close()是阻塞的
.setSoKeepAlive(true) //开启监视TCP连接是否有效
.build();
}
private static ConnectionConfig getConnectionConfig(){
return ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.build();
}
public static void releaseResponse(CloseableHttpResponse httpResponse){
try {
if(null != httpResponse){
httpResponse.close();
}
}catch (IOException e){
LOG.error("shut down response error happened: "+e.getMessage());
}
}
}
package com.pvuv.pvuv.util;
import com.google.gson.Gson;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by villiam on 16/7/19.
*/
public class HttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
/**
* POST请求
*
* @param url
* URL
* @param parameterMap
* 请求参数
* @return 返回结果
*/
public static String post(String url, Map<String, Object> parameterMap) {
Assert.hasText(url);
String result = null;
Gson gson = new Gson();
CloseableHttpClient httpclient = HttpClientConnectionPool.getClient();
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (parameterMap != null) {
for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String value = ConvertUtils.convert(entry.getValue());
if (StringUtils.isNotEmpty(name)) {
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
httpResponse = httpclient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientConnectionPool.releaseResponse(httpResponse);
}
return result;
}
/**
* GET请求
*
* @param url
* URL
* @param parameterMap
* 请求参数
* @return 返回结果
*/
public static String get(String url, Map<String, Object> parameterMap) {
Assert.hasText(url);
String result = null;
CloseableHttpClient httpClient = HttpClientConnectionPool.getClient();
CloseableHttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (parameterMap != null) {
for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String value = ConvertUtils.convert(entry.getValue());
if (StringUtils.isNotEmpty(name)) {
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
}
HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientConnectionPool.releaseResponse(httpResponse);
}
return result;
}
/**
* GET请求
*
* @param url
* URL
* @param header
* Header
* @param parameterMap
* 请求参数
* @return 返回结果
*/
public static String getWithHeader(String url,String header, Map<String, Object> parameterMap) {
Assert.hasText(url);
String result = null;
CloseableHttpClient httpclient = HttpClientConnectionPool.getClient();
CloseableHttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
if (parameterMap != null) {
for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
String name = entry.getKey();
String value = ConvertUtils.convert(entry.getValue());
if (StringUtils.isNotEmpty(name)) {
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
}
HttpGet httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
httpGet.setHeader("apikey",header);
httpResponse = httpclient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
HttpClientConnectionPool.releaseResponse(httpResponse);
}
return result;
}
/**
* 得到HTTP请求body中的JSON字符串
* @param inputStream
* @return
* @throws IOException
*/
public static String getRequestBody(InputStream inputStream) throws IOException {
Gson gson = new Gson();
Reader input = new InputStreamReader(inputStream,"UTF-8");
Writer output = new StringWriter();
char[] buffer = new char[DEFAULT_BUFFER_SIZE];
int n = 0;
while(-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return gson.toJson(output.toString());
}
/**
* POST请求
*
* @param url
* URL
* @param body
* 请求参数
* @return 返回结果
*/
public static String postWithBody(String url,Map<String, String> headers, String body) {
Assert.hasText(url);
String result = null;
CloseableHttpClient httpClient = HttpClientConnectionPool.getClient();
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(url);
// 添加http headers
if (headers != null && headers.size() > 0) {
for (String key : headers.keySet()) {
httpPost.addHeader(key, headers.get(key));
}
}
httpPost.setHeader("Content-Type","application/json");
httpPost.setEntity(new StringEntity(body,"UTF-8"));
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
} catch (ClientProtocolException e) {
LOG.error(e.toString() + "http response result is " + result);
e.printStackTrace();
} catch (Exception e) {
LOG.error(e.toString() + "http response result is " + result);
e.printStackTrace();
} finally {
HttpClientConnectionPool.releaseResponse(httpResponse);
}
return result;
}
}
package com.pvuv.pvuv.util;
import java.util.HashMap;
import java.util.Map;
public class SystemConstant {
//登录类型
public static final int LOGIN_TYPE_WEB = 0;
public static final int LOGIN_TYPE_ANDROID = 1;
public static final String COOKIE_USER_PRE = "ubaby_user_";
public static final String COOKIE_PSW_PRE = "ubaby_psw_";
//WEB SERVICE URL映射常量地址
public static final String WS_URL_LOGIN = "/login/{accountCode}/{password}";
public static final String WS_URL_LIST_ALLBRAND = "/listAllBrand/{token}";
public static final String WS_URL_LIST_ALLCATEGORY = "/listAllCategory/{token}";
public static final String WS_URL_LIST_ALLFOLDER = "/listAllFolder/{token}";
public static final String WS_URL_LIST_BRAND_FOLDER = "/listBrandFolder/{brandId}/{token}";
//URL映射常量地址
public static final String URL_REALTIME_CONTROLLER = "/realtime";
public static final String URL_TAOBAOMESSAGE_CONTROLLER = "/externalInterface";
public static final String URL_WAREHOUSE_CONTROLLER = "/warehouse";
public static final String URL_REALTIMEINTER_CONTROLLER = "/realtimeInterface";
public static final String URL_API_CREATED = "/api/created";
public static final String URL_USER_CONTROLLER = "/userController";
public static final String URL_EMAIL_CONTROLLER = "/emailController";
public static final String URL_FTP_CONTROLLER = "/ftpController";
public static final String URL_SWITCH_CONTROLLER = "/switchController";
public static final String URL_ROLE_CONTROLLER = "/roleController";
public static final String URL_RESOURCE_CONTROLLER = "/resourceController";
public static final String URL_MENU_CONTROLLER = "/menuController";
public static final String URL_GROUP_CONTROLLER = "/groupController";
public static final String URL_JOB_CONTROLLER = "/ckcjob";
public static final String URL_JOB_SHOPEXCHANGE = "/shopExchange";
public static final String URL_SCHEDULE_CONTROLLER = "/ckSchedule";
public static final String URL_SHOP_CONTROLLER = "/shop";
public static final String URL_CUSTOMER_CONTROLLER = "/customer";
public static final String URL_COMMON = "/common";
public static final String URL_TAOBAOAG_CONTROLLER ="/taobaoAG";
public static final String URL_OA_CONTROLLER = "/oa";
public static final String URL_CUSTOMER_LOG_CONTROLLER = "/customerlog";
public static final String URL_PROMOTION_CONTROLLER= "/promotion";
public static final String URL_SHOPMANAGER_CONTROLLER = "/shopManager";
public static final String URL_JOBMANAGER_CONTROLLER = "/jobManager";
public static final String URL_PRICEMANAGER_CONTROLLER = "/priceManager";
public static final String URL_ALIPAYSTATEMENT_CONTROLLER = "/alipayStatement";
public static final String URL_GOODS_CONTROLLER = "/goods";
public static final String URL_WEEK_REPORT_CONTROLLER = "/weekReport";
public static final String URL_INVENTORY_CONTROLLER = "/inventory";
public static final String URL_MATCHPRODUCT_CONTROLLER = "/matchProduct";
public static final String URL_PRODUCT_CONTROLLER = "/product";
public static final String URL_DIVIDE_CONTROLLER = "/divide";
public static final String URL_CATEGORY_CONTROLLER = "/category";
public static final String URL_ORDER_LOG_CONTROLLER = "/orderLog";
public static final String URL_ORDER_CONTROLLER = "/order";
public static final String URL_SHIPPING_CONTROLLER = "/ship";
public static final String URL_HISTORYORDER_CONTROLLER = "/historyOrder";
public static final String URL_PM_CONTROLLER = "/pmController";
public static final String URL_RETURN_CONTROLLER = "/return";
public static final String URL_REPEAT_CONTROLLER = "/repeat";
public static final String URL_VIP_CONTROLLER = "/vip";
public static final String URL_SHORTSTOCK_CONTROLLER = "/shortStock";
public static final String URL_UPPRODUCT_CONTROLLER = "/upproduct";
public static final String URL_WECHATPAY_CONTROLLER = "/wechatPay";
public static final String URL_RESERVE_CONTROLLER = "/reserve";
public static final String URL_PRESALE_CONTROLLER = "/presale";
public static final String URL_REPORT_CONTROLLER = "/report";
public static final String URL_MERGE_ORDER_CONTROLLER = "/mergeOrder";
public static final String URL_RETURNREPORT_CONTROLLER = "/returnReport";
public static final String URL_USER_REGISTER = "/reg";
public static final String URL_USER_LOGIN = "/login";
public static final String URL_USER_LOGOUT = "/logout";
public static final String URL_COMBOGRID = "/combogrid";
public static final String URL_COMBOBOX = "/combobox";
public static final String URL_DATAGRID = "/datagrid";
public static final String URL_REMOVE = "/remove";
public static final String URL_UPDATE_STATUS= "/updateStatus";
public static final String URL_ADD = "/add";
public static final String URL_EDIT = "/edit";
public static final String URL_MODIFY_ROLE = "/modifyRole";
public static final String URL_MODIFY_GROUP = "/modifyGroup";
public static final String URL_MODIFY_PWD = "/modifyPwd";
public static final String URL_CURRENT_USER_PWD = "/modifyCurrentUserPwd";
public static final String URL_USER_INFO = "/userInfo";
public static final String URL_TREE_GRID = "/treegrid";
public static final String URL_ALLTREE_GRID = "/allTreeNode";
public static final String URL_ORDER_HANGS="/taobaoTrade";
public static final String URL_EDIT_TRADEADDRESS="/taobaoaddress";
public static final String URL_GUAVA_CATCH = "/guava";
//VIEW地址
public static final String VIEW_USER_INFO = "user/userInfo";
//常用格式
public static final String FORMAT_DATE_YMDHMS = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_DATE_HH = "HH";
public static final String FORMAT_DATE_YMDHMS_STRING = "yyyyMMddHHmmss";
public static final String FORMAT_DATE_YMD = "yyyy-MM-dd";
public static final String FORMAT_MONTH = "yyyy-MM";
public static final String FORMAT_DATE_YYMMDD = "yyyyMMdd";
public static final String FORMAT_DATE_YYMM = "yyyyMM";
public static final String FORMAT_DATE_MDYHMS = "MM/dd/yy HH:mm";
public static final String CRON_DATE_FORMAT = "ss mm HH dd MM ? yyyy";
//消息字符串
public static final String MSG_REGISTER_SUCCESS = "注册成功!";
public static final String MSG_DELETE_SUCCESS = "删除成功!";
public static final String MSG_DELETE_FAIL = "删除失败!";
public static final String MSG_LOGIN_SUCCESS = "登录成功!";
public static final String MSG_LOGIN_FAIL = "登录失败!";
public static final String MSG_ADD_SUCCESS = "添加成功!";
public static final String MSG_ADD_FAIL = "添加失败!";
public static final String MSG_EDIT_SUCCESS = "修改成功!";
public static final String MSG_EDIT_FAIL = "修改失败!";
public static final String MSG_RECORD_ALREADY_EXIST = "记录已经存在!";
public static final String MSG_UPLOAD_SUCCESS = "上传成功!";
public static final String MSG_UPLOAD_FAIL = "上传失败!";
public static final String MSG_SUCCESS_DELIVERY = "发货成功!";
public static final String MSG_FAILED_DELIVERY = "发货失败!";
public static final String JOB_LAUNCH_FAIL ="Job启动失败!";
public static final String JOB_LAUNCH_SUCCESS="Job启动成功!";
public static final String JOB_CORRECTNESS_INFOR="请填写店铺与时间!";
public static final String JOB_ERROR_INFO = "Job错误信息:";
public static final String JOB_STOP_SUCCESS="已经停止了{0}个Job!";
public static final String JOB_STOP_FAIL="停止Job失败,错误信息如下:";
public static final String MSG_ORDEREXPORT_FAIL = "订单导出失败!";
public static final String MSG_ORDEREXPORT_SUCCESS = "订单导出成功!";
public static final String SHOP_ID_NOT_IN=" and shopid !=5 and shopid !=10 and shopid !=12 and shopid !=31";
public static final String DAILY_REPORT_SHOP_ID_NOT_IN=" and shopid !=5 and shopid !=10 and shopid !=31 and shopid !=6 and shopid !=12 and !ISNULL(shopid)";
public static final String PROMOTION="promotion_";
// 品牌名字
public static final String BRAND_CK="ck";
public static final String BRAND_PEDRO="pedro";
public static Map<String,String> kuaiDi100 = new HashMap<String, String>();
static {
kuaiDi100.put("sf","shunfeng");
kuaiDi100.put("COD","jd");
kuaiDi100.put("CSCOD","shunfeng");
kuaiDi100.put("EMS","EMS");
kuaiDi100.put("ZTO","zhongtong");
}
}
package com.pvuv.pvuv.util;
import com.movitech.apollo.foundation.util.SequenceUtils;
import com.movitech.apollo.seamwork.model.Guidable;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* General utility classes<br>
* <br>
*
* @created Jan 25, 2007 @ 12:14:05 PM
* @author dzhao
* @version 1.0
*/
public final class Utils {
// For random string/GUID generation
public static final String UPPER_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String LOWER_ALPHA = "abcdefghijklmnopqrstuvwxyz";
public static final String ALPHA = UPPER_ALPHA + LOWER_ALPHA;
public static final String ALPHANUMERIC = ALPHA + "0123456789";
public static final String GUID_ALPHA = ALPHANUMERIC + "-_";
private static final Random RANDOM = new Random();
public static String integrityFileFolderLocation(String location) {
if (!location.substring(location.length()-1).equals("/")) {
return location + "/";
}
return location;
}
public static Double getDoubleValueOf(String doubleValue) {
if (doubleValue != null) {
return Double.valueOf(doubleValue);
} else {
return 0.00;
}
}
public static Double getDoubleValueOf(Long doubleValue) {
return getDoubleValueOf(doubleValue.toString());
}
/**
* Create a random GUID of the maximum length<br>
* First and last chars have to be alphanumeric
*
* @return random guid
*/
public static final String randomProductGuid() {
return "CK-" + randomString(ALPHANUMERIC, 1) + randomString(GUID_ALPHA, 28 - 2) + randomString(ALPHANUMERIC, 1);
}
/**
* Create a random GUID of the maximum length<br>
* First and last chars have to be alphanumeric
*
* @return random guid
*/
public static final String randomGuid() {
return randomString(ALPHANUMERIC, 1) + randomString(GUID_ALPHA, Guidable.MAX_GUID_SIZE - 2) + randomString(ALPHANUMERIC, 1);
}
/**
* Create a string of random characters given an alphabet
*
* @param alpha
* @param length
* @return random string
*/
public static final String randomString(String alpha, int length) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < length; i++) {
out.append(alpha.charAt(RANDOM.nextInt(alpha.length())));
}
return out.toString();
}
/**
* Generate a number of random integer
*
* @param length
* @return random string
*/
public static final Integer randomInteger(int length) {
return RANDOM.nextInt(length) + 1;
}
/**
* Generate a string of random characters
*
* @param length
* @return random string
*/
public static final String randomString(int length) {
return randomString(ALPHA, length);
}
/**
* Create a random GUID for orders
* @param shopAlias shop type like: TB,ES,MS
* @param orderAlias order type like: OD, RO, CO
* @return
*/
public static final String randomGuid(String shopAlias, String orderAlias) {
StringBuilder out = new StringBuilder();
out.append(shopAlias);
out.append(orderAlias);
String code = SequenceUtils.getSequenceCodeByDay(out.toString(), 3);
return code;
}
public static String convertDateToString(Date date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}
public static Date convertStringToDate(String date, String pattern) {
if(date=="")
return null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new Date();
}
public static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return sdf.format(date);
}
public static String removeSpecialCharacter(String targetString) {
if (targetString.indexOf("}") > 0 || targetString.indexOf("{") > 0) {
targetString = targetString.replaceAll("\\{", "");
targetString = targetString.replaceAll("\\}", "");
}
return targetString;
}
public static String removeSpecialCharacterJson(String targetString) {
if (targetString.indexOf("]") > 0 || targetString.indexOf("[") > 0) {
targetString = targetString.replaceAll("\\[", "");
targetString = targetString.replaceAll("\\]", "");
}
return targetString;
}
public static String replaceSpecialCharacter(String targetString) {
if (targetString != null) {
char[] invalidateChars = new char[]{'\t', '\r','\n', ',','"','!','@','#','$','%','^','&','*','(',')','_','+','{','}','[',']',':',';','\'','.','<','>','?','\\','|','\b'};
if (!StringUtils.containsNone(targetString, invalidateChars)){
for(char invalidateChar: invalidateChars) {
targetString = StringUtils.replaceChars(targetString, invalidateChar, ' ');
}
}
}
return targetString;
}
public static String convertObject2Json(Object obj) {
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(obj);
return json;
} catch (IOException e) {
e.printStackTrace();
return "{}";
}
}
private static byte[] lock = new byte[0];
// 位数,默认是9位
private final static long ramdomMath = 1000000000;
public static String createTaobaotidSplit(String seed) {
long r = 0;
synchronized (lock) {
r = (long) ((Math.random() + 1) * ramdomMath);
}
return seed+ System.currentTimeMillis() + String.valueOf(r).substring(1);
}
/**
*
* @param fileName 写入的文件名,完整地址
* @param text 写入文本内容
*/
public static void writerFile(String fileName,String text) {
File file = new File(fileName);
FileWriter fileWriter=null;
try {
if (!file.exists()){
file.createNewFile();
}
fileWriter = new FileWriter(file,true);
fileWriter.write(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (fileWriter !=null) {
fileWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.pvuv.pvuv.util;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Created by villiam on 18/3/20.
*/
public class WechatUtils {
private static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx072302256a82deb1&secret=13b1c66b86e402562249b9478b54732d";
private static final String data_url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend?access_token=";
private static final String pedro_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx56ccb2900f39febe&secret=1c0fdee749bbafa0e15a7cdb58d3c9d5";
private static final String pedro_data_url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend?access_token=";
public static String getAccessToken(){
String token = "";
String result = HttpUtils.get(access_token_url, null);
JSONObject jsonResult = JSONObject.fromObject(result);
if(StringUtils.isNotEmpty(result))
token = jsonResult.getString("access_token");
return token;
}
public static String getWeChatData(String token, String begin, String end){
if(StringUtils.isNotEmpty(token)){
Map<String, Object> parameterMap = new HashMap<String, Object>();
JSONObject jsonObject = new JSONObject();
// jsonObject.put("begin_date","20180318");
// jsonObject.put("end_date","20180318");
jsonObject.put("begin_date",begin);
jsonObject.put("end_date",end);
return HttpUtils.postWithBody(data_url + token, null, jsonObject.toString());
}
return null;
}
public static String getPedroAccessToken(){
String token = "";
String result = HttpUtils.get(pedro_access_token_url, null);
JSONObject jsonResult = JSONObject.fromObject(result);
if(StringUtils.isNotEmpty(result))
token = jsonResult.getString("access_token");
return token;
}
public static String getPedroWeChatData(String token, String begin, String end){
if(StringUtils.isNotEmpty(token)){
Map<String, Object> parameterMap = new HashMap<String, Object>();
JSONObject jsonObject = new JSONObject();
// jsonObject.put("begin_date","20180318");
// jsonObject.put("end_date","20180318");
jsonObject.put("begin_date",begin);
jsonObject.put("end_date",end);
return HttpUtils.postWithBody(pedro_data_url + token, null, jsonObject.toString());
}
return null;
}
public static void main(String args[]){
System.out.println(getWeChatData(getAccessToken(), DateUtil.format(DateUtil.getYesterday(), SystemConstant.FORMAT_DATE_YYMMDD),DateUtil.format(DateUtil.getYesterday(),SystemConstant.FORMAT_DATE_YYMMDD)));
System.out.println(getPedroWeChatData(getPedroAccessToken(), DateUtil.format(DateUtil.getYesterday(), SystemConstant.FORMAT_DATE_YYMMDD),DateUtil.format(DateUtil.getYesterday(),SystemConstant.FORMAT_DATE_YYMMDD)));
}
}
package com.pvuv.pvuv;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class PvuvApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment