Commit 4b2d9875 authored by renjie's avatar renjie

browser-backend

parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
/*
* 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.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.edgec</groupId>
<artifactId>browser-backend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>browser-backend</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.4.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure -->
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.5</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>3.7.110.ALL</version>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>1.50.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.edgec.browserbackend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BrowserBackendApplication {
public static void main(String[] args) {
SpringApplication.run(BrowserBackendApplication.class, args);
}
}
package com.edgec.browserbackend.alipay;
public abstract class AlipayConfig {
public abstract String getAPPID();
public abstract String getAPP_PRIVATE_KEY();
public abstract String getALIPAY_PUBLIC_KEY();
public abstract String getNOTIFY_URL();
public static String RETURN_URL_CLOUDAM = "https://www.cloudam.cn/v2/personal/UserCost?alipayreturn="; // cloudam 费用中心,账户余额
public static String RETURN_URL_CVM = "https://www.cloudam.cn/v2/console/cloudhost-buy?alipayreturn="; // 云主机购买
public static String RETURN_URL_VPS = "https://www.fangguanlian.cn/vpsconsole/vps/cost?alipayreturn="; // vps 费用中心, 账户余额
public static String RETURN_URL_VPS_FRONT = "https://www.fangguanlian.cn/home/detail.html?order="; // VPS购买
public static String RETURN_URL_C3IP = "https://www.cloudam.cn/v2/console/ipcloud-buy?alipayreturn="; //c3ip云购买
public static String RETURN_URL_MODIFYSPEC_DESC = "https://cloudam.cn/v2/console/child-page/4";
public static String RETURN_URL_MODIFYSPEC_ASC = "https://cloudam.cn/v2/console/child-page/3";
public static String RETURN_URL_ORDER = "https://www.cloudam.cn/v2/console/orderDetail?alipayreturn=";
public abstract String getSIGN_TYPE();
public abstract String getCHARSET();
public abstract String getURL();
public abstract String getReturnUrl(boolean isVpsClient, String by);
}
package com.edgec.browserbackend.alipay;
import org.apache.commons.lang3.StringUtils;
public class CloudamAlipayConfig extends AlipayConfig{
@Override
public String getAPPID() {
return "2019071765790965";
}
@Override
public String getAPP_PRIVATE_KEY() {
return "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDDU+npZLO6AoKN" +
"lQBO/3gOMTJEeOBDV5zRdvkrMUBq8R5r5phzkq2T2lxg5gMnZx6Lk/NZ0evSntMG" +
"PzKXFEmVdBKRuqQvQ7gaZNeWA494sCP76dEDPREcvs7qcP7xTuK9/FTqPQH3iUEA" +
"058N03/edQGdv1HLi3BmTYdp2ywZQsb0hqGu6/pPYCLnwSprBdWv1nG3zstcBEmK" +
"PYNKipzy0LpHiGB445XO0EJWV/XK6t1knDKrC6FFiFfxuLy3fHy37jjFW2TxZLSc" +
"ROGs0Py+w9saxIJ1n7jGJqHCQmyuNgPKtelYy1jpbdXIX/2bhW1ck4dOCF8j37Gc" +
"cGZR+c3nAgMBAAECggEASFW1FDe0zzfKvT/mw1qcTTUu1milNIsnifKzR6mPn4r3" +
"pyHYZ0R0f4KoH0JO/LKVfz8lKagx2ufyYifZRlW/Alff4JPr5Y0AitW5eNaMtTcV" +
"vF7UhoyA39JRskRyRU7fbVga4jwBlHgB2JqGFoqymeFe3dpSIjzbPSeM9Ei0Rg3s" +
"hIv+An/U2optO29ggsC0hXyHWXLupaMwbIpBTOHDiFzxW7z4ZxUH1jAL0jvQxuNN" +
"YEY8vAcvJAlz4iab5x2vlEn00crfhE+kwO6f+0Am7spDKjkjsVX8mioD+J/VozZk" +
"517zz5EF66DdtD5i9LdLIGBsWjagbINtVrH7KWqlgQKBgQDzWxlOMpjsP/WFk0L5" +
"ic7HJvflbz+hCJAyQlDAy43Ls8nVYIkeTk2Umae+uSbkMga2N83LN4e1FRNGDjGB" +
"JNDHtzAF3aAwPXS+PDwLGDrgQ44KN8aw/1dt0W9TiBVLHOhAjqPO4UqW0wkgSwNh" +
"HqeuR1GwLyp5IueFZxX/YhNT4QKBgQDNef0W6fDhhcsxyLm5dDL+LuenE1omas74" +
"zNKPaR7yQpZOxqdJYXEI6nrJ1vTUOLa1nqT1/n8kgLNDASRQH5NFQfSizRG07tij" +
"3NLto8DD89h82y7IbY1Rz38FH3Mf+W7soKMKo6tQb7oHOZm2uDTlSpe25neDSJeI" +
"kL+JsEbaxwKBgQCkAOYJ/DFxLh2CGt+NGqF/N7TjK9k+5m1/YY/YjpYODSldowRl" +
"pzHDjtYsw80BBvHdBbisVs0fbYeis9gLB8uofL1hhp35RMGTnzZ756VuFDj6i+Jc" +
"0IiUWwviyJhJGb8wGrEssEo7YRgKamNppWYuHqRfzzmZj7tl/TYm+Wq7IQKBgBFo" +
"NDisuOtiGkStbI55eZhvAND2orx+b+pD79KWZTjAy1sBGUruJlVLB/vxaexQoanh" +
"NrhgRwUgog8bGahwBFnprH/eP5HEajX3jybyqHHxRnXNW7k/DqnPmkMk1uvuhacm" +
"NKnCE9FMpcXW616/XDvQhenIvHcyvyOin5dah6YhAoGASANVYkA4JX3cTXzDvlzh" +
"5l/afal++mv6Ld2TH/3aeg2CBh2HzNIUBCr/SQFpqOjQf6L2lpftDPIbtDB7ogVv" +
"roAgSIXPlz+TK9rgMRI/uzWTP4J164r2UBs5aT5N5Y6hArL7ce1+1QemCsevFRTP" +
"tHwdG2+8KyXqSWp4eyFmBFs=";
}
@Override
public String getALIPAY_PUBLIC_KEY() {
return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkXY3UcHC2Eu4X0Ggf36Kz94aag+nGoBhIjcyXADTCsqYpKLenWC/RzgzbipFKOur+Z8AyxK9pk4Z/B5NlMuSsNM+D4cHdRl21qZszXlygTNIxOnl+tGdlbxjEmlIqwuhSFZRAz7/zhAQ0Rto/1mz+DNmHvhXpXY91xVMLetWXkIKQR+D5IXtAXVkssHevRMiMhMrlazw9Gn1vS+8iKy+Op9G7o9M2LvNiKv0HNOIhvoMqntdPCFWgGNuXMPoobsfkD8dFQs2GzuERgWs+maBQuHWXkghk4RoMYCjS0wKvm8zxJVfHmQ6yApcM676R1pRpJrMzX+LTQINm3UQCaCxKwIDAQAB";
}
@Override
public String getNOTIFY_URL() {
return "https://www.cloudam.cn/accounts/0xalipaycallback/";
}
// public static String RETURN_URL_CLOUDAM = "https://www.cloudam.cn/v2/console/finance?alipayreturn="; // cloudam 费用中心,账户余额
//
// public static String RETURN_URL_CVM = "https://www.cloudam.cn/v2/console/cloudhost-buy?alipayreturn="; // 云主机购买
//
// public static String RETURN_URL_VPS = "https://www.fangguanlian.cn/vpsconsole/vps/cost?alipayreturn="; // vps 费用中心, 账户余额
//
// public static String RETURN_URL_VPS_FRONT = "https://www.fangguanlian.cn/home/detail.html?order="; // VPS购买
@Override
public String getSIGN_TYPE() {
return "RSA2";
}
@Override
public String getCHARSET() {
return "utf-8";
}
@Override
public String getURL() {
return "https://openapi.alipay.com/gateway.do";
}
@Override
public String getReturnUrl(boolean isVpsClient, String by) {
if (StringUtils.isNotEmpty(by)) {
switch (by) {
case "1":
return RETURN_URL_VPS_FRONT; // vps购买
case "2":
return RETURN_URL_CVM; // 云主机购买
case "3":
return RETURN_URL_C3IP; //云ip购买
case "4":
return RETURN_URL_MODIFYSPEC_ASC;
case "5":
return RETURN_URL_MODIFYSPEC_DESC;
case "6":
return RETURN_URL_ORDER;
}
}
// 费用中心
if (isVpsClient) {
return RETURN_URL_VPS;
} else {
return RETURN_URL_CLOUDAM;
}
}
}
\ No newline at end of file
package com.edgec.browserbackend.alipay;
import org.apache.commons.lang3.StringUtils;
public class VpsAlipayConfig extends AlipayConfig{
@Override
public String getAPPID() {
return "2019091967616095";
}
@Override
public String getAPP_PRIVATE_KEY() {
return "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQi9PVnyGA+r1Q"+
"Fu08beA/oGX1FBBWMl6A1e7LydbpFutHY2gtLszQquM2CnfR6cS+p2lhNLRO1al9" +
"LO26NR7F+UEbj0ieo1HLss8jS8qpmIcMjWdYYvEbiK19lEW0aYO2tgDKj+JGtvru" +
"L9mBZnr4quuQPa8gBb07DbJ+GsXBNWfRyz3YjVKfzwbU85azu72Gh/cRvqX6Zcbk" +
"1nlbfvHkhGTv/JkTQBT3ilo2bhPffFyArI20gwA0a9zAGr4h31QOl6Sw6mv3q8ed" +
"u4vBl0vVAAKiQJW1e52thLuJ5tflZToqnk5A7QdwqfCe8mksA3V/97+T04bUzINn" +
"QhFK4Q/JAgMBAAECggEAbN0BONt33t+FIaDGOKxWyoANmTDfEk/62yBSJpl3kXfA" +
"XCS9RhDPJAKA1z4BrFdut+Omc/LSSPDqKAjjFDgUl131KdDTJNS2pzHxRUiUQ5H2" +
"tYu/LfmASVJA1nQnKvWFp0Q9B4Cyqx1rwhjCXvVDLjny+/nnSD0WuhP9YCzTnHY1" +
"U7djStrlHmVmiIrHlSV4Myul0Y7AWy2r7X/f43eSra1UP8J2KmN7IYD1nW19Fkdn" +
"uDnXXDLcctnZ5toMjMbikjzvKyMW8HnPyG5aHztJlJWQ33tpAZBkAIWZ4/4KuVLa" +
"zt6MPUXPEw7urWHVg1cqKprAlShVL5G6mCD2AJ6mPQKBgQD8Iv9GqYmaeW4NBQYn" +
"jInoDYaHU2VUwYXwuNjqm7IgVgf6VHqJ5aj5EA+gClpzH6HzLvuEEZ5D4XTlpbHa" +
"AN8h3aMo2lryEB8Cv/6uMjMYRFkuuMCVc1XaAsjTxJhO1qwsW4/IkWIoM7uGMD74" +
"5zGvWg12QQuMPV7sVXT0XCrxFwKBgQDTvdjdu3QdIWYUaiRIkF/8e+6+finFZ0Dt" +
"aaTnZ6mDSGaBwGqOSt+woOB61Vkl/EoaLpPGW0mKmhSlAnrD04LmB1LNt16W39RN" +
"5mjVxBdHIkyWUcQAq46kNYvPJ6BGJkZiRW1eOrXfw0fTBQPb3X1Na2cWBzvT4+tw" +
"Am1Sjv/SHwKBgQDkCKLnvZ194CTwEYMncaun+9OXwIz8wqnotMU6KeZH6Ib+mDjb" +
"TqIr36LCE5sKU6mczvka0PRaYCXhLKJVkEQ91L4jzJhEJOBnFE26LhyX7fjakK1c" +
"fRtAORR4sm0toGnHFGhN9W7Y/TC0hB3v7ui4trFGKj3PcBHRnNhRyKntsQKBgGR2" +
"xEnYYixcJ2nyPorrbY+HYeyiQcF2zziWEnb1GVm/5VsU57nhzqaofjnptmWugZ5Q" +
"kS7hK1CG8NqmBYeaeJYZzXDr2wZs5vebJgyfAIhwvrPn0b6bp49EFLTSUVpXWLfR" +
"xyWZZ6fmqNJ3o7ATNBuipQOvpPRRROkdTa+JR9nzAoGBAJV4ejLCkgllaGr7IISK" +
"YgYNicZKqzNtJ7JTxYsH7pylNHC8eo63S+xNv5xCUp85vjHGQXbp+HY3HeEqzkRn" +
"PS7gkR0Q9tpdX03xREkWodj0GchdjwRgSlHK9W30x00pccv0iDlxSrGJUVLTqFlu" +
"fCu0gOJ91NfpFLX9bP1YN29V";
}
@Override
public String getALIPAY_PUBLIC_KEY() {
return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhwIiSpdHHs7XgZyNiSA++/usN6Sg2IKLlEUhfy89yig9GSGyb2p/VW7Ei4/5IuG9hM0yQx9bM28VDMj/KO0Y5VCcOgrVB11UhfdwpLx8JQXB9u9x0gf/q/wovdxBgqtStLuQ98vveID2O/nf+PluWfq/90EgiQs16fi91b7H150fHr3ra8HHTuvCMKGBck3QUURrRp9OdQaa/vPQjuEyVUNUyX9B9HRdn4PkigI/5rrxjVt4r/jvSOR2MhgBo0QKIm4lCxNibumAHN/w+mewjmoTu77X14bn80V1xPjTRfRohyuW1t0pOcPIpiV7FmlQB0T6uzKZ8I3vVg4l0SxfdQIDAQAB";
}
@Override
public String getNOTIFY_URL() {
return "https://www.cloudam.cn/accounts/0xalipaycallback/";
}
@Override
public String getSIGN_TYPE() {
return "RSA2";
}
@Override
public String getCHARSET() {
return "utf-8";
}
@Override
public String getURL() {
return "https://openapi.alipay.com/gateway.do";
}
@Override
public String getReturnUrl(boolean isVpsClient, String by) {
if (StringUtils.isNotEmpty(by)) {
switch (by) {
case "1":
return RETURN_URL_VPS_FRONT; // vps购买
case "2":
return RETURN_URL_CVM; // 云主机购买
}
}
// 费用中心
if (isVpsClient) {
return RETURN_URL_VPS;
} else {
return RETURN_URL_CLOUDAM;
}
}
}
\ No newline at end of file
package com.edgec.browserbackend.common.auth;
public class Securitys {
public static final String SUPPORT_EL = "hasRole('SUPPORT')"; // 需要客户支持权限
public static final String ADMIN_EL = "hasRole('ADMIN')"; // 需要管理员权限
public static final String SERVER_ONLY_EL = "#oauth2.hasScope('server')"; // 仅限后端调用
public static final String ROOT_EL = "hasRole('ROOT')"; // ROOT 用户
}
package com.edgec.browserbackend.common.charge;
// 交易类型
public interface ChargeType {
int newip = 0; // 购买vps, ip
int renew = 1; // 续费ip
int ipkeptfee = 2; // ip保留
int deleteip = 3; // 删除ip
int stopinstanceonly = 4; // 停机
int Startinstanceonly = 5; // 重启
int refundipkeptfee = 6;
int newcvm = 7; // 云主机购买
int renewcvm = 8; // 云主机续费
int intelligroup = 9; //预留
int c3_ip_app = 10; //ip云
int cvmsnapshot = 11; //云主机快照
int modifyinstancespec = 12; //升降配
int c3_ip_duration = 13; //ip云短效包月
int c3_ip_quantity = 14; //ip云短效按量
int c3_ip_fix = 15; //ip云长效
int renew_c3_ip_duration = 16; //ip云短效包月续费
int enew_c3_ip_fix = 17; //ip云长效续费
int resetcvm = 18; //云主机重置系统
}
package com.edgec.browserbackend.common.commons.client;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.CredentialsProvider;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* Elasticsearch Rest Client
* Make sure to config this client before use it
* See example : intelligroup-tasks#com.edgec.intelligroup.config.ElasticsearchClientConfig
*/
public class ElasticsearchClient {
private String hostname;
private int port;
private CredentialsProvider credentialsProvider;
private static final Logger log = LoggerFactory.getLogger(ElasticsearchClient.class);
public void index(String name, String id, String sourceJson) {
if (StringUtils.isEmpty(name) || StringUtils.isEmpty(id) || StringUtils.isEmpty(sourceJson)) {
throw new IllegalArgumentException("Missing params");
}
RestHighLevelClient client = buildRestClient();
try {
IndexRequest indexRequest = new IndexRequest(name).id(id).source(sourceJson, XContentType.JSON);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
if (indexResponse != null && indexResponse.getResult() != null) {
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
log.info("Index created " + indexResponse.getId());
} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
log.info("Index updated " + indexResponse.getId());
}
}
} catch (Exception e) {
log.error("Index request errors ", e);
} finally {
try {
client.close();
} catch (IOException e) {
log.error("Closing client errors ", e);
}
}
}
private RestHighLevelClient buildRestClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost(hostname, port, "http"))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder).setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)));
return client;
}
public ElasticsearchClient(String hostname, int port, CredentialsProvider credentialsProvider) {
log.info("Initialize ElasticsearchClient host {} port {}", hostname, port);
this.hostname = hostname;
this.port = port;
this.credentialsProvider = credentialsProvider;
}
}
package com.edgec.browserbackend.common.commons.core;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name){
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name,Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
package com.edgec.browserbackend.common.commons.domain;
import java.util.List;
public class WeixinMessage {
private String msgType;
private String content;
private List<String> mentionedList;
private String mobileList;
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public List<String> getMentionedList() {
return mentionedList;
}
public void setMentionedList(List<String> mentionedList) {
this.mentionedList = mentionedList;
}
public String getMobileList() {
return mobileList;
}
public void setMobileList(String mobileList) {
this.mobileList = mobileList;
}
}
package com.edgec.browserbackend.common.commons.domain;
public class WeixinRobot {
private String robotId;
private String robotName;
private String webhookAddress;
public String getRobotId() {
return robotId;
}
public void setRobotId(String robotId) {
this.robotId = robotId;
}
public String getRobotName() {
return robotName;
}
public void setRobotName(String robotName) {
this.robotName = robotName;
}
public String getWebhookAddress() {
return webhookAddress;
}
public void setWebhookAddress(String webhookAddress) {
this.webhookAddress = webhookAddress;
}
}
package com.edgec.browserbackend.common.commons.error;
import com.edgec.commons.core.ApplicationContextProvider;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import java.time.LocalDateTime;
import java.util.Locale;
public class ApiError {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private LocalDateTime timestamp;
private String message;
private String debugMessage;
private ErrorCode errorCode;
private Object[] args;
public ApiError(ErrorCode code, Object... args) {
timestamp = LocalDateTime.now();
this.errorCode = code;
this.args = args;
}
public ApiError(ErrorCode errorCode, String message, Object... args) {
this(errorCode);
this.message = message;
this.args = args;
}
public ApiError(ErrorCode errorCode, Throwable ex, Object... args) {
this(errorCode);
this.message = ex.getMessage();
this.debugMessage = ex.getLocalizedMessage();
this.args = args;
}
public ApiError(String message,ErrorCode errorCode, Throwable ex, Object... args) {
this(errorCode);
this.message = message;
this.debugMessage = ex.getLocalizedMessage();
this.args = args;
}
public String getMessage() {
MessageSource messageSource = ApplicationContextProvider.getBean(MessageSource.class);
Locale locale = LocaleContextHolder.getLocale();
try{
return messageSource.getMessage(errorCode.toString(), args, locale);
} catch(NoSuchMessageException e) {
return this.message;
}
}
public String getDebugMessage() {
return debugMessage;
}
public ErrorCode getErrorCode() {
return errorCode;
}
}
package com.edgec.browserbackend.common.commons.error;
public class ClientRequestException extends IllegalArgumentException {
private ErrorCode errorCode;
private Object[] args;
private String additionalInfo;
public ClientRequestException(ErrorCode errorCode) {
this.errorCode = errorCode;
}
public ClientRequestException(ErrorCode errorCode, String s, Object... args) {
super(s);
this.errorCode = errorCode;
}
public ClientRequestException(ErrorCode errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
public ClientRequestException(ErrorCode errorCode, Throwable cause, String additionalInfo) {
super(cause);
this.errorCode = errorCode;
}
public String getAdditionalInfo() {
return additionalInfo;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public Object[] getArgs() {
return this.args;
}
}
package com.edgec.browserbackend.common.commons.error;
import com.fasterxml.jackson.annotation.JsonValue;
public interface ErrorCode {
public static final int COMMON_UNKNOWN = 100000;
public static final int COMMON_SERVER_ERROR = 100001;
public static final int COMMON_OTHERS = 100002;
public static final int COMMON_INVALID_TOKEN = 100003;
public static final int COMMON_UNAUTHRORIZED = 100004;
public static final int ACCOUNT_BASE = 400000;
public static final int AUTH_BASE = 500000;
public static final int INTELLIGROUP_BASE = 600000;
public static final int VPS_BASE = 700000;
public static final int C3_BASE = 800000;
int value() ;
@JsonValue
int getCode() ;
}
package com.edgec.browserbackend.common.commons.error;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import java.time.LocalDateTime;
@JsonSerialize(using = IntelligroupOauthExceptionSerializer.class)
public class IntelligroupOauthException extends OAuth2Exception {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private LocalDateTime timestamp;
private String message;
private String debugMessage;
private int errorCode;
public IntelligroupOauthException(String message, String debugMessage, int errorCode ) {
super(message);
timestamp = LocalDateTime.now();
this.message = message;
this.debugMessage = debugMessage;
this.errorCode = errorCode;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
@Override
public String getMessage() {
return message;
}
public String getDebugMessage() {
return debugMessage;
}
public int getErrorCode() {
return errorCode;
}
}
\ No newline at end of file
package com.edgec.browserbackend.common.commons.error;
import com.edgec.commons.core.ApplicationContextProvider;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class IntelligroupOauthExceptionSerializer extends StdSerializer<IntelligroupOauthException> {
public IntelligroupOauthExceptionSerializer() {
super(IntelligroupOauthException.class);
}
@Override
public void serialize(IntelligroupOauthException value, JsonGenerator gen, SerializerProvider provider) throws IOException {
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
gen.writeStartObject();
gen.writeStringField("timestamp", value.getTimestamp().format(DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm:ss")));
MessageSource messageSource = ApplicationContextProvider.getBean(MessageSource.class);
Locale locale = LocaleContextHolder.getLocale();
String message = value.getMessage();
try {
message = messageSource.getMessage("" + value.getErrorCode(), null, locale);
} catch (NoSuchMessageException e) {
}
gen.writeStringField("message", message);
gen.writeStringField("debugMessage", value.getDebugMessage());
gen.writeStringField("errorCode", "" + value.getErrorCode());
gen.writeEndObject();
}
}
package com.edgec.browserbackend.common.commons.error;
public class InternalServerErrorException extends RuntimeException {
private ErrorCode errorCode;
public InternalServerErrorException(ErrorCode errorCode) {
this.errorCode = errorCode;
}
public InternalServerErrorException(String message, ErrorCode errorCode) {
super(message);
this.errorCode = errorCode;
}
public InternalServerErrorException(String message, Throwable cause, ErrorCode errorCode) {
super(message, cause);
this.errorCode = errorCode;
}
public InternalServerErrorException(Throwable cause, ErrorCode errorCode) {
super(cause);
this.errorCode = errorCode;
}
public InternalServerErrorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace,ErrorCode errorCode) {
super(message, cause, enableSuppression, writableStackTrace);
this.errorCode = errorCode;
}
public ErrorCode getErrorCode() {
return errorCode;
}
}
package com.edgec.browserbackend.common.commons.kafka;
public final class KafkaUtils {
public static final String TOPIC_NAME_C3_MINIONS = "tp.minions.c3";
public static final String CONSUMER_GROUP_C3_MINIONS = "cg.minions.c3";
public static final TopicDef TOPIC_C3_MINIONS = new TopicDef(TOPIC_NAME_C3_MINIONS, 12, 2);
public static class TopicDef {
final public String NAME;
final public int PARTITIONS;
final public int REPLICAS;
public TopicDef(String NAME, int PARTITIONS, int REPLICAS) {
this.NAME = NAME;
this.PARTITIONS = PARTITIONS;
this.REPLICAS = REPLICAS;
}
}
}
package com.edgec.browserbackend.common.commons.utils;
public class CommonStringUtils {
public static int getLongestCommonSubstring(String a, String b) {
int m = a.length();
int n = b.length();
int max = 0;
int[][] dp = new int[m][n];
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(a.charAt(i) == b.charAt(j)){
if(i==0 || j==0){
dp[i][j]=1;
}else{
dp[i][j] = dp[i-1][j-1]+1;
}
if(max < dp[i][j])
max = dp[i][j];
}
}
}
return max;
}
}
package com.edgec.browserbackend.common.commons.utils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;
public class DateConverter {
public static final String DATE_PATTERN = "yyyy-MM-dd";
public static final String DATE_TIME_PATTERN = "yyyy-MM-dd hh:mm:ss";
public static final String DATE_TIME_PATTERN_ALI = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String DATE_TIME_PATTERN_TENCENT = "yyyy-MM-dd HH:mm:ss";
private static final DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(DATE_PATTERN);
private static final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(DATE_TIME_PATTERN);
private static final DateTimeFormatter dateTimeFormatter_ali = DateTimeFormat.forPattern(DATE_TIME_PATTERN_ALI);
private static final DateTimeFormatter dateTimeFormatter_tencent = DateTimeFormat.forPattern(DATE_TIME_PATTERN_TENCENT);
public static Date stringToDate(String date) {
try {
return dateFormatter.parseDateTime(date).toDate();
} catch (Exception e) {
return dateTimeFormatter.parseDateTime(date).toDate();
}
}
public static String dateToString(Date date) {
DateTime dateTime = new DateTime(date);
return dateTimeFormatter.print(dateTime);
}
public static long stringToLongAli(String date) {
try {
return dateTimeFormatter_ali.parseDateTime(date).getMillis();
} catch (Exception e) {
return dateTimeFormatter_ali.parseDateTime(date).getMillis();
}
}
public static long stringToLongTencent(String date) {
try {
return dateTimeFormatter_tencent.parseDateTime(date).getMillis();
} catch (Exception e) {
return dateTimeFormatter_tencent.parseDateTime(date).getMillis();
}
}
}
package com.edgec.browserbackend.common.commons.utils;
import com.alibaba.fastjson.JSONObject;
import com.edgec.commons.core.ApplicationContextProvider;
import com.edgec.commons.domain.WeixinMessage;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class NotifyUtils {
private static final Logger log = LoggerFactory.getLogger(NotifyUtils.class);
private static final CloseableHttpClient httpClient = HttpClients.createDefault();
public enum MsgType {
WEBHOOK("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6bdea516-5321-45b8-bdf4-c666aa35af7c"),
;
String url;
MsgType(String url) {
this.url = url;
}
public String getCode() {
return url;
}
}
private static void sendPost(MsgType msgType, JSONObject param) {
HttpPost httpPost = new HttpPost(msgType.getCode());
StringEntity requestEntity = new StringEntity(String.valueOf(param), "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(requestEntity);
try {
CloseableHttpResponse response = httpClient.execute(httpPost);
response.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
private static void arrangeMessage(MsgType weChatURL, WeixinMessage message) {
JSONObject json = new JSONObject();
json.put("msgtype", "text");
JSONObject text = new JSONObject();
String env = "main";
try {
env = ApplicationContextProvider.getApplicationContext().getEnvironment().getProperty("spring.profiles.active");
} catch (Exception e) {
}
if (!StringUtils.isEmpty(env) && !env.equalsIgnoreCase("prod")) {
return;
}
String envPrefix = "执行环境: " + env + "\n";
text.put("content", envPrefix + message.getContent());
json.put("text", text);
sendPost(weChatURL, json);
}
public static void sendMessage(String content, MsgType weChatURL) {
try {
WeixinMessage message = new WeixinMessage();
message.setContent(content);
arrangeMessage(weChatURL, message);
} catch (Exception e) {
log.error("fail to send wx notify", e);
}
}
public static void sendMessage(String content, Throwable exception, MsgType weChatURL) {
try {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
exception.printStackTrace(printWriter);
WeixinMessage message = new WeixinMessage();
message.setContent(stringWriter.toString());
arrangeMessage(weChatURL, message);
} catch (Exception e) {
log.error("fail to send wx notify", e);
}
}
}
package com.edgec.browserbackend.common.commons.utils;
public final class Pair<S, T> {
private S first;
private T second;
public Pair() {
}
public Pair(S first, T second) {
this.first = first;
this.second = second;
}
public static <S, T> Pair<S, T> of(S first, T second) {
return new Pair<>(first, second);
}
public S getFirst() {
return first;
}
public T getSecond() {
return second;
}
public void setFirst(S first) {
this.first = first;
}
public void setSecond(T second) {
this.second = second;
}
}
package com.edgec.browserbackend.common.commons.utils;
import java.util.Comparator;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class PriorityFutureTask<V>
extends FutureTask<V> implements Comparable<PriorityFutureTask<V>> {
private Object object;
private Comparator comparator;
public PriorityFutureTask(Callable<V> callable, Comparator comparator) {
super(callable);
this.object = callable;
this.comparator = comparator;
}
public PriorityFutureTask(Runnable runnable, V result, Comparator comparator) {
super(runnable, result);
this.object = runnable;
this.comparator = comparator;
}
@Override
public int compareTo(PriorityFutureTask<V> o) {
if (this == o) {
return 0;
}
if (o == null) {
return -1; // high priority
}
if (object != null && o.object != null) {
return this.comparator.compare(this.object, o.object);
}
return 0;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (!(obj instanceof PriorityFutureTask)) {
return false;
} else {
PriorityFutureTask<V> c = (PriorityFutureTask<V>) obj;
return object.equals(c.object);
}
}
@Override
public int hashCode() {
return object.hashCode();
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
package com.edgec.browserbackend.common.commons.utils;
import java.util.Comparator;
import java.util.concurrent.*;
public class PriorityThreadPoolExecutor extends ThreadPoolExecutor {
private Comparator comparator;
public PriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public PriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}
public PriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}
public PriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler, Comparator comparator) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
this.comparator = comparator;
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new PriorityFutureTask(runnable, value, this.comparator);
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new PriorityFutureTask(callable, this.comparator);
}
public static ThreadPoolExecutor of(int poolSize, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler, Comparator comparator) {
return new PriorityThreadPoolExecutor(poolSize, poolSize, 0L, TimeUnit.MILLISECONDS, workQueue, threadFactory, handler, comparator);
}
}
\ No newline at end of file
package com.edgec.browserbackend.common.commons.utils;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SmsUtils {
private static final Logger log = LoggerFactory.getLogger(SmsUtils.class);
private static final IAcsClient iAcsClient;
static {
DefaultProfile profile = DefaultProfile.getProfile("default", "LTAIODPWRh6stFca", "0SBDR59HsquSDEj9CFXNt9njTs2cCv");
iAcsClient = new DefaultAcsClient(profile);
}
public enum SmsTemplateCode {
VPS_INVITE("SMS_171856442"),
VPS_EXPIRE("SMS_173341111"),
CLOUDAM_ARREARS("SMS_174805285"),
CVM_EXPIRE("SMS_175572297"),
;
String code;
SmsTemplateCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
public static void notifyNewUserRegistered(String username, String phone, String vps) {
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("PhoneNumbers", "13851961528");
request.putQueryParameter("SignName", "微艾");
request.putQueryParameter("TemplateCode", "SMS_170842632");
request.putQueryParameter("TemplateParam", "{"+"\"name\":\""+username+"\"," +
"\"number\":\""+phone+"\"," +
"\"vps\":\""+vps+"\""+
"}");
try {
CommonResponse response = iAcsClient.getCommonResponse(request);
System.out.println(response);
} catch (ClientException e) {
log.error("Sms sends failure",e);
}
}
// public static void sendSmsOpMsg(String username, String groupName, String error) {
// String randomCode = "";
// CommonRequest request = new CommonRequest();
// //request.setProtocol(ProtocolType.HTTPS);
// request.setMethod(MethodType.POST);
// request.setDomain("dysmsapi.aliyuncs.com");
// request.setVersion("2017-05-25");
// request.setAction("SendSms");
// request.putQueryParameter("PhoneNumbers", "13851961528");
// request.putQueryParameter("SignName", "微艾");
// request.putQueryParameter("TemplateCode", "SMS_166665358");
// request.putQueryParameter("TemplateParam", "{"+"\"name\":\""+username+"\"," +
// "\"group\":\""+groupName+"\"," +
// "\"error\":\""+error+"\""+
// "}");
// try {
// CommonResponse response = iAcsClient.getCommonResponse(request);
// System.out.println(response);
// } catch (ClientException e) {
// log.error("Sms sends failure",e);
// }
// }
public static void sendVpsSms(String phoneNum, SmsTemplateCode smsTemplateCode, JSONObject param) {
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("PhoneNumbers", phoneNum);
request.putQueryParameter("SignName", "防关联VPS");
request.putQueryParameter("TemplateCode", smsTemplateCode.getCode());
request.putQueryParameter("TemplateParam", param.toJSONString());
try {
CommonResponse response = iAcsClient.getCommonResponse(request);
if (response.getHttpStatus() == 200 && response.getData().contains("OK")) {
return;
} else {
log.error("Send SMS Error,{}, {}, {}, {}", phoneNum, smsTemplateCode, param, response.getData());
}
} catch (Exception e) {
log.error("Send SMS Error,{}, {}, {}", phoneNum, smsTemplateCode, param);
}
}
public static void sendCloadamSms(String phoneNum, SmsTemplateCode smsTemplateCode, JSONObject param) {
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("PhoneNumbers", phoneNum);
request.putQueryParameter("SignName", "深圳云端CLOUDAM");
request.putQueryParameter("TemplateCode", smsTemplateCode.getCode());
request.putQueryParameter("TemplateParam", param.toJSONString());
try {
CommonResponse response = iAcsClient.getCommonResponse(request);
if (response.getHttpStatus() == 200 && response.getData().contains("OK")) {
return;
} else {
log.error("Send SMS Error,{}, {}, {}, {}", phoneNum, smsTemplateCode, param, response.getData());
}
} catch (Exception e) {
log.error("Send SMS Error,{}, {}, {}", phoneNum, smsTemplateCode, param);
}
}
}
package com.edgec.browserbackend.common.commons.utils;
import java.util.UUID;
public class UUIDGenerator {
public static String gen(Boolean withoutDashes) {
return withoutDashes ? UUID.randomUUID().toString().replace("-", "")
: UUID.randomUUID().toString();
}
}
package com.edgec.browserbackend.common.commons.utils;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
public class UniquePriorityBlockingQueue<E> extends PriorityBlockingQueue<E> {
public UniquePriorityBlockingQueue(int initialCapacity) {
super(initialCapacity);
}
@Override
public boolean add(E e) {
if (super.contains(e))
return true;
return super.add(e);
}
@Override
public boolean offer(E e) {
if (super.contains(e))
return true;
return super.offer(e);
}
@Override
public void put(E e) {
if (super.contains(e))
return;
super.put(e);
}
@Override
public boolean offer(E e, long timeout, TimeUnit unit) {
if (super.contains(e))
return true;
return super.offer(e, timeout, unit);
}
}
package com.edgec.browserbackend.common.constant;
public interface InstanceStatus {
String STOPPING = "Stopping";
String PENDING = "Pending";
String STOPPED = "Stopped";
String RUNNING = "RUNNING";
}
package com.edgec.browserbackend.common.constant;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Set;
public class SpecialUsers {
public static final Set<String> CLOUDAM_USERS = new HashSet<>();
public static final String VPS_CLOUD_ACCOUNT_NAME = "vpsclient";
public static final String CVM_CLOUD_ACCOUNT_NAME = "cvmclient";
public static final String C3_ECC_ACCOUNT_NAME = "eccclient"; // 电商云集群
public static final String C3_IP_ACCOUNT_NAME = "c3ipclient"; //c3 ip云
public static final String SUPERBROWSER = "superbrowser";
public static final String ECOMMERCEBROWSER = "ecommercebrowser";
public static final String JKBROWSER = "jkbrowser";
//新增用户名写在上边
public static void main(String[] args) {
for (String cloudamUser : CLOUDAM_USERS) {
System.out.println(cloudamUser);
}
}
static {
Field[] fields = SpecialUsers.class.getFields();
for (Field field : fields) {
Class clazz = field.getType();
if (!clazz.equals(String.class)) {
continue;
}
if (Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
try {
String cloudamUserName = (String) field.get(SpecialUsers.class);
CLOUDAM_USERS.add(cloudamUserName);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
package com.edgec.browserbackend.common.dto;
public class BaseResponse<T> {
private String requestId;
private Result result = Result.SUCCESS;
private String message;
private T data;
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
package com.edgec.browserbackend.common.dto;
public enum Result {
SUCCESS,
FAIL
}
package com.edgec.browserbackend.config;
import com.edgec.browserbackend.service.auth.security.MongoUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
/**
* @author cdov
*/
@Configuration
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
private final String NOOP_PASSWORD_ENCODE = "{noop}";
private TokenStore tokenStore = new InMemoryTokenStore();
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private MongoUserDetailsService userDetailsService;
@Autowired
private Environment env;
@Autowired
private OAuthResponseExceptionTranslator oAuthResponseExceptionTranslator;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// TODO persist clients details
// @formatter:off
clients.inMemory()
.withClient("browser")
.authorizedGrantTypes("refresh_token", "password")
.scopes("ui")
.and()
.withClient("account-service")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("intelligroup-service")
.secret(env.getProperty("INTELLIGROUP_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("intelligroup-vps")
.secret(env.getProperty("INTELLIGROUP_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("c3-app")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("c3-ecc-app")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("c3-ip-app")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server");
// @formatter:on
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService).exceptionTranslator(oAuthResponseExceptionTranslator);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
}
package com.edgec.browserbackend.config;
import com.edgec.browserbackend.error.AuthErrorCode;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.error.IntelligroupOauthException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import java.io.IOException;
@Component("oAuthResponseExceptionTranslator")
public class OAuthResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e, AuthErrorCode error) throws IOException {
IntelligroupOauthException ex = new IntelligroupOauthException(error.getReason(), error.getReason(), error.getCode());
int status = e.getHttpErrorCode();
HttpHeaders headers = new HttpHeaders();
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
}
ResponseEntity<OAuth2Exception> response = new ResponseEntity<OAuth2Exception>(ex, headers,
HttpStatus.valueOf(status));
return response;
}
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
// Try to extract a SpringSecurityException from the stacktrace
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
Exception ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
causeChain);
if (ase != null) {
AuthErrorCode code = AuthErrorCode.AUTHENTICATION_ERROR;
return handleOAuth2Exception((OAuth2Exception) ase, code);
}
ase = (AccessDeniedException) throwableAnalyzer
.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
if (ase instanceof AccessDeniedException) {
AuthErrorCode code = AuthErrorCode.AUTHORIZATION_ERROR;
return handleOAuth2Exception((OAuth2Exception) ase, code);
}
ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer
.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
if (ase instanceof HttpRequestMethodNotSupportedException) {
AuthErrorCode code = AuthErrorCode.OTHERS;
return handleOAuth2Exception((OAuth2Exception) ase, code);
}
ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(
OAuth2Exception.class, causeChain);
if (ase != null) {
AuthErrorCode code = AuthErrorCode.AUTHENTICATION_ERROR;
return handleOAuth2Exception((OAuth2Exception) ase, code);
}
ase = (ClientRequestException) throwableAnalyzer.getFirstThrowableOfType(
ClientRequestException.class, causeChain);
if (ase != null) {
ClientRequestException clientRequestException = (ClientRequestException) ase;
OAuth2Exception exception = OAuth2Exception.create(OAuth2Exception.UNAUTHORIZED_CLIENT, "xxxx");
return handleOAuth2Exception(exception, (AuthErrorCode) clientRequestException.getErrorCode());
}
AuthErrorCode code = AuthErrorCode.INTERNALSERVERERROR;
return handleOAuth2Exception((OAuth2Exception) ase, code);
}
}
package com.edgec.browserbackend.config;
import com.edgec.browserbackend.service.auth.security.MongoUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @author cdov
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MongoUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().authenticated()
.and()
.csrf().disable();
}
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/users/verify/**", "/users/changepass");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
\ No newline at end of file
package com.edgec.browserbackend.controller.account;
import com.edgec.browserbackend.exception.AccountErrorCode;
import com.edgec.browserbackend.common.commons.error.ApiError;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.error.InternalServerErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute("javax.servlet.error.exception", ex, 0);
}
ApiError error = new ApiError(AccountErrorCode.OTHERS, "http request error");
return new ResponseEntity(error, headers, status);
}
private ResponseEntity<Object> buildResponseEntity(ApiError apiError, HttpStatus status) {
return new ResponseEntity<>(apiError, status);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Object> processValidationError(IllegalArgumentException e) {
log.debug("Returning HTTP 400 Bad Request", e);
ApiError apiError = new ApiError(AccountErrorCode.UNKNOWN, e);
return buildResponseEntity(apiError, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ClientRequestException.class)
public ResponseEntity<Object> processValidationError(ClientRequestException e) {
log.debug("Returning HTTP 400 Client Request Eror", e);
ApiError apiError = new ApiError(e.getErrorCode(), e, e.getArgs());
return buildResponseEntity(apiError, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(InternalServerErrorException.class)
public ResponseEntity<Object> processValidationError(InternalServerErrorException e) {
log.info("Returning HTTP 500 Internal Server Error", e);
ApiError apiError = new ApiError(e.getErrorCode());
return buildResponseEntity(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ApiError apiError = new ApiError(AccountErrorCode.UNKNOWN, "Validation failed, wrong request data.");
return buildResponseEntity(apiError, HttpStatus.BAD_REQUEST);
}
}
package com.edgec.browserbackend.controller.account;
import com.edgec.browserbackend.exception.AccountErrorCode;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import org.apache.commons.lang3.StringUtils;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;
public class LimitedUsers {
private static List<String> getLimitedUsers() {
return Arrays.asList("cloudam");
}
public static void filterIfLimitedUser(Principal principal) {
if (principal != null && !StringUtils.isEmpty(principal.getName())) {
if (getLimitedUsers().contains(principal.getName())) {
throw new ClientRequestException(AccountErrorCode.UNAUTHORIZED, "Not allowed");
}
}
}
}
package com.edgec.browserbackend.controller.auth;
import com.edgec.browserbackend.error.AuthErrorCode;
import com.edgec.browserbackend.common.commons.error.ApiError;
import com.edgec.browserbackend.common.commons.error.ClientRequestException;
import com.edgec.browserbackend.common.commons.error.InternalServerErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
private final Logger log = LoggerFactory.getLogger(getClass());
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute("javax.servlet.error.exception", ex, 0);
}
ApiError error = new ApiError(AuthErrorCode.OTHERS, "http request error");
return new ResponseEntity(error, headers, status);
}
private ResponseEntity<Object> buildResponseEntity(ApiError apiError, HttpStatus status) {
return new ResponseEntity<>(apiError, status);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Object> processValidationError(IllegalArgumentException e) {
log.debug("Returning HTTP 400 Bad Request", e);
ApiError apiError = new ApiError(AuthErrorCode.OTHERS, e);
return buildResponseEntity(apiError, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ClientRequestException.class)
public ResponseEntity<Object> processValidationError(ClientRequestException e) {
log.debug("Returning HTTP 400 Client Request Eror", e);
ApiError apiError = new ApiError(e.getErrorCode(), e);
return buildResponseEntity(apiError, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(InternalServerErrorException.class)
public ResponseEntity<Object> processValidationError(InternalServerErrorException e) {
log.info("Returning HTTP 500 Internal Server Error", e);
ApiError apiError = new ApiError(e.getErrorCode());
return buildResponseEntity(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ApiError apiError = new ApiError(AuthErrorCode.OTHERS, "Validation Failed");
return buildResponseEntity(apiError, HttpStatus.BAD_REQUEST);
}
}
package com.edgec.browserbackend.controller.auth;
import com.edgec.browserbackend.domain.auth.User;
import com.edgec.browserbackend.domain.auth.UserPasswordReset;
import com.edgec.browserbackend.service.auth.UserAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserAuthService userAuthService;
@Autowired
@Qualifier("consumerTokenServices")
ConsumerTokenServices consumerTokenServices;
@RequestMapping(method = RequestMethod.DELETE, value = "/token")
@ResponseBody
public void revokeToken(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
if (authorization != null && authorization.contains("Bearer")){
String tokenId = authorization.substring("Bearer".length()+1);
consumerTokenServices.revokeToken(tokenId);
}
}
@RequestMapping(value = "/current", method = RequestMethod.GET)
public Principal getUser(Principal principal) {
return principal;
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(path = "/{name}/roles/{roles}", method = RequestMethod.PUT)
public void updateRoles(@PathVariable String name, @PathVariable String roles) {
userAuthService.updateRoles(name, roles);
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(path = "/{name}/addroles/{roles}", method = RequestMethod.PUT)
public void addRoles(@PathVariable String name, @PathVariable String roles) {
userAuthService.addRoles(name, roles);
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(method = RequestMethod.POST)
public void createUser(@Valid @RequestBody User user) {
userAuthService.create(user);
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(value = "/resetpasswd", method = RequestMethod.POST)
public void resetUserPassword(@Valid @RequestBody User user) {
userAuthService.resetUserPassword(user);
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(path = "/current/{name}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable String name) {
userAuthService.deleteUser(name);
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(method = RequestMethod.PUT)
public void resetUser(@Valid @RequestBody User user) {
userAuthService.reset(user);
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(path = "/{lockOrUnlock}",method = RequestMethod.PUT)
public void lockOrUnlockUser(@Valid @RequestBody User user, @PathVariable String lockOrUnlock) {//@RequestParam("by") String by,
if("lock".equals(lockOrUnlock)){
userAuthService.lock(user,lockOrUnlock);
}
else if("unlock".equals(lockOrUnlock)){
userAuthService.unlock(user,lockOrUnlock);
}
}
@RequestMapping(path = "/{name}", method = RequestMethod.GET)
public boolean lockState(@PathVariable String name) {
return userAuthService.lockState(name);
}
@RequestMapping(path = "/verify/{name}/{code}", method = RequestMethod.PUT)
public void verifyCode(@PathVariable String name, @PathVariable String code) {
userAuthService.verifyCode(name, code);
}
@RequestMapping(path = "/changepass", method = RequestMethod.PUT)
public void changePassword(@Valid @RequestBody UserPasswordReset userPasswordReset) {
userAuthService.changePassword(userPasswordReset);
}
@PreAuthorize("#oauth2.hasScope('server')")
@RequestMapping(path = "/updateuser",method = RequestMethod.PUT)
public void updateUser(@Valid @RequestBody User user, @RequestParam String username) {//@RequestParam("by") String by,
userAuthService.updateUser(username, user);
}
}
package com.edgec.browserbackend.domain.account;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.validator.constraints.Length;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Document(collection = "accounts")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Account {
@Id
private String name;
private String parent;
private Date lastSeen;
private Date signupDate = new Date();
private String email;
private String companyName;
private String jobTitle;
private String phoneNumber;
private String country;
private String province;
private String agencyID;
private String lockReason;
private int iprate;
private boolean isPrePaid = true;
private boolean isVpsUser = false;
private String token;
/**
是否具有参与免费试用两小时云主机资格
*/
private Boolean isQualified=true;
public Boolean isQualified() {
return isQualified;
}
public void setQualified(Boolean qualified) {
isQualified = qualified;
}
public boolean isVpsUser() {
return isVpsUser;
}
public void setVpsUser(boolean vpsUser) {
isVpsUser = vpsUser;
}
public int getIprate() {
return iprate;
}
public void setIprate(int iprate) {
this.iprate = iprate;
}
public String getAgencyID(){
return agencyID;
}
public void setAgencyID(String agencyID){
this.agencyID = agencyID;
}
private boolean allowedToCreateSubUser = false;
private boolean allowedToCreateCloudAccount = false;
private List<UserService> userServices = new ArrayList<>();
public List<UserService> getUserServices() {
return userServices;
}
public void addUserService(UserService service) {
this.userServices.add(service);
}
public void setUserServices(List<UserService> userServices) {
this.userServices = userServices;
}
public Date getSignupDate() {
return signupDate;
}
public void setSignupDate(Date signupDate) {
this.signupDate = signupDate;
}
public boolean isPrePaid() {
return isPrePaid;
}
public void setPrePaid(boolean prePaid) {
isPrePaid = prePaid;
}
public boolean isAllowedToCreateCloudAccount() {
return allowedToCreateCloudAccount;
}
public void setAllowedToCreateCloudAccount(boolean allowedToCreateCloudAccount) {
this.allowedToCreateCloudAccount = allowedToCreateCloudAccount;
}
public Account() {
}
public Account(AccountDto account) {
this.setName(account.getName());
this.setAllowedToCreateSubUser(account.isAllowedToCreateSubUser());
this.setAllowedToCreateCloudAccount(account.isAllowedToCreateCloudAccount());
this.setCompanyName(account.getCompanyName());
this.setCountry(account.getCountry());
this.setEmail(account.getEmail());
this.setJobTitle(account.getJobTitle());
this.setPhoneNumber(account.getPhoneNumber());
this.setProvince(account.getProvince());
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
@Length(min = 0, max = 20000)
private String note;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastSeen() {
return lastSeen;
}
public void setLastSeen(Date lastSeen) {
this.lastSeen = lastSeen;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public boolean isAllowedToCreateSubUser() {
return allowedToCreateSubUser;
}
public void setAllowedToCreateSubUser(boolean allowedToCreateSubUser) {
this.allowedToCreateSubUser = allowedToCreateSubUser;
}
public String getLockReason() {
return lockReason;
}
public void setLockReason(String lockReason) {
this.lockReason = lockReason;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
package com.edgec.browserbackend.domain.account;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class AccountDto {
private String name;
private String password;
private List<AccountDto> child;
private Date lastSeen;
private String email;
private String fullname;
private String companyName;
private String jobTitle;
private String phoneNumber;
private String country;
private String province;
private boolean allowedToCreateSubUser;
private boolean allowedToCreateCloudAccount;
private List<CloudAccountDto> cloudAccounts;
private int balance;
private boolean isPrePaid = true;
private boolean isVpsUser = false;
private String parent;
private String realName;
private String idCard;
private String token;
public AccountDto(){
}
public AccountDto(Account account) {
this.setName(account.getName());
this.setAllowedToCreateSubUser(account.isAllowedToCreateSubUser());
this.setAllowedToCreateCloudAccount(account.isAllowedToCreateCloudAccount());
this.setCompanyName(account.getCompanyName());
this.setCountry(account.getCountry());
this.setEmail(account.getEmail());
this.setFullname(account.getFullname());
this.setJobTitle(account.getJobTitle());
this.setPhoneNumber(account.getPhoneNumber());
this.setProvince(account.getProvince());
this.setUserServices(account.getUserServices());
this.setParent(account.getParent());
this.setRealName(account.getRealName());
this.setIdCard(account.getIdCard());
this.setToken(account.getToken());
}
public boolean isVpsUser() {
return isVpsUser;
}
public void setVpsUser(boolean vpsUser) {
isVpsUser = vpsUser;
}
public boolean isPrePaid() {
return isPrePaid;
}
public void setPrePaid(boolean prePaid) {
isPrePaid = prePaid;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
private List<UserService> userServices = new ArrayList<>();
public List<UserService> getUserServices() {
return userServices;
}
public void setUserServices(List<UserService> userServices) {
this.userServices = userServices;
}
public List<CloudAccountDto> getCloudAccounts() {
return cloudAccounts;
}
public void setCloudAccounts(List<CloudAccountDto> cloudAccounts) {
this.cloudAccounts = cloudAccounts;
}
public boolean isAllowedToCreateCloudAccount() {
return allowedToCreateCloudAccount;
}
public void setAllowedToCreateCloudAccount(boolean allowedToCreateCloudAccount) {
this.allowedToCreateCloudAccount = allowedToCreateCloudAccount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<AccountDto> getChild() {
return child;
}
public void setChild(List<AccountDto> child) {
this.child = child;
}
public Date getLastSeen() {
return lastSeen;
}
public void setLastSeen(Date lastSeen) {
this.lastSeen = lastSeen;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public boolean isAllowedToCreateSubUser() {
return allowedToCreateSubUser;
}
public void setAllowedToCreateSubUser(boolean allowedToCreateSubUser) {
this.allowedToCreateSubUser = allowedToCreateSubUser;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
package com.edgec.browserbackend.domain.account;
public enum AccountServerUsingStatus {
USING,
STOP,
TRAIVAL,
}
package com.edgec.browserbackend.domain.account;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "administrator")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Administrator {
@Id
private String name;
private String role; //List<Map<String,Boolean>>
@Transient
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPassword() { return password; }
public void setPassword(String password) {
this.password = password;
}
}
package com.edgec.browserbackend.domain.account;
public enum BillStatus {
NOTCREATED,
PARENTSHALLPAY,
UNPAID,
PAID,
TRAIVAL
}
package com.edgec.browserbackend.domain.account;
public class CloudAccountDto {
private String id;
private String accountName;
private String provider;
private String owner;
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
}
package com.edgec.browserbackend.domain.account;
import com.edgec.browserbackend.service.account.SmsUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
/**
* @Desc
* @Author jason
* @CreateTime 2020/2/11 5:20 下午
**/
@Document(collection = "clouduserorder")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CloudUserOrder {
@Id
private String id;
private String tradeNo = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ SmsUtils.createRandom(true, 4);
private String username;
private String orderTimeStamp;
private Services service;
//0 -- newip, 1 --renew, 2 --ipkeptfee, 3 --deleteip, 4 -- stopinstanceonly , 5 -- bindinstance, 6 -- refundipkeptfee
//7 -- newcvm , 8 -- renewcvm , 9 -- intelligroup, 10 -- resetcvm, 11 -- modifycvmspec
private int chargeType;
private OrderStatus status;
private float rate;
private HashMap<String, String> details;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getOrderTimeStamp() {
return orderTimeStamp;
}
public void setOrderTimeStamp(String orderTimeStamp) {
this.orderTimeStamp = orderTimeStamp;
}
public Services getService() {
return service;
}
public void setService(Services service) {
this.service = service;
}
public int getChargeType() {
return chargeType;
}
public void setChargeType(int chargeType) {
this.chargeType = chargeType;
}
public float getRate() {
return rate;
}
public void setRate(float rate) {
this.rate = rate;
}
public OrderStatus getStatus() {
return status;
}
public void setStatus(OrderStatus status) {
this.status = status;
}
public String getTradeNo() {
return tradeNo;
}
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
public HashMap<String, String> getDetails() {
return details;
}
public void setDetails(HashMap<String, String> details) {
this.details = details;
}
public enum OrderStatus {
UNPAID,
PAYING,
PAID,
FAILURE,
EXPIRED;
}
}
package com.edgec.browserbackend.domain.account;
public class CompanyEarningsDto {
private String username;
private double userBillAmount;
private BillStatus payStatus;
private float totalBillingCost = -1; //用户应支付的钱,产生收益
private String agencyname;
private double ratio;
private double agencyEarnings;
private EarningsStatus agencyEarningStatus;
private double companyShouldEarning;//公司本应收益
private double companyActualEarning;//公司实际到账:用户未支付不到账,代理未提现不扣除
public EarningsStatus getAgencyEarningStatus() {
return agencyEarningStatus;
}
public void setAgencyEarningStatus(EarningsStatus agencyEarningStatus) {
this.agencyEarningStatus = agencyEarningStatus;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public double getUserBillAmount() {
return userBillAmount;
}
public void setUserBillAmount(double userBillAmount) {
this.userBillAmount = userBillAmount;
}
public BillStatus getPayStatus() {
return payStatus;
}
public void setPayStatus(BillStatus payStatus) {
this.payStatus = payStatus;
}
public float getTotalBillingCost() {
return totalBillingCost;
}
public void setTotalBillingCost(float totalBillingCost) {
this.totalBillingCost = totalBillingCost;
}
public String getAgencyname() {
return agencyname;
}
public void setAgencyname(String agencyname) {
this.agencyname = agencyname;
}
public double getRatio() {
return ratio;
}
public void setRatio(double ratio) {
this.ratio = ratio;
}
public double getAgencyEarnings() {
return agencyEarnings;
}
public void setAgencyEarnings(double agencyEarnings) {
this.agencyEarnings = agencyEarnings;
}
public double getCompanyShouldEarning() {
return companyShouldEarning;
}
public void setCompanyShouldEarning(double companyShouldEarning) {
this.companyShouldEarning = companyShouldEarning;
}
public double getCompanyActualEarning() {
return companyActualEarning;
}
public void setCompanyActualEarning(double companyActualEarning) {
this.companyActualEarning = companyActualEarning;
}
}
package com.edgec.browserbackend.domain.account;
import org.springframework.data.mongodb.core.mapping.Document;
@Document( collection = "companymonthreport")
public class CompanyMonthReport {
private int year;
private int month; //几月的订单
private int prepaidBillingCount; //订单的总数
private float prepaidBillingAmount; //订单的金额统计
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getPrepaidBillingCount() {
return prepaidBillingCount;
}
public void setPrepaidBillingCount(int prepaidBillingCount) {
this.prepaidBillingCount = prepaidBillingCount;
}
public float getPrepaidBillingAmount() {
return prepaidBillingAmount;
}
public void setPrepaidBillingAmount(float prepaidBillingAmount) {
this.prepaidBillingAmount = prepaidBillingAmount;
}
}
package com.edgec.browserbackend.domain.account;
public class ContactUs {
private String name;
private String email;
private String phone;
private String company;
private String title;
private String detail;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
package com.edgec.browserbackend.domain.account;
public enum Currency {
USD, EUR, RUB;
public static Currency getDefault() {
return USD;
}
}
package com.edgec.browserbackend.domain.account;
public class DeductionRecord {
private float deductionAmount;
private long deductionTime;
public float getDeductionAmount() {
return deductionAmount;
}
public void setDeductionAmount(float deductionAmount) {
this.deductionAmount = deductionAmount;
}
public long getDeductionTime() {
return deductionTime;
}
public void setDeductionTime(long deductionTime) {
this.deductionTime = deductionTime;
}
}
package com.edgec.browserbackend.domain.account;
public enum EarningsStatus {
WITHDRAWN,
NOWITHDRAWN
}
package com.edgec.browserbackend.domain.account;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.Date;
@Document(collection = "invoice")
public class Invoice {
private String id;
private String username;
private Date date = new Date();
private String invoiceTitle;
private String companyTaxNumber;
private String name;
private float amount;
private InvoiceType invoiceType;
private String phone;
private String expressInformation;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getInvoiceTitle() {
return invoiceTitle;
}
public void setInvoiceTitle(String invoiceTitle) {
this.invoiceTitle = invoiceTitle;
}
public String getCompanyTaxNumber() {
return companyTaxNumber;
}
public void setCompanyTaxNumber(String companyTaxNumber) {
this.companyTaxNumber = companyTaxNumber;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public InvoiceType getInvoiceType() {
return invoiceType;
}
public void setInvoiceType(InvoiceType invoiceType) {
this.invoiceType = invoiceType;
}
public String getExpressInformation() {
return expressInformation;
}
public void setExpressInformation(String expressInformation) {
this.expressInformation = expressInformation;
}
}
package com.edgec.browserbackend.domain.account;
public enum InvoiceType {
GENERAL,
VAT,
}
package com.edgec.browserbackend.domain.account;
public class IpChargeRequestDto {
private int period;
private int amount;
private String region;
private String unit="month";
private String target;
//0 -- newip, 1 --renew, 2 --ipkeptfee, 3 --deleteip, 4 -- stopinstanceonly , 5 -- bindinstance, 6 -- refundipkeptfee
private int chargeType = 0;
private float daysPerMonth = 0;
private String tradeNo;
private String services;
public String getServices() {
return services;
}
public void setServices(String services) {
this.services = services;
}
public String getTradeNo() {
return tradeNo;
}
public void setTradeNo(String tradeNo) {
this.tradeNo = tradeNo;
}
public float getDaysPerMonth() {
return daysPerMonth;
}
public void setDaysPerMonth(float daysPerMonth) {
this.daysPerMonth = daysPerMonth;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public int getChargeType() {
return chargeType;
}
public void setChargeType(int chargeType) {
this.chargeType = chargeType;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
package com.edgec.browserbackend.domain.account;
public class IpChargeResultDto {
private boolean success;
private int balance;
private int approvedAmount;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getApprovedAmount() {
return approvedAmount;
}
public void setApprovedAmount(int approvedAmount) {
this.approvedAmount = approvedAmount;
}
}
package com.edgec.browserbackend.domain.account;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "phoneotp")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Otp {
@Id
private String phone;
private String otp;
private long createdAt;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getOtp() {
return otp;
}
public void setOtp(String otp) {
this.otp = otp;
}
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
}
package com.edgec.browserbackend.domain.account;
public enum PaymentMethod {
WECHAT,
ALIPAY,
BANK,
}
package com.edgec.browserbackend.domain.account;
public enum ServiceType {
TRIAL,
FORMAL,
LOCKED,
}
package com.edgec.browserbackend.domain.account;
public enum Services {
INTELLIGROUP,
CVM,
ECC,
IPC,
VPS,
C3IP
}
package com.edgec.browserbackend.domain.account;
public enum TimePeriod {
YEAR, QUARTER, MONTH, DAY, HOUR
}
This diff is collapsed.
This diff is collapsed.
package com.edgec.browserbackend.domain.browser;
public class Group {
}
package com.edgec.browserbackend.domain.browser;
public class IpResource {
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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