Commit 728edf62 728edf62e8085afbb977580ec6f8ae4e9d5da610 by lWoHvYe

完成自动关联应用、自动关联服务包、自动上线功能

0 parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
logs/*
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.topdraw.platform</groupId>
<artifactId>cms-scheduler</artifactId>
<version>1.0</version>
<name>cms-scheduler</name>
<description>cms系统部分定时任务</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.2</version>
</dependency>
</dependencies>
<profiles>
<!-- 本地开发环境 -->
<profile>
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<!-- 默认的,不加参数时执行这个profile -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 生产环境 -->
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
<modifier>-prod</modifier>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/main/resources/config</directory>
<includes>
<include>application.yml</include>
<include>application-${profiles.active}.yml</include>
</includes>
</resource>
</resources>
<outputDirectory>${project.build.directory}/config</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- jar包内剔除所有配置文件 -->
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<!--不打入jar包的文件类型或者路径-->
<excludes>
<exclude>config/**</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
#!/bin/bash
echo Stopping application
source ./shutdown.sh
# sleep 2
echo Starting application
source ./start.sh
#!/bin/bash
echo "stop SpringBoot BAppApiServerApplication"
pid=`ps -ef | grep cms-scheduler-1.0.jar | grep -v grep | awk '{print $2}'`
echo "旧应用进程id:" $pid
if [ -n "$pid" ]
then
kill -9 $pid
fi
#!/bin/bash
export JAVA_HOME=/x/app/jdk1.8.0_77
echo ${JAVA_HOME}
echo "授权当前用户"
chmod 777 ./*.jar
echo "执行...."
# cd x/app/ams/
nohup ${JAVA_HOME}/bin/java -Xms100m -Xmx500m -jar cms-scheduler-1.0.jar --spring.profiles.active=prod >log.info &
echo "启动成功"
package com.topdraw.platform;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class CmsSchedulerApplication {
public static void main(String[] args) {
SpringApplication.run(CmsSchedulerApplication.class, args);
}
}
package com.topdraw.platform.executor;
import cn.hutool.core.util.StrUtil;
import com.topdraw.platform.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@Slf4j
public class AutoBindAppProcessor {
@Autowired
DbUtil dbUtil;
@Value("${entity.appId}")
private Long APP_ID;
@Transactional(rollbackFor = Exception.class)
public void execute() {
Connection connection = null;
try {
connection = dbUtil.getConnection();
// 查询未绑定
String sql = StrUtil.format(" select xm.id,xm.name from x_media xm LEFT JOIN x_media__app xma on xm.id = xma.media_id and xma.app_id = {} where xma.id is null limit 100 ", APP_ID);
List<Map<String, Object>> list = dbUtil.queryList(connection, sql);
// 开启事务
dbUtil.beginTransaction(connection);
for (Map<String, Object> map : list) {
var mediaId = (Long) map.get("id");
var mapData = new HashMap<String, Object>();
mapData.put("media_id", mediaId);
mapData.put("app_id", APP_ID);
String objectName = "x_media__app";
// 添加关联关系
dbUtil.save(connection, mapData, objectName);
}
// 提交事务
dbUtil.commitTransaction(connection);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
dbUtil.close(connection);
}
}
}
package com.topdraw.platform.executor;
import cn.hutool.core.util.StrUtil;
import com.topdraw.platform.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@Slf4j
public class AutoBindServiceProcessor {
@Autowired
DbUtil dbUtil;
@Value("${entity.serviceId}")
private Long SERVICE_ID;
@Transactional(rollbackFor = Exception.class)
public void execute() {
Connection connection = null;
try {
connection = dbUtil.getConnection();
// 查询未绑定
String sql = StrUtil.format(" select xm.id,xm.name from x_media xm LEFT JOIN x_service__media xsm on xm.id = xsm.media_id and xsm.service_id = {} where xsm.id is null limit 100 ", SERVICE_ID);
List<Map<String, Object>> list = dbUtil.queryList(connection, sql);
// 开启事务
dbUtil.beginTransaction(connection);
for (Map<String, Object> map : list) {
var mediaId = (Long) map.get("id");
var mapData = new HashMap<String, Object>();
mapData.put("media_id", mediaId);
mapData.put("service_id", SERVICE_ID);
String objectName = "x_service__media";
// 添加关联关系
dbUtil.save(connection, mapData, objectName);
}
// 提交事务
dbUtil.commitTransaction(connection);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
dbUtil.close(connection);
}
}
}
package com.topdraw.platform.executor;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.topdraw.platform.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Connection;
@Component
@Slf4j
public class AutoOnlineProcessor {
@Autowired
DbUtil dbUtil;
@Transactional(rollbackFor = Exception.class)
public void execute() {
Connection connection = null;
String today = DateUtil.today();
try {
connection = dbUtil.getConnection();
// 查询未绑定
String sql = " update `x_media` set `status` = '001' where `status` = '000' and file_status = '001' and create_time >= ? ";
dbUtil.doExecute(connection, sql, today);
// 提交事务
dbUtil.commitTransaction(connection);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
dbUtil.close(connection);
}
}
}
package com.topdraw.platform.scheduler;
import com.topdraw.platform.executor.AutoBindAppProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@ConditionalOnProperty(prefix = "scheduler", name = "auto-bind.app-enabled", havingValue = "true")
public class AutoBindAppScheduler {
@Autowired
private AutoBindAppProcessor autoBindAppProcessor;
@Scheduled(cron = "${cron.auto-bind.app}")
public void execute() {
log.info("schedule [自动绑定应用] start >>>>>>>>>>");
autoBindAppProcessor.execute();
log.info("schedule [自动绑定应用] end <<<<<<<<<<");
}
}
package com.topdraw.platform.scheduler;
import com.topdraw.platform.executor.AutoBindServiceProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@ConditionalOnProperty(prefix = "scheduler", name = "auto-bind.service-enabled", havingValue = "true")
public class AutoBindServiceScheduler {
@Autowired
private AutoBindServiceProcessor autoBindServiceProcessor;
@Scheduled(cron = "${cron.auto-bind.service}")
public void execute() {
log.info("schedule [自动绑定服务包] start >>>>>>>>>>");
autoBindServiceProcessor.execute();
log.info("schedule [自动绑定服务包] end <<<<<<<<<<");
}
}
package com.topdraw.platform.scheduler;
import com.topdraw.platform.executor.AutoOnlineProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@ConditionalOnProperty(prefix = "scheduler", name = "media-online-enabled", havingValue = "true")
public class AutoOnlineScheduler {
@Autowired
private AutoOnlineProcessor autoOnlineProcessor;
@Scheduled(cron = "${cron.media-online}")
public void execute() {
log.info("schedule [内容自动上线] start >>>>>>>>>>");
autoOnlineProcessor.execute();
log.info("schedule [内容自动上线] end <<<<<<<<<<");
}
}
package com.topdraw.platform.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
@Component
@Slf4j
public class DbUtil {
@Resource
DataSource dataSource;
public Connection getConnection() throws SQLException {
Connection connection = null;
if (dataSource != null) {
connection = dataSource.getConnection();
connection.setAutoCommit(true);
}
return connection;
}
public void close(Connection conn) {
if (conn != null) {
try {
if (!conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 查询唯一结果集
*
* @param conn
* @param strSqlCommand
* @param parameters
* @return
* @throws SQLException
*/
public Map<String, Object> queryUniqueResult(Connection conn, String strSqlCommand, Object... parameters)
throws SQLException {
QueryRunner runner = new QueryRunner();
MapHandler handler = new MapHandler();
return runner.query(conn, strSqlCommand, handler, parameters);
}
/**
* 列表查询
*
* @param conn
* @param strSqlCommand
* @param parameters
* @return
* @throws Exception
*/
public List<Map<String, Object>> queryList(Connection conn, String strSqlCommand, Object... parameters)
throws SQLException {
QueryRunner runner = new QueryRunner();
MapListHandler handler = new MapListHandler();
return runner.query(conn, strSqlCommand, handler, parameters);
}
/***
* 记录保存
*
* @param conn
* @param mapData
* @param objectName
* @return
* @throws SQLException
*/
public <T> T save(Connection conn, Map<String, Object> mapData, String objectName) throws SQLException {
if (!mapData.containsKey("update_time") || mapData.get("update_time") == null) {
mapData.put("update_time", new Date());
}
if (!mapData.containsKey("create_time") || mapData.get("create_time") == null) {
mapData.put("create_time", new Date());
}
Iterator<String> it = mapData.keySet().iterator();
String key;
StringBuilder sbInsert = new StringBuilder();
sbInsert.append("INSERT INTO ").append(objectName);
List<Object> valueList = new ArrayList<>();
List<String> filedNameList = new ArrayList<>();
List<String> preValueList = new ArrayList<>();
while (it.hasNext()) {
key = it.next();
filedNameList.add(key);
preValueList.add("?");
valueList.add(mapData.get(key));
}
sbInsert.append(" ( `").append(StringUtils.collectionToDelimitedString(filedNameList, "`,`"))
.append("` ) VALUES ( ").append(StringUtils.collectionToDelimitedString(preValueList, ",")).append(")");
QueryRunner run = new QueryRunner();
return run.insert(conn, sbInsert.toString(), new InsertResultHandler<T>(), valueList.toArray());
}
private class InsertResultHandler<T> implements ResultSetHandler<T> {
@SuppressWarnings("unchecked")
@Override
public T handle(ResultSet rs) throws SQLException {
T t;
if (rs.next()) {
t = (T) rs.getObject(1);
} else {
// throw new NoIdGeneratedException("No id generated from database...");
return null;
}
return t;
}
}
/**
* 记录更新
*
* @param conn
* @param mapData
* @param objectName
* @param strPrimaryKey
* @return
* @throws SQLException
*/
public long update(Connection conn, Map<String, Object> mapData, String objectName, String strPrimaryKey)
throws SQLException {
if (!mapData.containsKey("update_time") || mapData.get("update_time") == null) {
mapData.put("update_time", new Date());
}
Iterator<String> it = mapData.keySet().iterator();
String key;
List<Object> valList = new ArrayList<>();
StringBuffer updateSql = new StringBuffer(128);
updateSql.append("UPDATE ").append(objectName).append(" SET ");
while (it.hasNext()) {
key = it.next();
if (key.equalsIgnoreCase(strPrimaryKey)) {
continue;
}
updateSql.append("`" + key + "`").append("=?,");
valList.add(mapData.get(key));
}
updateSql.deleteCharAt(updateSql.length() - 1);
updateSql.append(" WHERE `" + strPrimaryKey + "`= ? ");
valList.add(mapData.get(strPrimaryKey));
return doExecute(conn, updateSql.toString(), valList.toArray());
}
/**
* sql执行
*
* @param conn
* @param sql
* @param parameters
* @return
* @throws SQLException
*/
public long doExecute(Connection conn, String sql, Object... parameters) throws SQLException {
QueryRunner runner = new QueryRunner();
return runner.update(conn, sql, parameters);
}
/**
* 按主键删除记录
*
* @param conn
* @param objectName
* @param id
* @return
*/
public int deleteById(Connection conn, String objectName, String id) throws SQLException {
String sql = "DELETE FROM " + objectName + " WHERE id = ? ";
QueryRunner runner = new QueryRunner();
return runner.update(conn, sql, id);
}
public void beginTransaction(Connection connection) throws Exception {
connection.setAutoCommit(false);
connection.setReadOnly(false);
}
public void commitTransaction(Connection connection) throws SQLException {
if (!connection.getAutoCommit()) {
connection.commit();
}
}
public void rollbackTransaction(Connection connection) throws SQLException {
if (!connection.getAutoCommit()) {
connection.rollback();
}
}
}
package com.topdraw.platform.util;
/*
MessageDigest md = MessageDigest.getInstance("SHA");
try {
md.update(toChapter1);
MessageDigest tc1 = md.clone();
byte[] toChapter1Digest = tc1.digest();
md.update(toChapter2);
...etc.
} catch (CloneNotSupportedException cnse) {
throw new DigestException("couldn't make digest of partial content");
}
*/
import org.apache.commons.codec.binary.Hex;
import org.apache.tomcat.util.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @author zehui.zeng
* @date 13-3-17 下午9:23
*/
public class MD5Util {
private final String algorithm;
private boolean encodeHashAsBase64 = false;
private static MD5Util md5 = null;
/**
* The digest algorithm to use
* Supports the named <a href="http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html#AppA">
* Message Digest Algorithms</a> in the Java environment.
*
* @param algorithm
*/
public MD5Util(String algorithm) {
this(algorithm, false);
}
public MD5Util(){
this.algorithm = "MD5";
}
/**
* Convenience constructor for specifying the algorithm and whether or not to enable base64 encoding
*
* @param algorithm
* @param encodeHashAsBase64
* @throws IllegalArgumentException if an unknown
*/
public MD5Util(String algorithm, boolean encodeHashAsBase64) throws IllegalArgumentException {
this.algorithm = algorithm;
setEncodeHashAsBase64(encodeHashAsBase64);
//Validity Check
getMessageDigest();
}
public static String encodePassword(String passwd){
if(md5 == null){
md5 = new MD5Util();
}
return md5.encodePassword(passwd, "");
}
/**
* Encodes the rawPass using a MessageDigest.
* If a salt is specified it will be merged with the password before encoding.
*
* @param rawPass The plain text password
* @param salt The salt to sprinkle
* @return Hex string of password digest (or base64 encoded string if encodeHashAsBase64 is enabled.
*/
public String encodePassword(String rawPass, Object salt) {
String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
MessageDigest messageDigest = getMessageDigest();
byte[] digest;
try {
digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 not supported!");
}
if (getEncodeHashAsBase64()) {
return new String(Base64.encodeBase64(digest));
} else {
return new String(Hex.encodeHex(digest));
}
}
/**
* Get a MessageDigest instance for the given algorithm.
* Throws an IllegalArgumentException if <i>algorithm</i> is unknown
*
* @return MessageDigest instance
* @throws IllegalArgumentException if NoSuchAlgorithmException is thrown
*/
protected final MessageDigest getMessageDigest() throws IllegalArgumentException {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
}
}
/**
* Takes a previously encoded password and compares it with a rawpassword after mixing in the salt and
* encoding that value
*
* @param encPass previously encoded password
* @param rawPass plain text password
* @param salt salt to mix into password
* @return true or false
*/
public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
String pass1 = "" + encPass;
String pass2 = encodePassword(rawPass, salt);
return pass1.equals(pass2);
}
/**
* Used by subclasses to extract the password and salt from a merged <code>String</code> created using
* {@link #mergePasswordAndSalt(String,Object,boolean)}.<p>The first element in the returned array is the
* password. The second element is the salt. The salt array element will always be present, even if no salt was
* found in the <code>mergedPasswordSalt</code> argument.</p>
*
* @param mergedPasswordSalt as generated by <code>mergePasswordAndSalt</code>
*
* @return an array, in which the first element is the password and the second the salt
*
* @throws IllegalArgumentException if mergedPasswordSalt is null or empty.
*/
protected String[] demergePasswordAndSalt(String mergedPasswordSalt) {
if ((mergedPasswordSalt == null) || "".equals(mergedPasswordSalt)) {
throw new IllegalArgumentException("Cannot pass a null or empty String");
}
String password = mergedPasswordSalt;
String salt = "";
int saltBegins = mergedPasswordSalt.lastIndexOf("{");
if ((saltBegins != -1) && ((saltBegins + 1) < mergedPasswordSalt.length())) {
salt = mergedPasswordSalt.substring(saltBegins + 1, mergedPasswordSalt.length() - 1);
password = mergedPasswordSalt.substring(0, saltBegins);
}
return new String[] {password, salt};
}
/**
* Used by subclasses to generate a merged password and salt <code>String</code>.<P>The generated password
* will be in the form of <code>password{salt}</code>.</p>
* <p>A <code>null</code> can be passed to either method, and will be handled correctly. If the
* <code>salt</code> is <code>null</code> or empty, the resulting generated password will simply be the passed
* <code>password</code>. The <code>toString</code> method of the <code>salt</code> will be used to represent the
* salt.</p>
*
* @param password the password to be used (can be <code>null</code>)
* @param salt the salt to be used (can be <code>null</code>)
* @param strict ensures salt doesn't contain the delimiters
*
* @return a merged password and salt <code>String</code>
*
* @throws IllegalArgumentException if the salt contains '{' or '}' characters.
*/
protected String mergePasswordAndSalt(String password, Object salt, boolean strict) {
if (password == null) {
password = "";
}
if (strict && (salt != null)) {
if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
throw new IllegalArgumentException("Cannot use { or } in salt.toString()");
}
}
if ((salt == null) || "".equals(salt)) {
return password;
} else {
return password + "{" + salt.toString() + "}";
}
}
public String getAlgorithm() {
return algorithm;
}
public boolean getEncodeHashAsBase64() {
return encodeHashAsBase64;
}
/**
* The encoded password is normally returned as Hex (32 char) version of the hash bytes. Setting this
* property to true will cause the encoded pass to be returned as Base64 text, which will consume 24 characters.
*
* @param encodeHashAsBase64 set to true for Base64 output
*/
public void setEncodeHashAsBase64(boolean encodeHashAsBase64) {
this.encodeHashAsBase64 = encodeHashAsBase64;
}
public static void main(String[] args){
System.out.println(MD5Util.encodePassword("system1"));
}
}
package com.topdraw.platform.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
@Component
public class MailUtil {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String from;
@Value("${spring.mail.developer-mail-address}")
private String to;
public void sendSimpleMail(String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}
package com.topdraw.platform.util;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 通过HTTP协议 访问服务器
*
* @author LucaMa
*
*/
@Slf4j
public class WebUtil {
public static boolean LOG = false;
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendGet(String url, boolean needRedirect) {
return sendGet(url, null, "UTF-8", null, needRedirect);
}
public static String sendGet(String url, String param, String charset) {
return sendGet(url, param, charset, null, true);
}
public static String sendGet(String url, String param, String charset, Integer timeout) {
return sendGet(url, param, charset, timeout, timeout, true);
}
public static String sendGet(String url, String param, String charset, Integer timeout, boolean needRedirect) {
return sendGet(url, param, charset, timeout, timeout, needRedirect);
}
public static String sendGet(String url, String param, String charset, Integer connectTimeout,
Integer readTimeout) {
return sendGet(url, param, charset, connectTimeout, readTimeout, true);
}
public static String sendGet(String url, String param, String charset, Integer connectTimeout,Integer readTimeout,boolean needRedirect) {
String result = "";
StringBuilder sbResult = new StringBuilder();
BufferedReader in = null;
try {
String urlName = url + ((null != param && !"".equals(param)) ? ("?" + param) : "");
URL realUrl = new URL(urlName);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
// 设置通用的请求属性
conn.setInstanceFollowRedirects(needRedirect);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("charset", charset);
if (null != connectTimeout && connectTimeout > 0) {
conn.setConnectTimeout(connectTimeout);
}
if (null != readTimeout && readTimeout > 0) {
conn.setReadTimeout(readTimeout);
}
//conn.setRequestProperty("charset", conn.setRequestProperty("charset", charset);;);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 建立实际的连接
conn.connect();
// 获取所有响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
if(LOG){
log.info(key + "--->" + map.get(key));
}
}
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),charset));
String line;
while ((line = in.readLine()) != null) {
sbResult.append(line).append("\n");
}
if (null != sbResult && sbResult.length() > 0) {
sbResult.setLength(sbResult.length() - 1);
}
result = sbResult.toString();
} catch (Exception e) {
//System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
//throw e;
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String sendGet(String url, Map<String,String> mapParam , String charset) {
StringBuilder sbParam=new StringBuilder("");
int i1=0;
Set<String> setKey=mapParam.keySet();
for (String strKey : setKey ) {
sbParam.append(strKey).append("=").append(mapParam.get(strKey));
if (i1<setKey.size()-1){
sbParam.append("&");
}
i1++;
}
return sendGet(url, sbParam.toString(), charset);
}
/**
* 向指定URL发送POST方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendPost(String url, String param , String charset, String contentType) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
StringBuilder sbResult = new StringBuilder();
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("charset", charset);
if (null!=contentType && !contentType.isEmpty()){
conn.setRequestProperty("Content-Type",contentType);
}
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(new String(param.getBytes(charset)));
// flush 输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),charset));
String line;
while ((line = in.readLine()) != null) {
sbResult.append(line).append("\n");
}
if (null != sbResult && sbResult.length() > 0) {
sbResult.setLength(sbResult.length() - 1);
}
result = sbResult.toString();
} catch (Exception e) {
//System.out.println("发送POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流.
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, Map<String,String> mapParam , String charset,String contentType) {
StringBuilder sbParam=new StringBuilder("");
int i1=0;
Set<String> setKey=mapParam.keySet();
for (String strKey : setKey ) {
sbParam.append(strKey).append("=").append(mapParam.get(strKey));
if (i1<setKey.size()-1){
sbParam.append("&");
}
i1++;
}
return sendPost(url, sbParam.toString(), charset,contentType);
}
//////////////////////////////////////////////////以下新版////////////////////////////////////////////
/**
* 新版本的 GET请求
*
* @param strURL
* 发送请求的URL
* @param strParam
* 请求参数,应该是name1=value1&name2=value2的形式。
* @thows Exception
*
* @return URL所代表远程资源的响应
*/
public static String sendGet(String strURL, String strParam, Map<String,String> mapHeader ) throws Exception {
String strResult = "";
BufferedReader brIn = null;
try {
String strFullURL = strURL + (null != strParam ? ("?" + strParam) : "");
URL url = new URL(strFullURL);
// 打开和URL之间的连接
//URLConnection conn = urlReal.openConnection();
HttpURLConnection connHttps = (HttpURLConnection)url.openConnection();
connHttps.setRequestMethod("GET");
connHttps.setUseCaches(false);
// 设置通用的请求属性
connHttps.setRequestProperty("Accept", "*/*");
connHttps.setRequestProperty("Charset", "UTF-8");
connHttps.setRequestProperty("Connection", "Keep-Alive");
connHttps.setRequestProperty("User-Agent", "Server(Java) WebUtil");
if (null!=mapHeader && !mapHeader.isEmpty()){
for(String strKey:mapHeader.keySet()){
String strValue=mapHeader.get(strKey);
char cFirst = strKey.charAt(0);
if(cFirst < 65 || cFirst > 90){ //不是大写开头
//System.out.println( new StringBuilder("A http header parameter '").append(strKey).append("' isn't start with capital letter.."));
}
if (null!=strValue && !strValue.isEmpty()){
connHttps.setRequestProperty(strKey, strValue);
}
}
}
//得到实际使用的Charset
String strCharset=mapHeader.get("Charset");
if (null==strCharset || strCharset.isEmpty()){
strCharset=mapHeader.get("charset");
if (null==strCharset || strCharset.isEmpty()){
strCharset="UTF-8";
}
}
// 建立实际的连接
connHttps.connect();
brIn = new BufferedReader(
new InputStreamReader(connHttps.getInputStream(),strCharset));
String strLine;
StringBuilder sbResult=new StringBuilder();
while ((strLine = brIn.readLine()) != null) {
sbResult.append("\n").append(strLine); //readLine不包含换行符
}
connHttps.disconnect();
strResult=sbResult.toString();
} catch (Exception e) {
//System.out.println("发送GET请求出现异常!" + e);
throw new IOException("WebUtil发送GET请求异常",e);
//e.printStackTrace();
//throw e;
} finally {// 使用finally块来关闭输入流
try {
if (brIn != null) {
brIn.close();
brIn=null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return strResult;
}
public static String sendGet(String strUrl, Map<String,String> mapParam, Map<String,String> mapHeader) throws Exception {
StringBuilder sbParam=new StringBuilder("");
int i1=0;
Set<String> setKey=mapParam.keySet();
for (String strKey : setKey ) {
sbParam.append(strKey).append("=").append(mapParam.get(strKey));
if (i1<setKey.size()-1){
sbParam.append("&");
}
i1++;
}
return sendGet(strUrl, sbParam.toString(), mapHeader);
}
public static String sendPost(String strUrl, Map<String, String> mapParam, Map<String, String> mapHeader)
throws Exception {
return sendPost(strUrl, mapParam, mapHeader, 5000);
}
public static String sendPost(String strUrl, String strParam, Map<String, String> mapHeader) throws Exception {
return sendPost(strUrl, strParam, mapHeader, 5000);
}
/**
* 新版的 POST请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是name1=value1&name2=value2的形式。
* @return URL所代表远程资源的响应
*/
public static String sendPost(String strUrl, String strParam , Map<String,String> mapHeader, Integer timeout) throws Exception {
PrintWriter brOut = null;
BufferedReader brIn = null;
String strResult = "";
try {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
URL realUrl = new URL(strUrl);
// 打开和URL之间的连接
//URLConnection conn = realUrl.openConnection();
HttpURLConnection connHttps = (HttpURLConnection)realUrl.openConnection();
if (null != timeout) {
connHttps.setConnectTimeout(timeout);
connHttps.setReadTimeout(timeout);
}
connHttps.setRequestMethod("POST");
connHttps.setUseCaches(false);
// 设置默认通用的请求属性
connHttps.setRequestProperty("Accept", "*/*");
connHttps.setRequestProperty("Charset", "UTF-8");
connHttps.setRequestProperty("Connection", "Keep-Alive");
connHttps.setRequestProperty("User-Agent", "Server(Java) WebUtil");
if (null!=mapHeader && !mapHeader.isEmpty()){
for(String strKey:mapHeader.keySet()){
String strValue=mapHeader.get(strKey);
char cFirst = strKey.charAt(0);
if(cFirst < 65 || cFirst > 90){ //不是大写开头
//System.out.println( new StringBuilder("A http header parameter '").append(strKey).append("' isn't start with capital letter.."));
}
if (null!=strValue && !strValue.isEmpty()){
connHttps.setRequestProperty(strKey, strValue);
}
}
}
/*
if (null!=contentType && !contentType.isEmpty()){
conn.setRequestProperty("Content-Type",contentType);
}*/
// 发送POST请求必须设置如下两行
connHttps.setDoOutput(true);
connHttps.setDoInput(true);
// 获取URLConnection对象对应的输出流
brOut = new PrintWriter(connHttps.getOutputStream());
//得到实际使用的Charset
String strCharset=mapHeader.get("Charset");
if (null==strCharset || strCharset.isEmpty()){
strCharset=mapHeader.get("charset");
if (null==strCharset || strCharset.isEmpty()){
strCharset="UTF-8";
}
}
// 发送请求参数
brOut.print(new String(strParam.getBytes(strCharset)));
// flush 输出流的缓冲
brOut.flush();
//System.out.println(connHttps.getResponseCode());
// 定义BufferedReader输入流来读取URL的响应
brIn = new BufferedReader(
new InputStreamReader(connHttps.getInputStream(),strCharset));
String strLine;
StringBuilder sbResult=new StringBuilder();
while ((strLine = brIn.readLine()) != null) {
sbResult.append(strLine).append("\n"); //readLine不包含换行符
}
if (null != sbResult && sbResult.length() > 0) {
sbResult.setLength(sbResult.length() - 1);
}
connHttps.disconnect();
strResult=sbResult.toString();
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {// 使用finally块来关闭输出流、输入流.
try {
if (brOut != null) {
brOut.close();
brOut=null;
}
if (brIn != null) {
brIn.close();
brIn=null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return strResult;
}
public static String sendPost(String url, Map<String,String> mapParam ,Map<String,String> mapHeader, Integer timeout) throws Exception {
StringBuilder sbParam=new StringBuilder("");
int i1=0;
Set<String> setKey=mapParam.keySet();
for (String strKey : setKey ) {
sbParam.append(strKey).append("=").append(mapParam.get(strKey));
if (i1<setKey.size()-1){
sbParam.append("&");
}
i1++;
}
return sendPost(url, sbParam.toString(), mapHeader, timeout);
}
/**
* 安全的 Get 请求
*
*
*
**/
public static String sendSecureGet(String strURL, String strParam, Map<String,String> mapHeader
,TrustManager tmIn) throws Exception {
BufferedReader brIn=null;
String strResult=null;
try {
// 创建SSLContext对象,并使用指定的信任管理器初始化
TrustManager[] arrayTM = { tmIn };
SSLContext sslc = SSLContext.getInstance("SSL", "SunJSSE");
sslc.init(null, arrayTM, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory sslsf = sslc.getSocketFactory();
URL urlHttps = new URL(strURL);
HttpsURLConnection connHttps = (HttpsURLConnection)(urlHttps.openConnection());
connHttps.setSSLSocketFactory(sslsf);
//设置请求方式(GET/POST)
connHttps.setRequestMethod("GET");
connHttps.setUseCaches(false);
//设置通用的请求属性
connHttps.setRequestProperty("Accept", "*/*");
connHttps.setRequestProperty("Charset", "UTF-8");
connHttps.setRequestProperty("Connection", "Keep-Alive");
connHttps.setRequestProperty("User-Agent", "Server(Java) WebUtil");
if (null!=mapHeader && !mapHeader.isEmpty()){
for(String strKey:mapHeader.keySet()){
String strValue=mapHeader.get(strKey);
char cFirst = strKey.charAt(0);
if(cFirst < 65 || cFirst > 90){ //不是大写开头
//System.out.println( new StringBuilder("A http header parameter '").append(strKey).append("' isn't start with capital letter.."));
}
if (null!=strValue && !strValue.isEmpty()){
connHttps.setRequestProperty(strKey, strValue);
}
}
}
//得到实际使用的Charset
String strCharset=mapHeader.get("Charset");
if (null==strCharset || strCharset.isEmpty()){
strCharset=mapHeader.get("charset");
if (null==strCharset || strCharset.isEmpty()){
strCharset="UTF-8";
}
}
// 建立实际的连接
connHttps.connect();
// 定义BufferedReader输入流来读取URL的响应
brIn = new BufferedReader(
new InputStreamReader(connHttps.getInputStream(),strCharset));
String strLine;
StringBuilder sbResult=new StringBuilder();
while ((strLine = brIn.readLine()) != null) {
sbResult.append("\n").append(strLine); //readLine不包含换行符
}
connHttps.disconnect();
strResult=sbResult.toString();
} catch (Exception e) {
throw new IOException("WebUtil发送安全的GET请求异常",e);
} finally {// 使用finally块来关闭输出流、输入流.
try {
if (brIn != null) {
brIn.close();
brIn=null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return strResult;
}
public static String sendSecureGet(String strUrl, Map<String,String> mapParam, Map<String,String> mapHeader,TrustManager tmIn) throws Exception {
StringBuilder sbParam=new StringBuilder("");
int i1=0;
Set<String> setKey=mapParam.keySet();
for (String strKey : setKey ) {
sbParam.append(strKey).append("=").append(mapParam.get(strKey));
if (i1<setKey.size()-1){
sbParam.append("&");
}
i1++;
}
return sendSecureGet(strUrl, sbParam.toString(), mapHeader,tmIn);
}
/**
* 安全的 Post 请求
*
*
*
**/
public static String sendSecurePost(String strURL, String strParam, Map<String,String> mapHeader
,TrustManager tmIn) throws Exception {
BufferedReader brIn=null;
PrintWriter brOut=null;
String strResult=null;
try {
// 创建SSLContext对象,并使用指定的信任管理器初始化
TrustManager[] arrayTM = { tmIn };
SSLContext sslc = SSLContext.getInstance("SSL", "SunJSSE");
sslc.init(null, arrayTM, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory sslsf = sslc.getSocketFactory();
URL urlHttps = new URL(strURL);
HttpsURLConnection connHttps = (HttpsURLConnection)(urlHttps.openConnection());
connHttps.setSSLSocketFactory(sslsf);
//设置请求方式(GET/POST)
connHttps.setRequestMethod("POST");
//设置POST所需配置
connHttps.setDoOutput(true);
connHttps.setDoInput(true);
connHttps.setUseCaches(false);
//设置通用的请求属性
connHttps.setRequestProperty("Accept", "*/*");
connHttps.setRequestProperty("Charset", "UTF-8");
connHttps.setRequestProperty("Connection", "Keep-Alive");
connHttps.setRequestProperty("User-Agent", "Server(Java) WebUtil");
if (null!=mapHeader && !mapHeader.isEmpty()){
for(String strKey:mapHeader.keySet()){
String strValue=mapHeader.get(strKey);
char cFirst = strKey.charAt(0);
if(cFirst < 65 || cFirst > 90){ //不是大写开头
//System.out.println( new StringBuilder("A http header parameter '").append(strKey).append("' isn't start with capital letter.."));
}
if (null!=strValue && !strValue.isEmpty()){
connHttps.setRequestProperty(strKey, strValue);
}
}
}
//得到实际使用的Charset
String strCharset=mapHeader.get("Charset");
if (null==strCharset || strCharset.isEmpty()){
strCharset=mapHeader.get("charset");
if (null==strCharset || strCharset.isEmpty()){
strCharset="UTF-8";
}
}
// 获取URLConnection对象对应的输出流
brOut = new PrintWriter(connHttps.getOutputStream());
// 发送请求参数
if (null!=strParam){
brOut.print(new String(strParam.getBytes(strCharset)));
brOut.flush();
}
// 定义BufferedReader输入流来读取URL的响应
brIn = new BufferedReader(new InputStreamReader(connHttps.getInputStream(),strCharset));
String strLine;
StringBuilder sbResult=new StringBuilder();
while ((strLine = brIn.readLine()) != null) {
sbResult.append("\n").append(strLine); //readLine不包含换行符
}
connHttps.disconnect();
strResult=sbResult.toString();
} catch (Exception e) {
throw new IOException("WebUtil发送安全的POST请求异常",e);
} finally { // 使用finally块来关闭输出流、输入流.
try {
if (brIn != null) {
brIn.close();
brIn=null;
}
if (brOut != null) {
brOut.close();
brOut=null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return strResult;
}
public static String sendSecurePost(String url, Map<String,String> mapParam ,Map<String,String> mapHeader,TrustManager tmIn) throws Exception {
StringBuilder sbParam=new StringBuilder("");
int i1=0;
Set<String> setKey=mapParam.keySet();
for (String strKey : setKey ) {
sbParam.append(strKey).append("=").append(mapParam.get(strKey));
if (i1<setKey.size()-1){
sbParam.append("&");
}
i1++;
}
return sendSecurePost(url, sbParam.toString(), mapHeader,tmIn);
}
/**
* 获取请求的PostBody
*
*
*
**/
public static String getPostBody(HttpServletRequest request)
throws IOException {
// 解析结果存储在HashMap
//Map<String, Object> map = new HashMap<String, Object>();
String str = "";
BufferedReader reader = null;
try {
StringBuilder buffer = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(
request.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
str = buffer.toString();
//map = JSONUtil.json2map(str);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return str;
}
/**
* 向指定 URL 发送POST方法 发送PostBody
*
* @param url
*
* @param param
*
* @return
*/
/*
@Deprecated
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "* /*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (ConnectException ce) {
System.out.println("发送 POST 请求出现异常(Connection timed out!)");
//logger.info(url+" (post failed)");
ce.printStackTrace();
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}finally{//使用finally块来关闭输出流、输入流
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}*/
/**
* 处理用户上传
*/
public static String handleUpload(HttpServletRequest request, HttpServletResponse response, String strFilePath,String strFileName)
throws Exception {
//String strFileName = request.getParameter("fileName");
//strFileName = new String(strFileName.getBytes("ISO-8859-1"),"UTF-8");
//String overFlg = request.getParameter("over"); // 0:go on;1:over
//System.out.println("get: " + fileName);
byte[] buf = new byte[4096];
if (strFilePath.charAt(strFilePath.length()-1)!='/'){
strFilePath+="/";
}
strFileName=strFilePath+strFileName;
File file = new File(strFileName);
InputStream is = null;
BufferedOutputStream fileOut
= new BufferedOutputStream(new FileOutputStream(file, true));
try {
is = request.getInputStream();
while (true) {
int bytesIn = is.read(buf, 0, 4096);
//System.out.println(bytesIn);
if (bytesIn == -1) {
break;
} else {
fileOut.write(buf, 0, bytesIn);
}
}
fileOut.flush();
fileOut.close();
//System.out.println(file.getAbsolutePath());
} catch (IOException e) {
throw e;
}
return strFileName;
}
}
spring:
datasource:
url: jdbc:mysql://139.196.192.242:3306/cms_test?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
username: root
password: Tjlh@2017
driver-class-name: com.mysql.jdbc.Driver
hikari:
maximum-pool-size: 10
minimum-idle: 5
idle-timeout: 180000
auto-commit: true
connection-timeout: 30000
connection-test-query: SELECT 1
spring:
datasource:
url: jdbc:mysql://139.196.192.242:3306/cms_test?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&autoReconnect=true
username: root
password: Topdraw1qaz
driver-class-name: com.mysql.jdbc.Driver
hikari:
maximum-pool-size: 10
minimum-idle: 5
idle-timeout: 180000
auto-commit: true
connection-timeout: 30000
connection-test-query: SELECT 1
server:
port: 18080
scheduler:
auto-bind:
app-enabled: true
service-enabled: true
media-online-enabled: true
cron:
auto-bind:
app: 0/10 * * * * ?
service: 0/10 * * * * ?
media-online: 0/10 * * * * ?
spring:
mail:
host: smtp.ym.163.com
username: test@topdraw.cn
password: 123456789
protocol: smtp
default-encoding: utf-8
developer-mail-address: wanghongyan@topdraw.cn
profiles:
active: dev
entity:
appId: 63
serviceId: 1
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!--定义参数,后面可以通过${app.name}使用-->
<property name="app.name" value="cms.scheduler"/>
<property name="log.path" value="./logs"/>
<property name="log.pattern" value="%d [%thread] %-5level %logger{36} [%file : %line] - %msg%n"/>
<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoder 默认配置为PatternLayoutEncoder -->
<!--定义控制台输出格式-->
<encoder>
<pattern>%red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}) - %msg %n</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<!--获取比info级别高(包括info级别)但除error级别的日志-->
<appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<!--滚动策略-->
<file>${log.path}/${app.name}-info.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径-->
<fileNamePattern>${log.path}/info/${app.name}-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
<!-- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
<!-- &lt;!&ndash;每个日志文件最大100MB&ndash;&gt;-->
<!-- <maxFileSize>100MB</maxFileSize>-->
<!-- </triggeringPolicy>-->
</appender>
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<!--滚动策略-->
<file>${log.path}/${app.name}-error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--路径-->
<fileNamePattern>${log.path}/error/${app.name}-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>10GB</totalSizeCap>
</rollingPolicy>
<!-- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
<!-- &lt;!&ndash;每个日志文件最大50MB&ndash;&gt;-->
<!-- <maxFileSize>50MB</maxFileSize>-->
<!-- </triggeringPolicy>-->
</appender>
<!--普通日志输出到控制台-->
<root level="info">
<appender-ref ref="console" />
<appender-ref ref="info" />
<appender-ref ref="error" />
</root>
<!--监控sql日志输出 -->
<logger name="jdbc.sqlonly" level="INFO" additivity="false">
<appender-ref ref="console" />
</logger>
<logger name="jdbc.resultset" level="ERROR" additivity="false">
<appender-ref ref="console" />
</logger>
<!-- 如想看到表格数据,将OFF改为INFO -->
<logger name="jdbc.resultsettable" level="OFF" additivity="false">
<appender-ref ref="console" />
</logger>
<logger name="jdbc.connection" level="OFF" additivity="false">
<appender-ref ref="console" />
</logger>
<logger name="jdbc.sqltiming" level="OFF" additivity="false">
<appender-ref ref="console" />
</logger>
<logger name="jdbc.audit" level="OFF" additivity="false">
<appender-ref ref="console" />
</logger>
</configuration>
package com.topdraw.platform;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LeviathanSchedulerApplicationTests {
@Test
void contextLoads() {
}
}