Commit 728edf62 728edf62e8085afbb977580ec6f8ae4e9d5da610 by lWoHvYe

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

0 parents
1 HELP.md
2 target/
3 !.mvn/wrapper/maven-wrapper.jar
4 !**/src/main/**/target/
5 !**/src/test/**/target/
6
7 ### STS ###
8 .apt_generated
9 .classpath
10 .factorypath
11 .project
12 .settings
13 .springBeans
14 .sts4-cache
15
16 ### IntelliJ IDEA ###
17 .idea
18 *.iws
19 *.iml
20 *.ipr
21
22 ### NetBeans ###
23 /nbproject/private/
24 /nbbuild/
25 /dist/
26 /nbdist/
27 /.nb-gradle/
28 build/
29 !**/src/main/**/build/
30 !**/src/test/**/build/
31
32 ### VS Code ###
33 .vscode/
34
35 logs/*
36
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4 <modelVersion>4.0.0</modelVersion>
5 <parent>
6 <groupId>org.springframework.boot</groupId>
7 <artifactId>spring-boot-starter-parent</artifactId>
8 <version>2.3.4.RELEASE</version>
9 <relativePath/> <!-- lookup parent from repository -->
10 </parent>
11 <groupId>com.topdraw.platform</groupId>
12 <artifactId>cms-scheduler</artifactId>
13 <version>1.0</version>
14 <name>cms-scheduler</name>
15 <description>cms系统部分定时任务</description>
16
17 <properties>
18 <java.version>1.8</java.version>
19 </properties>
20
21 <dependencies>
22 <dependency>
23 <groupId>org.springframework.boot</groupId>
24 <artifactId>spring-boot-starter-web</artifactId>
25 </dependency>
26 <dependency>
27 <groupId>org.springframework.boot</groupId>
28 <artifactId>spring-boot-devtools</artifactId>
29 <scope>runtime</scope>
30 <optional>true</optional>
31 </dependency>
32 <dependency>
33 <groupId>org.projectlombok</groupId>
34 <artifactId>lombok</artifactId>
35 <optional>true</optional>
36 </dependency>
37 <dependency>
38 <groupId>org.springframework.boot</groupId>
39 <artifactId>spring-boot-starter-test</artifactId>
40 <scope>test</scope>
41 </dependency>
42 <dependency>
43 <groupId>org.springframework.boot</groupId>
44 <artifactId>spring-boot-starter-mail</artifactId>
45 </dependency>
46 <dependency>
47 <groupId>org.springframework.boot</groupId>
48 <artifactId>spring-boot-starter-jdbc</artifactId>
49 </dependency>
50 <dependency>
51 <groupId>com.alibaba</groupId>
52 <artifactId>fastjson</artifactId>
53 <version>1.2.73</version>
54 </dependency>
55 <dependency>
56 <groupId>mysql</groupId>
57 <artifactId>mysql-connector-java</artifactId>
58 <version>5.1.40</version>
59 </dependency>
60 <dependency>
61 <groupId>commons-dbutils</groupId>
62 <artifactId>commons-dbutils</artifactId>
63 <version>1.7</version>
64 </dependency>
65 <dependency>
66 <groupId>commons-codec</groupId>
67 <artifactId>commons-codec</artifactId>
68 <version>1.15</version>
69 </dependency>
70 <dependency>
71 <groupId>cn.hutool</groupId>
72 <artifactId>hutool-all</artifactId>
73 <version>5.5.2</version>
74 </dependency>
75 </dependencies>
76
77 <profiles>
78 <!-- 本地开发环境 -->
79 <profile>
80 <id>dev</id>
81 <properties>
82 <profiles.active>dev</profiles.active>
83 </properties>
84 <activation>
85 <!-- 默认的,不加参数时执行这个profile -->
86 <activeByDefault>true</activeByDefault>
87 </activation>
88 </profile>
89 <!-- 生产环境 -->
90 <profile>
91 <id>prod</id>
92 <properties>
93 <profiles.active>prod</profiles.active>
94 <modifier>-prod</modifier>
95 </properties>
96 </profile>
97 </profiles>
98
99 <build>
100 <plugins>
101 <plugin>
102 <groupId>org.springframework.boot</groupId>
103 <artifactId>spring-boot-maven-plugin</artifactId>
104 </plugin>
105 <plugin>
106 <groupId>org.apache.maven.plugins</groupId>
107 <artifactId>maven-surefire-plugin</artifactId>
108 <configuration>
109 <skip>true</skip>
110 </configuration>
111 </plugin>
112 <plugin>
113 <artifactId>maven-resources-plugin</artifactId>
114 <executions>
115 <execution>
116 <id>copy-resources</id>
117 <phase>package</phase>
118 <goals>
119 <goal>copy-resources</goal>
120 </goals>
121 <configuration>
122 <resources>
123 <resource>
124 <directory>src/main/resources/config</directory>
125 <includes>
126 <include>application.yml</include>
127 <include>application-${profiles.active}.yml</include>
128 </includes>
129 </resource>
130 </resources>
131 <outputDirectory>${project.build.directory}/config</outputDirectory>
132 </configuration>
133 </execution>
134 </executions>
135 </plugin>
136 <!-- jar包内剔除所有配置文件 -->
137 <plugin>
138 <artifactId>maven-jar-plugin</artifactId>
139 <configuration>
140 <!--不打入jar包的文件类型或者路径-->
141 <excludes>
142 <exclude>config/**</exclude>
143 </excludes>
144 </configuration>
145 </plugin>
146 </plugins>
147 </build>
148
149 </project>
1 #!/bin/bash
2 echo Stopping application
3 source ./shutdown.sh
4 # sleep 2
5 echo Starting application
6 source ./start.sh
1 #!/bin/bash
2 echo "stop SpringBoot BAppApiServerApplication"
3 pid=`ps -ef | grep cms-scheduler-1.0.jar | grep -v grep | awk '{print $2}'`
4 echo "旧应用进程id:" $pid
5 if [ -n "$pid" ]
6 then
7 kill -9 $pid
8 fi
9
1 #!/bin/bash
2 export JAVA_HOME=/x/app/jdk1.8.0_77
3 echo ${JAVA_HOME}
4 echo "授权当前用户"
5 chmod 777 ./*.jar
6 echo "执行...."
7 # cd x/app/ams/
8 nohup ${JAVA_HOME}/bin/java -Xms100m -Xmx500m -jar cms-scheduler-1.0.jar --spring.profiles.active=prod >log.info &
9 echo "启动成功"
1 package com.topdraw.platform;
2
3 import org.springframework.boot.SpringApplication;
4 import org.springframework.boot.autoconfigure.SpringBootApplication;
5 import org.springframework.scheduling.annotation.EnableScheduling;
6
7 @SpringBootApplication
8 @EnableScheduling
9 public class CmsSchedulerApplication {
10
11 public static void main(String[] args) {
12 SpringApplication.run(CmsSchedulerApplication.class, args);
13 }
14
15 }
1 package com.topdraw.platform.executor;
2
3 import cn.hutool.core.util.StrUtil;
4 import com.topdraw.platform.util.DbUtil;
5 import lombok.extern.slf4j.Slf4j;
6 import lombok.var;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.beans.factory.annotation.Value;
9 import org.springframework.stereotype.Component;
10 import org.springframework.transaction.annotation.Transactional;
11
12 import java.sql.Connection;
13 import java.util.HashMap;
14 import java.util.List;
15 import java.util.Map;
16
17 @Component
18 @Slf4j
19 public class AutoBindAppProcessor {
20 @Autowired
21 DbUtil dbUtil;
22
23 @Value("${entity.appId}")
24 private Long APP_ID;
25
26 @Transactional(rollbackFor = Exception.class)
27 public void execute() {
28 Connection connection = null;
29 try {
30 connection = dbUtil.getConnection();
31 // 查询未绑定
32 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);
33 List<Map<String, Object>> list = dbUtil.queryList(connection, sql);
34 // 开启事务
35 dbUtil.beginTransaction(connection);
36 for (Map<String, Object> map : list) {
37 var mediaId = (Long) map.get("id");
38 var mapData = new HashMap<String, Object>();
39 mapData.put("media_id", mediaId);
40 mapData.put("app_id", APP_ID);
41 String objectName = "x_media__app";
42 // 添加关联关系
43 dbUtil.save(connection, mapData, objectName);
44 }
45 // 提交事务
46 dbUtil.commitTransaction(connection);
47
48 } catch (Exception ex) {
49 ex.printStackTrace();
50 } finally {
51 dbUtil.close(connection);
52 }
53 }
54 }
1 package com.topdraw.platform.executor;
2
3 import cn.hutool.core.util.StrUtil;
4 import com.topdraw.platform.util.DbUtil;
5 import lombok.extern.slf4j.Slf4j;
6 import lombok.var;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.beans.factory.annotation.Value;
9 import org.springframework.stereotype.Component;
10 import org.springframework.transaction.annotation.Transactional;
11
12 import java.sql.Connection;
13 import java.util.HashMap;
14 import java.util.List;
15 import java.util.Map;
16
17 @Component
18 @Slf4j
19 public class AutoBindServiceProcessor {
20 @Autowired
21 DbUtil dbUtil;
22
23 @Value("${entity.serviceId}")
24 private Long SERVICE_ID;
25
26 @Transactional(rollbackFor = Exception.class)
27 public void execute() {
28 Connection connection = null;
29 try {
30 connection = dbUtil.getConnection();
31 // 查询未绑定
32 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);
33 List<Map<String, Object>> list = dbUtil.queryList(connection, sql);
34 // 开启事务
35 dbUtil.beginTransaction(connection);
36 for (Map<String, Object> map : list) {
37 var mediaId = (Long) map.get("id");
38 var mapData = new HashMap<String, Object>();
39 mapData.put("media_id", mediaId);
40 mapData.put("service_id", SERVICE_ID);
41 String objectName = "x_service__media";
42 // 添加关联关系
43 dbUtil.save(connection, mapData, objectName);
44 }
45 // 提交事务
46 dbUtil.commitTransaction(connection);
47
48 } catch (Exception ex) {
49 ex.printStackTrace();
50 } finally {
51 dbUtil.close(connection);
52 }
53 }
54 }
1 package com.topdraw.platform.executor;
2
3 import cn.hutool.core.date.DateUtil;
4 import cn.hutool.core.util.StrUtil;
5 import com.topdraw.platform.util.DbUtil;
6 import lombok.extern.slf4j.Slf4j;
7 import org.springframework.beans.factory.annotation.Autowired;
8 import org.springframework.stereotype.Component;
9 import org.springframework.transaction.annotation.Transactional;
10
11 import java.sql.Connection;
12
13 @Component
14 @Slf4j
15 public class AutoOnlineProcessor {
16 @Autowired
17 DbUtil dbUtil;
18
19 @Transactional(rollbackFor = Exception.class)
20 public void execute() {
21 Connection connection = null;
22 String today = DateUtil.today();
23 try {
24 connection = dbUtil.getConnection();
25 // 查询未绑定
26 String sql = " update `x_media` set `status` = '001' where `status` = '000' and file_status = '001' and create_time >= ? ";
27 dbUtil.doExecute(connection, sql, today);
28 // 提交事务
29 dbUtil.commitTransaction(connection);
30
31 } catch (Exception ex) {
32 ex.printStackTrace();
33 } finally {
34 dbUtil.close(connection);
35 }
36 }
37 }
1 package com.topdraw.platform.scheduler;
2
3 import com.topdraw.platform.executor.AutoBindAppProcessor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
7 import org.springframework.scheduling.annotation.Scheduled;
8 import org.springframework.stereotype.Component;
9
10 @Component
11 @Slf4j
12 @ConditionalOnProperty(prefix = "scheduler", name = "auto-bind.app-enabled", havingValue = "true")
13 public class AutoBindAppScheduler {
14
15 @Autowired
16 private AutoBindAppProcessor autoBindAppProcessor;
17
18 @Scheduled(cron = "${cron.auto-bind.app}")
19 public void execute() {
20 log.info("schedule [自动绑定应用] start >>>>>>>>>>");
21 autoBindAppProcessor.execute();
22 log.info("schedule [自动绑定应用] end <<<<<<<<<<");
23 }
24 }
1 package com.topdraw.platform.scheduler;
2
3 import com.topdraw.platform.executor.AutoBindServiceProcessor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
7 import org.springframework.scheduling.annotation.Scheduled;
8 import org.springframework.stereotype.Component;
9
10 @Component
11 @Slf4j
12 @ConditionalOnProperty(prefix = "scheduler", name = "auto-bind.service-enabled", havingValue = "true")
13 public class AutoBindServiceScheduler {
14
15 @Autowired
16 private AutoBindServiceProcessor autoBindServiceProcessor;
17
18 @Scheduled(cron = "${cron.auto-bind.service}")
19 public void execute() {
20 log.info("schedule [自动绑定服务包] start >>>>>>>>>>");
21 autoBindServiceProcessor.execute();
22 log.info("schedule [自动绑定服务包] end <<<<<<<<<<");
23 }
24 }
1 package com.topdraw.platform.scheduler;
2
3 import com.topdraw.platform.executor.AutoOnlineProcessor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
7 import org.springframework.scheduling.annotation.Scheduled;
8 import org.springframework.stereotype.Component;
9
10 @Component
11 @Slf4j
12 @ConditionalOnProperty(prefix = "scheduler", name = "media-online-enabled", havingValue = "true")
13 public class AutoOnlineScheduler {
14
15 @Autowired
16 private AutoOnlineProcessor autoOnlineProcessor;
17
18 @Scheduled(cron = "${cron.media-online}")
19 public void execute() {
20 log.info("schedule [内容自动上线] start >>>>>>>>>>");
21 autoOnlineProcessor.execute();
22 log.info("schedule [内容自动上线] end <<<<<<<<<<");
23 }
24 }
1 package com.topdraw.platform.util;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.commons.dbutils.QueryRunner;
5 import org.apache.commons.dbutils.ResultSetHandler;
6 import org.apache.commons.dbutils.handlers.MapHandler;
7 import org.apache.commons.dbutils.handlers.MapListHandler;
8 import org.springframework.stereotype.Component;
9 import org.springframework.util.StringUtils;
10
11 import javax.annotation.Resource;
12 import javax.sql.DataSource;
13 import java.sql.Connection;
14 import java.sql.ResultSet;
15 import java.sql.SQLException;
16 import java.util.*;
17
18 @Component
19 @Slf4j
20 public class DbUtil {
21 @Resource
22 DataSource dataSource;
23
24 public Connection getConnection() throws SQLException {
25 Connection connection = null;
26 if (dataSource != null) {
27 connection = dataSource.getConnection();
28 connection.setAutoCommit(true);
29 }
30 return connection;
31 }
32
33 public void close(Connection conn) {
34 if (conn != null) {
35 try {
36 if (!conn.isClosed()) {
37 conn.close();
38 }
39 } catch (SQLException e) {
40 e.printStackTrace();
41 }
42 }
43 }
44
45 /**
46 * 查询唯一结果集
47 *
48 * @param conn
49 * @param strSqlCommand
50 * @param parameters
51 * @return
52 * @throws SQLException
53 */
54 public Map<String, Object> queryUniqueResult(Connection conn, String strSqlCommand, Object... parameters)
55 throws SQLException {
56 QueryRunner runner = new QueryRunner();
57 MapHandler handler = new MapHandler();
58 return runner.query(conn, strSqlCommand, handler, parameters);
59 }
60
61 /**
62 * 列表查询
63 *
64 * @param conn
65 * @param strSqlCommand
66 * @param parameters
67 * @return
68 * @throws Exception
69 */
70 public List<Map<String, Object>> queryList(Connection conn, String strSqlCommand, Object... parameters)
71 throws SQLException {
72 QueryRunner runner = new QueryRunner();
73 MapListHandler handler = new MapListHandler();
74 return runner.query(conn, strSqlCommand, handler, parameters);
75 }
76
77 /***
78 * 记录保存
79 *
80 * @param conn
81 * @param mapData
82 * @param objectName
83 * @return
84 * @throws SQLException
85 */
86 public <T> T save(Connection conn, Map<String, Object> mapData, String objectName) throws SQLException {
87 if (!mapData.containsKey("update_time") || mapData.get("update_time") == null) {
88 mapData.put("update_time", new Date());
89 }
90 if (!mapData.containsKey("create_time") || mapData.get("create_time") == null) {
91 mapData.put("create_time", new Date());
92 }
93 Iterator<String> it = mapData.keySet().iterator();
94
95 String key;
96 StringBuilder sbInsert = new StringBuilder();
97 sbInsert.append("INSERT INTO ").append(objectName);
98
99 List<Object> valueList = new ArrayList<>();
100 List<String> filedNameList = new ArrayList<>();
101 List<String> preValueList = new ArrayList<>();
102
103 while (it.hasNext()) {
104 key = it.next();
105 filedNameList.add(key);
106 preValueList.add("?");
107 valueList.add(mapData.get(key));
108 }
109 sbInsert.append(" ( `").append(StringUtils.collectionToDelimitedString(filedNameList, "`,`"))
110 .append("` ) VALUES ( ").append(StringUtils.collectionToDelimitedString(preValueList, ",")).append(")");
111 QueryRunner run = new QueryRunner();
112
113 return run.insert(conn, sbInsert.toString(), new InsertResultHandler<T>(), valueList.toArray());
114 }
115
116 private class InsertResultHandler<T> implements ResultSetHandler<T> {
117 @SuppressWarnings("unchecked")
118 @Override
119 public T handle(ResultSet rs) throws SQLException {
120 T t;
121 if (rs.next()) {
122 t = (T) rs.getObject(1);
123 } else {
124 // throw new NoIdGeneratedException("No id generated from database...");
125 return null;
126 }
127 return t;
128 }
129 }
130
131 /**
132 * 记录更新
133 *
134 * @param conn
135 * @param mapData
136 * @param objectName
137 * @param strPrimaryKey
138 * @return
139 * @throws SQLException
140 */
141 public long update(Connection conn, Map<String, Object> mapData, String objectName, String strPrimaryKey)
142 throws SQLException {
143 if (!mapData.containsKey("update_time") || mapData.get("update_time") == null) {
144 mapData.put("update_time", new Date());
145 }
146
147 Iterator<String> it = mapData.keySet().iterator();
148 String key;
149 List<Object> valList = new ArrayList<>();
150 StringBuffer updateSql = new StringBuffer(128);
151 updateSql.append("UPDATE ").append(objectName).append(" SET ");
152 while (it.hasNext()) {
153 key = it.next();
154 if (key.equalsIgnoreCase(strPrimaryKey)) {
155 continue;
156 }
157 updateSql.append("`" + key + "`").append("=?,");
158 valList.add(mapData.get(key));
159 }
160 updateSql.deleteCharAt(updateSql.length() - 1);
161 updateSql.append(" WHERE `" + strPrimaryKey + "`= ? ");
162 valList.add(mapData.get(strPrimaryKey));
163 return doExecute(conn, updateSql.toString(), valList.toArray());
164 }
165
166 /**
167 * sql执行
168 *
169 * @param conn
170 * @param sql
171 * @param parameters
172 * @return
173 * @throws SQLException
174 */
175 public long doExecute(Connection conn, String sql, Object... parameters) throws SQLException {
176 QueryRunner runner = new QueryRunner();
177 return runner.update(conn, sql, parameters);
178 }
179
180 /**
181 * 按主键删除记录
182 *
183 * @param conn
184 * @param objectName
185 * @param id
186 * @return
187 */
188 public int deleteById(Connection conn, String objectName, String id) throws SQLException {
189 String sql = "DELETE FROM " + objectName + " WHERE id = ? ";
190 QueryRunner runner = new QueryRunner();
191 return runner.update(conn, sql, id);
192 }
193
194 public void beginTransaction(Connection connection) throws Exception {
195 connection.setAutoCommit(false);
196 connection.setReadOnly(false);
197 }
198
199 public void commitTransaction(Connection connection) throws SQLException {
200 if (!connection.getAutoCommit()) {
201 connection.commit();
202 }
203 }
204
205 public void rollbackTransaction(Connection connection) throws SQLException {
206 if (!connection.getAutoCommit()) {
207 connection.rollback();
208 }
209 }
210 }
1 package com.topdraw.platform.util;
2
3 /*
4 MessageDigest md = MessageDigest.getInstance("SHA");
5
6 try {
7 md.update(toChapter1);
8 MessageDigest tc1 = md.clone();
9 byte[] toChapter1Digest = tc1.digest();
10 md.update(toChapter2);
11 ...etc.
12 } catch (CloneNotSupportedException cnse) {
13 throw new DigestException("couldn't make digest of partial content");
14 }
15 */
16
17 import org.apache.commons.codec.binary.Hex;
18 import org.apache.tomcat.util.codec.binary.Base64;
19
20 import java.io.UnsupportedEncodingException;
21 import java.security.MessageDigest;
22 import java.security.NoSuchAlgorithmException;
23
24 /**
25 * @author zehui.zeng
26 * @date 13-3-17 下午9:23
27 */
28 public class MD5Util {
29 private final String algorithm;
30 private boolean encodeHashAsBase64 = false;
31 private static MD5Util md5 = null;
32
33 /**
34 * The digest algorithm to use
35 * Supports the named <a href="http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html#AppA">
36 * Message Digest Algorithms</a> in the Java environment.
37 *
38 * @param algorithm
39 */
40 public MD5Util(String algorithm) {
41 this(algorithm, false);
42 }
43
44 public MD5Util(){
45 this.algorithm = "MD5";
46 }
47
48 /**
49 * Convenience constructor for specifying the algorithm and whether or not to enable base64 encoding
50 *
51 * @param algorithm
52 * @param encodeHashAsBase64
53 * @throws IllegalArgumentException if an unknown
54 */
55 public MD5Util(String algorithm, boolean encodeHashAsBase64) throws IllegalArgumentException {
56 this.algorithm = algorithm;
57 setEncodeHashAsBase64(encodeHashAsBase64);
58 //Validity Check
59 getMessageDigest();
60 }
61
62 public static String encodePassword(String passwd){
63 if(md5 == null){
64 md5 = new MD5Util();
65 }
66 return md5.encodePassword(passwd, "");
67 }
68
69
70
71 /**
72 * Encodes the rawPass using a MessageDigest.
73 * If a salt is specified it will be merged with the password before encoding.
74 *
75 * @param rawPass The plain text password
76 * @param salt The salt to sprinkle
77 * @return Hex string of password digest (or base64 encoded string if encodeHashAsBase64 is enabled.
78 */
79 public String encodePassword(String rawPass, Object salt) {
80 String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
81
82 MessageDigest messageDigest = getMessageDigest();
83
84 byte[] digest;
85
86 try {
87 digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
88 } catch (UnsupportedEncodingException e) {
89 throw new IllegalStateException("UTF-8 not supported!");
90 }
91
92 if (getEncodeHashAsBase64()) {
93 return new String(Base64.encodeBase64(digest));
94 } else {
95 return new String(Hex.encodeHex(digest));
96 }
97 }
98
99 /**
100 * Get a MessageDigest instance for the given algorithm.
101 * Throws an IllegalArgumentException if <i>algorithm</i> is unknown
102 *
103 * @return MessageDigest instance
104 * @throws IllegalArgumentException if NoSuchAlgorithmException is thrown
105 */
106 protected final MessageDigest getMessageDigest() throws IllegalArgumentException {
107 try {
108 return MessageDigest.getInstance(algorithm);
109 } catch (NoSuchAlgorithmException e) {
110 throw new IllegalArgumentException("No such algorithm [" + algorithm + "]");
111 }
112 }
113
114 /**
115 * Takes a previously encoded password and compares it with a rawpassword after mixing in the salt and
116 * encoding that value
117 *
118 * @param encPass previously encoded password
119 * @param rawPass plain text password
120 * @param salt salt to mix into password
121 * @return true or false
122 */
123 public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
124 String pass1 = "" + encPass;
125 String pass2 = encodePassword(rawPass, salt);
126
127 return pass1.equals(pass2);
128 }
129
130
131 /**
132 * Used by subclasses to extract the password and salt from a merged <code>String</code> created using
133 * {@link #mergePasswordAndSalt(String,Object,boolean)}.<p>The first element in the returned array is the
134 * password. The second element is the salt. The salt array element will always be present, even if no salt was
135 * found in the <code>mergedPasswordSalt</code> argument.</p>
136 *
137 * @param mergedPasswordSalt as generated by <code>mergePasswordAndSalt</code>
138 *
139 * @return an array, in which the first element is the password and the second the salt
140 *
141 * @throws IllegalArgumentException if mergedPasswordSalt is null or empty.
142 */
143 protected String[] demergePasswordAndSalt(String mergedPasswordSalt) {
144 if ((mergedPasswordSalt == null) || "".equals(mergedPasswordSalt)) {
145 throw new IllegalArgumentException("Cannot pass a null or empty String");
146 }
147
148 String password = mergedPasswordSalt;
149 String salt = "";
150
151 int saltBegins = mergedPasswordSalt.lastIndexOf("{");
152
153 if ((saltBegins != -1) && ((saltBegins + 1) < mergedPasswordSalt.length())) {
154 salt = mergedPasswordSalt.substring(saltBegins + 1, mergedPasswordSalt.length() - 1);
155 password = mergedPasswordSalt.substring(0, saltBegins);
156 }
157
158 return new String[] {password, salt};
159 }
160
161 /**
162 * Used by subclasses to generate a merged password and salt <code>String</code>.<P>The generated password
163 * will be in the form of <code>password{salt}</code>.</p>
164 * <p>A <code>null</code> can be passed to either method, and will be handled correctly. If the
165 * <code>salt</code> is <code>null</code> or empty, the resulting generated password will simply be the passed
166 * <code>password</code>. The <code>toString</code> method of the <code>salt</code> will be used to represent the
167 * salt.</p>
168 *
169 * @param password the password to be used (can be <code>null</code>)
170 * @param salt the salt to be used (can be <code>null</code>)
171 * @param strict ensures salt doesn't contain the delimiters
172 *
173 * @return a merged password and salt <code>String</code>
174 *
175 * @throws IllegalArgumentException if the salt contains '{' or '}' characters.
176 */
177 protected String mergePasswordAndSalt(String password, Object salt, boolean strict) {
178 if (password == null) {
179 password = "";
180 }
181
182 if (strict && (salt != null)) {
183 if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
184 throw new IllegalArgumentException("Cannot use { or } in salt.toString()");
185 }
186 }
187
188 if ((salt == null) || "".equals(salt)) {
189 return password;
190 } else {
191 return password + "{" + salt.toString() + "}";
192 }
193 }
194
195 public String getAlgorithm() {
196 return algorithm;
197 }
198
199 public boolean getEncodeHashAsBase64() {
200 return encodeHashAsBase64;
201 }
202
203 /**
204 * The encoded password is normally returned as Hex (32 char) version of the hash bytes. Setting this
205 * property to true will cause the encoded pass to be returned as Base64 text, which will consume 24 characters.
206 *
207 * @param encodeHashAsBase64 set to true for Base64 output
208 */
209 public void setEncodeHashAsBase64(boolean encodeHashAsBase64) {
210 this.encodeHashAsBase64 = encodeHashAsBase64;
211 }
212
213 public static void main(String[] args){
214 System.out.println(MD5Util.encodePassword("system1"));
215 }
216
217
218 }
1 package com.topdraw.platform.util;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.beans.factory.annotation.Value;
5 import org.springframework.mail.SimpleMailMessage;
6 import org.springframework.mail.javamail.JavaMailSender;
7 import org.springframework.stereotype.Component;
8
9 @Component
10 public class MailUtil {
11
12 @Autowired
13 private JavaMailSender javaMailSender;
14
15 @Value("${spring.mail.username}")
16 private String from;
17
18 @Value("${spring.mail.developer-mail-address}")
19 private String to;
20
21 public void sendSimpleMail(String subject, String text) {
22 SimpleMailMessage message = new SimpleMailMessage();
23 message.setFrom(from);
24 message.setTo(to);
25 message.setSubject(subject);
26 message.setText(text);
27 javaMailSender.send(message);
28 }
29 }
1 package com.topdraw.platform.util;
2
3
4 import lombok.extern.slf4j.Slf4j;
5
6 import javax.net.ssl.HttpsURLConnection;
7 import javax.net.ssl.SSLContext;
8 import javax.net.ssl.SSLSocketFactory;
9 import javax.net.ssl.TrustManager;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.*;
13 import java.net.HttpURLConnection;
14 import java.net.URL;
15 import java.net.URLConnection;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Set;
19
20
21 /**
22 * 通过HTTP协议 访问服务器
23 *
24 * @author LucaMa
25 *
26 */
27 @Slf4j
28 public class WebUtil {
29 public static boolean LOG = false;
30
31 /**
32 * 向指定URL发送GET方法的请求
33 *
34 * @param url
35 * 发送请求的URL
36 * @param param
37 * 请求参数,请求参数应该是name1=value1&name2=value2的形式。
38 * @return URL所代表远程资源的响应
39 */
40 public static String sendGet(String url, boolean needRedirect) {
41 return sendGet(url, null, "UTF-8", null, needRedirect);
42 }
43
44 public static String sendGet(String url, String param, String charset) {
45 return sendGet(url, param, charset, null, true);
46 }
47
48 public static String sendGet(String url, String param, String charset, Integer timeout) {
49 return sendGet(url, param, charset, timeout, timeout, true);
50 }
51
52 public static String sendGet(String url, String param, String charset, Integer timeout, boolean needRedirect) {
53 return sendGet(url, param, charset, timeout, timeout, needRedirect);
54 }
55
56 public static String sendGet(String url, String param, String charset, Integer connectTimeout,
57 Integer readTimeout) {
58 return sendGet(url, param, charset, connectTimeout, readTimeout, true);
59 }
60
61 public static String sendGet(String url, String param, String charset, Integer connectTimeout,Integer readTimeout,boolean needRedirect) {
62 String result = "";
63 StringBuilder sbResult = new StringBuilder();
64 BufferedReader in = null;
65 try {
66 String urlName = url + ((null != param && !"".equals(param)) ? ("?" + param) : "");
67 URL realUrl = new URL(urlName);
68 // 打开和URL之间的连接
69 HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
70 // 设置通用的请求属性
71 conn.setInstanceFollowRedirects(needRedirect);
72 conn.setRequestProperty("accept", "*/*");
73 conn.setRequestProperty("charset", charset);
74 if (null != connectTimeout && connectTimeout > 0) {
75 conn.setConnectTimeout(connectTimeout);
76 }
77 if (null != readTimeout && readTimeout > 0) {
78 conn.setReadTimeout(readTimeout);
79 }
80 //conn.setRequestProperty("charset", conn.setRequestProperty("charset", charset);;);
81 conn.setRequestProperty("connection", "Keep-Alive");
82 conn.setRequestProperty("user-agent",
83 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
84 // 建立实际的连接
85 conn.connect();
86 // 获取所有响应头字段
87 Map<String, List<String>> map = conn.getHeaderFields();
88 // 遍历所有的响应头字段
89 for (String key : map.keySet()) {
90 if(LOG){
91 log.info(key + "--->" + map.get(key));
92 }
93 }
94 // 定义BufferedReader输入流来读取URL的响应
95 in = new BufferedReader(
96 new InputStreamReader(conn.getInputStream(),charset));
97 String line;
98 while ((line = in.readLine()) != null) {
99 sbResult.append(line).append("\n");
100 }
101 if (null != sbResult && sbResult.length() > 0) {
102 sbResult.setLength(sbResult.length() - 1);
103 }
104 result = sbResult.toString();
105 } catch (Exception e) {
106 //System.out.println("发送GET请求出现异常!" + e);
107 e.printStackTrace();
108 //throw e;
109 }
110 // 使用finally块来关闭输入流
111 finally {
112 try {
113 if (in != null) {
114 in.close();
115 }
116 } catch (IOException ex) {
117 ex.printStackTrace();
118 }
119 }
120 return result;
121 }
122
123
124 public static String sendGet(String url, Map<String,String> mapParam , String charset) {
125 StringBuilder sbParam=new StringBuilder("");
126 int i1=0;
127 Set<String> setKey=mapParam.keySet();
128 for (String strKey : setKey ) {
129
130 sbParam.append(strKey).append("=").append(mapParam.get(strKey));
131 if (i1<setKey.size()-1){
132 sbParam.append("&");
133 }
134 i1++;
135 }
136 return sendGet(url, sbParam.toString(), charset);
137 }
138
139
140 /**
141 * 向指定URL发送POST方法的请求
142 *
143 * @param url
144 * 发送请求的URL
145 * @param param
146 * 请求参数,请求参数应该是name1=value1&name2=value2的形式。
147 * @return URL所代表远程资源的响应
148 */
149 public static String sendPost(String url, String param , String charset, String contentType) {
150 PrintWriter out = null;
151 BufferedReader in = null;
152 String result = "";
153 StringBuilder sbResult = new StringBuilder();
154 try {
155 URL realUrl = new URL(url);
156 // 打开和URL之间的连接
157 URLConnection conn = realUrl.openConnection();
158 // 设置通用的请求属性
159 conn.setRequestProperty("accept", "*/*");
160 conn.setRequestProperty("charset", charset);
161
162 if (null!=contentType && !contentType.isEmpty()){
163 conn.setRequestProperty("Content-Type",contentType);
164 }
165 conn.setRequestProperty("connection", "Keep-Alive");
166 conn.setRequestProperty("user-agent",
167 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
168 // 发送POST请求必须设置如下两行
169 conn.setDoOutput(true);
170 conn.setDoInput(true);
171 // 获取URLConnection对象对应的输出流
172 out = new PrintWriter(conn.getOutputStream());
173
174
175 // 发送请求参数
176 out.print(new String(param.getBytes(charset)));
177 // flush 输出流的缓冲
178 out.flush();
179 // 定义BufferedReader输入流来读取URL的响应
180 in = new BufferedReader(
181 new InputStreamReader(conn.getInputStream(),charset));
182 String line;
183 while ((line = in.readLine()) != null) {
184 sbResult.append(line).append("\n");
185 }
186 if (null != sbResult && sbResult.length() > 0) {
187 sbResult.setLength(sbResult.length() - 1);
188 }
189 result = sbResult.toString();
190 } catch (Exception e) {
191 //System.out.println("发送POST 请求出现异常!" + e);
192 e.printStackTrace();
193
194 }
195 // 使用finally块来关闭输出流、输入流.
196 finally {
197
198 try {
199 if (out != null) {
200 out.close();
201 }
202 if (in != null) {
203 in.close();
204 }
205 } catch (IOException ex) {
206 ex.printStackTrace();
207 }
208 }
209 return result;
210 }
211
212 public static String sendPost(String url, Map<String,String> mapParam , String charset,String contentType) {
213
214 StringBuilder sbParam=new StringBuilder("");
215 int i1=0;
216 Set<String> setKey=mapParam.keySet();
217 for (String strKey : setKey ) {
218
219 sbParam.append(strKey).append("=").append(mapParam.get(strKey));
220 if (i1<setKey.size()-1){
221 sbParam.append("&");
222 }
223 i1++;
224 }
225
226 return sendPost(url, sbParam.toString(), charset,contentType);
227 }
228
229
230
231
232
233
234 //////////////////////////////////////////////////以下新版////////////////////////////////////////////
235
236
237
238
239
240 /**
241 * 新版本的 GET请求
242 *
243 * @param strURL
244 * 发送请求的URL
245 * @param strParam
246 * 请求参数,应该是name1=value1&name2=value2的形式。
247 * @thows Exception
248 *
249 * @return URL所代表远程资源的响应
250 */
251 public static String sendGet(String strURL, String strParam, Map<String,String> mapHeader ) throws Exception {
252
253 String strResult = "";
254 BufferedReader brIn = null;
255 try {
256 String strFullURL = strURL + (null != strParam ? ("?" + strParam) : "");
257 URL url = new URL(strFullURL);
258 // 打开和URL之间的连接
259 //URLConnection conn = urlReal.openConnection();
260 HttpURLConnection connHttps = (HttpURLConnection)url.openConnection();
261
262 connHttps.setRequestMethod("GET");
263
264 connHttps.setUseCaches(false);
265
266 // 设置通用的请求属性
267 connHttps.setRequestProperty("Accept", "*/*");
268 connHttps.setRequestProperty("Charset", "UTF-8");
269 connHttps.setRequestProperty("Connection", "Keep-Alive");
270 connHttps.setRequestProperty("User-Agent", "Server(Java) WebUtil");
271
272 if (null!=mapHeader && !mapHeader.isEmpty()){
273 for(String strKey:mapHeader.keySet()){
274 String strValue=mapHeader.get(strKey);
275
276 char cFirst = strKey.charAt(0);
277 if(cFirst < 65 || cFirst > 90){ //不是大写开头
278 //System.out.println( new StringBuilder("A http header parameter '").append(strKey).append("' isn't start with capital letter.."));
279 }
280 if (null!=strValue && !strValue.isEmpty()){
281 connHttps.setRequestProperty(strKey, strValue);
282
283 }
284 }
285 }
286
287
288 //得到实际使用的Charset
289 String strCharset=mapHeader.get("Charset");
290 if (null==strCharset || strCharset.isEmpty()){
291 strCharset=mapHeader.get("charset");
292 if (null==strCharset || strCharset.isEmpty()){
293 strCharset="UTF-8";
294 }
295 }
296
297
298 // 建立实际的连接
299 connHttps.connect();
300
301
302 brIn = new BufferedReader(
303 new InputStreamReader(connHttps.getInputStream(),strCharset));
304 String strLine;
305
306 StringBuilder sbResult=new StringBuilder();
307
308 while ((strLine = brIn.readLine()) != null) {
309 sbResult.append("\n").append(strLine); //readLine不包含换行符
310 }
311 connHttps.disconnect();
312 strResult=sbResult.toString();
313
314
315 } catch (Exception e) {
316 //System.out.println("发送GET请求出现异常!" + e);
317 throw new IOException("WebUtil发送GET请求异常",e);
318 //e.printStackTrace();
319 //throw e;
320 } finally {// 使用finally块来关闭输入流
321 try {
322 if (brIn != null) {
323 brIn.close();
324 brIn=null;
325 }
326 } catch (IOException ex) {
327 ex.printStackTrace();
328 }
329 }
330 return strResult;
331 }
332
333 public static String sendGet(String strUrl, Map<String,String> mapParam, Map<String,String> mapHeader) throws Exception {
334 StringBuilder sbParam=new StringBuilder("");
335 int i1=0;
336 Set<String> setKey=mapParam.keySet();
337 for (String strKey : setKey ) {
338
339 sbParam.append(strKey).append("=").append(mapParam.get(strKey));
340 if (i1<setKey.size()-1){
341 sbParam.append("&");
342 }
343 i1++;
344 }
345 return sendGet(strUrl, sbParam.toString(), mapHeader);
346 }
347
348 public static String sendPost(String strUrl, Map<String, String> mapParam, Map<String, String> mapHeader)
349 throws Exception {
350 return sendPost(strUrl, mapParam, mapHeader, 5000);
351 }
352
353 public static String sendPost(String strUrl, String strParam, Map<String, String> mapHeader) throws Exception {
354 return sendPost(strUrl, strParam, mapHeader, 5000);
355 }
356
357 /**
358 * 新版的 POST请求
359 *
360 * @param url
361 * 发送请求的URL
362 * @param param
363 * 请求参数,请求参数应该是name1=value1&name2=value2的形式。
364 * @return URL所代表远程资源的响应
365 */
366 public static String sendPost(String strUrl, String strParam , Map<String,String> mapHeader, Integer timeout) throws Exception {
367 PrintWriter brOut = null;
368 BufferedReader brIn = null;
369 String strResult = "";
370 try {
371 System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
372 URL realUrl = new URL(strUrl);
373 // 打开和URL之间的连接
374 //URLConnection conn = realUrl.openConnection();
375 HttpURLConnection connHttps = (HttpURLConnection)realUrl.openConnection();
376 if (null != timeout) {
377 connHttps.setConnectTimeout(timeout);
378 connHttps.setReadTimeout(timeout);
379 }
380 connHttps.setRequestMethod("POST");
381 connHttps.setUseCaches(false);
382
383 // 设置默认通用的请求属性
384 connHttps.setRequestProperty("Accept", "*/*");
385 connHttps.setRequestProperty("Charset", "UTF-8");
386 connHttps.setRequestProperty("Connection", "Keep-Alive");
387 connHttps.setRequestProperty("User-Agent", "Server(Java) WebUtil");
388
389 if (null!=mapHeader && !mapHeader.isEmpty()){
390 for(String strKey:mapHeader.keySet()){
391 String strValue=mapHeader.get(strKey);
392
393 char cFirst = strKey.charAt(0);
394 if(cFirst < 65 || cFirst > 90){ //不是大写开头
395 //System.out.println( new StringBuilder("A http header parameter '").append(strKey).append("' isn't start with capital letter.."));
396 }
397 if (null!=strValue && !strValue.isEmpty()){
398 connHttps.setRequestProperty(strKey, strValue);
399
400 }
401 }
402 }
403
404 /*
405 if (null!=contentType && !contentType.isEmpty()){
406 conn.setRequestProperty("Content-Type",contentType);
407 }*/
408
409 // 发送POST请求必须设置如下两行
410 connHttps.setDoOutput(true);
411 connHttps.setDoInput(true);
412 // 获取URLConnection对象对应的输出流
413 brOut = new PrintWriter(connHttps.getOutputStream());
414
415
416 //得到实际使用的Charset
417 String strCharset=mapHeader.get("Charset");
418 if (null==strCharset || strCharset.isEmpty()){
419 strCharset=mapHeader.get("charset");
420 if (null==strCharset || strCharset.isEmpty()){
421 strCharset="UTF-8";
422 }
423 }
424
425 // 发送请求参数
426 brOut.print(new String(strParam.getBytes(strCharset)));
427 // flush 输出流的缓冲
428 brOut.flush();
429
430 //System.out.println(connHttps.getResponseCode());
431
432 // 定义BufferedReader输入流来读取URL的响应
433 brIn = new BufferedReader(
434 new InputStreamReader(connHttps.getInputStream(),strCharset));
435 String strLine;
436
437 StringBuilder sbResult=new StringBuilder();
438
439 while ((strLine = brIn.readLine()) != null) {
440 sbResult.append(strLine).append("\n"); //readLine不包含换行符
441 }
442 if (null != sbResult && sbResult.length() > 0) {
443 sbResult.setLength(sbResult.length() - 1);
444 }
445 connHttps.disconnect();
446 strResult=sbResult.toString();
447
448
449 } catch (Exception e) {
450 e.printStackTrace();
451 throw e;
452 }finally {// 使用finally块来关闭输出流、输入流.
453
454 try {
455 if (brOut != null) {
456 brOut.close();
457 brOut=null;
458 }
459 if (brIn != null) {
460 brIn.close();
461 brIn=null;
462 }
463 } catch (IOException ex) {
464 ex.printStackTrace();
465 }
466 }
467 return strResult;
468 }
469
470 public static String sendPost(String url, Map<String,String> mapParam ,Map<String,String> mapHeader, Integer timeout) throws Exception {
471
472 StringBuilder sbParam=new StringBuilder("");
473 int i1=0;
474 Set<String> setKey=mapParam.keySet();
475 for (String strKey : setKey ) {
476
477 sbParam.append(strKey).append("=").append(mapParam.get(strKey));
478 if (i1<setKey.size()-1){
479 sbParam.append("&");
480 }
481 i1++;
482 }
483
484 return sendPost(url, sbParam.toString(), mapHeader, timeout);
485 }
486
487
488
489
490
491 /**
492 * 安全的 Get 请求
493 *
494 *
495 *
496 **/
497 public static String sendSecureGet(String strURL, String strParam, Map<String,String> mapHeader
498 ,TrustManager tmIn) throws Exception {
499
500 BufferedReader brIn=null;
501 String strResult=null;
502
503 try {
504
505 // 创建SSLContext对象,并使用指定的信任管理器初始化
506 TrustManager[] arrayTM = { tmIn };
507 SSLContext sslc = SSLContext.getInstance("SSL", "SunJSSE");
508 sslc.init(null, arrayTM, new java.security.SecureRandom());
509 // 从上述SSLContext对象中得到SSLSocketFactory对象
510 SSLSocketFactory sslsf = sslc.getSocketFactory();
511
512 URL urlHttps = new URL(strURL);
513 HttpsURLConnection connHttps = (HttpsURLConnection)(urlHttps.openConnection());
514 connHttps.setSSLSocketFactory(sslsf);
515
516 //设置请求方式(GET/POST)
517 connHttps.setRequestMethod("GET");
518
519 connHttps.setUseCaches(false);
520
521 //设置通用的请求属性
522 connHttps.setRequestProperty("Accept", "*/*");
523 connHttps.setRequestProperty("Charset", "UTF-8");
524 connHttps.setRequestProperty("Connection", "Keep-Alive");
525 connHttps.setRequestProperty("User-Agent", "Server(Java) WebUtil");
526
527 if (null!=mapHeader && !mapHeader.isEmpty()){
528 for(String strKey:mapHeader.keySet()){
529 String strValue=mapHeader.get(strKey);
530
531 char cFirst = strKey.charAt(0);
532 if(cFirst < 65 || cFirst > 90){ //不是大写开头
533 //System.out.println( new StringBuilder("A http header parameter '").append(strKey).append("' isn't start with capital letter.."));
534 }
535 if (null!=strValue && !strValue.isEmpty()){
536 connHttps.setRequestProperty(strKey, strValue);
537
538 }
539 }
540 }
541
542
543 //得到实际使用的Charset
544 String strCharset=mapHeader.get("Charset");
545 if (null==strCharset || strCharset.isEmpty()){
546 strCharset=mapHeader.get("charset");
547 if (null==strCharset || strCharset.isEmpty()){
548 strCharset="UTF-8";
549 }
550 }
551
552
553 // 建立实际的连接
554 connHttps.connect();
555
556
557 // 定义BufferedReader输入流来读取URL的响应
558 brIn = new BufferedReader(
559 new InputStreamReader(connHttps.getInputStream(),strCharset));
560 String strLine;
561
562 StringBuilder sbResult=new StringBuilder();
563
564 while ((strLine = brIn.readLine()) != null) {
565 sbResult.append("\n").append(strLine); //readLine不包含换行符
566 }
567 connHttps.disconnect();
568 strResult=sbResult.toString();
569
570 } catch (Exception e) {
571 throw new IOException("WebUtil发送安全的GET请求异常",e);
572 } finally {// 使用finally块来关闭输出流、输入流.
573 try {
574 if (brIn != null) {
575 brIn.close();
576 brIn=null;
577 }
578 } catch (IOException ex) {
579 ex.printStackTrace();
580 }
581 }
582 return strResult;
583 }
584
585 public static String sendSecureGet(String strUrl, Map<String,String> mapParam, Map<String,String> mapHeader,TrustManager tmIn) throws Exception {
586 StringBuilder sbParam=new StringBuilder("");
587 int i1=0;
588 Set<String> setKey=mapParam.keySet();
589 for (String strKey : setKey ) {
590
591 sbParam.append(strKey).append("=").append(mapParam.get(strKey));
592 if (i1<setKey.size()-1){
593 sbParam.append("&");
594 }
595 i1++;
596 }
597 return sendSecureGet(strUrl, sbParam.toString(), mapHeader,tmIn);
598 }
599
600
601 /**
602 * 安全的 Post 请求
603 *
604 *
605 *
606 **/
607 public static String sendSecurePost(String strURL, String strParam, Map<String,String> mapHeader
608 ,TrustManager tmIn) throws Exception {
609
610 BufferedReader brIn=null;
611 PrintWriter brOut=null;
612 String strResult=null;
613
614 try {
615
616 // 创建SSLContext对象,并使用指定的信任管理器初始化
617 TrustManager[] arrayTM = { tmIn };
618 SSLContext sslc = SSLContext.getInstance("SSL", "SunJSSE");
619 sslc.init(null, arrayTM, new java.security.SecureRandom());
620 // 从上述SSLContext对象中得到SSLSocketFactory对象
621 SSLSocketFactory sslsf = sslc.getSocketFactory();
622
623 URL urlHttps = new URL(strURL);
624 HttpsURLConnection connHttps = (HttpsURLConnection)(urlHttps.openConnection());
625 connHttps.setSSLSocketFactory(sslsf);
626
627 //设置请求方式(GET/POST)
628 connHttps.setRequestMethod("POST");
629
630 //设置POST所需配置
631 connHttps.setDoOutput(true);
632 connHttps.setDoInput(true);
633
634 connHttps.setUseCaches(false);
635
636 //设置通用的请求属性
637 connHttps.setRequestProperty("Accept", "*/*");
638 connHttps.setRequestProperty("Charset", "UTF-8");
639 connHttps.setRequestProperty("Connection", "Keep-Alive");
640 connHttps.setRequestProperty("User-Agent", "Server(Java) WebUtil");
641
642 if (null!=mapHeader && !mapHeader.isEmpty()){
643 for(String strKey:mapHeader.keySet()){
644 String strValue=mapHeader.get(strKey);
645
646 char cFirst = strKey.charAt(0);
647 if(cFirst < 65 || cFirst > 90){ //不是大写开头
648 //System.out.println( new StringBuilder("A http header parameter '").append(strKey).append("' isn't start with capital letter.."));
649 }
650 if (null!=strValue && !strValue.isEmpty()){
651 connHttps.setRequestProperty(strKey, strValue);
652
653 }
654 }
655 }
656
657 //得到实际使用的Charset
658 String strCharset=mapHeader.get("Charset");
659 if (null==strCharset || strCharset.isEmpty()){
660 strCharset=mapHeader.get("charset");
661 if (null==strCharset || strCharset.isEmpty()){
662 strCharset="UTF-8";
663 }
664 }
665
666 // 获取URLConnection对象对应的输出流
667 brOut = new PrintWriter(connHttps.getOutputStream());
668
669 // 发送请求参数
670 if (null!=strParam){
671 brOut.print(new String(strParam.getBytes(strCharset)));
672 brOut.flush();
673 }
674
675
676 // 定义BufferedReader输入流来读取URL的响应
677 brIn = new BufferedReader(new InputStreamReader(connHttps.getInputStream(),strCharset));
678 String strLine;
679
680 StringBuilder sbResult=new StringBuilder();
681
682 while ((strLine = brIn.readLine()) != null) {
683 sbResult.append("\n").append(strLine); //readLine不包含换行符
684 }
685 connHttps.disconnect();
686 strResult=sbResult.toString();
687
688 } catch (Exception e) {
689 throw new IOException("WebUtil发送安全的POST请求异常",e);
690 } finally { // 使用finally块来关闭输出流、输入流.
691 try {
692 if (brIn != null) {
693 brIn.close();
694 brIn=null;
695 }
696 if (brOut != null) {
697 brOut.close();
698 brOut=null;
699 }
700 } catch (IOException ex) {
701 ex.printStackTrace();
702 }
703 }
704 return strResult;
705 }
706
707 public static String sendSecurePost(String url, Map<String,String> mapParam ,Map<String,String> mapHeader,TrustManager tmIn) throws Exception {
708
709 StringBuilder sbParam=new StringBuilder("");
710 int i1=0;
711 Set<String> setKey=mapParam.keySet();
712 for (String strKey : setKey ) {
713
714 sbParam.append(strKey).append("=").append(mapParam.get(strKey));
715 if (i1<setKey.size()-1){
716 sbParam.append("&");
717 }
718 i1++;
719 }
720
721 return sendSecurePost(url, sbParam.toString(), mapHeader,tmIn);
722 }
723
724
725 /**
726 * 获取请求的PostBody
727 *
728 *
729 *
730 **/
731 public static String getPostBody(HttpServletRequest request)
732 throws IOException {
733 // 解析结果存储在HashMap
734 //Map<String, Object> map = new HashMap<String, Object>();
735 String str = "";
736 BufferedReader reader = null;
737 try {
738 StringBuilder buffer = new StringBuilder();
739 reader = new BufferedReader(new InputStreamReader(
740 request.getInputStream(), "UTF-8"));
741 String line = null;
742 while ((line = reader.readLine()) != null) {
743 buffer.append(line);
744 }
745 str = buffer.toString();
746 //map = JSONUtil.json2map(str);
747 } catch (Exception e) {
748 e.printStackTrace();
749 } finally {
750 if (null != reader) {
751 try {
752 reader.close();
753 } catch (IOException e) {
754 e.printStackTrace();
755 }
756 }
757
758 }
759
760 return str;
761 }
762
763 /**
764 * 向指定 URL 发送POST方法 发送PostBody
765 *
766 * @param url
767 *
768 * @param param
769 *
770 * @return
771 */
772 /*
773 @Deprecated
774 public static String sendPost(String url, String param) {
775 PrintWriter out = null;
776 BufferedReader in = null;
777 String result = "";
778 try {
779 URL realUrl = new URL(url);
780 // 打开和URL之间的连接
781 URLConnection conn = realUrl.openConnection();
782 // 设置通用的请求属性
783 conn.setRequestProperty("accept", "* /*");
784 conn.setRequestProperty("connection", "Keep-Alive");
785 conn.setRequestProperty("user-agent",
786 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
787 // 发送POST请求必须设置如下两行
788 conn.setDoOutput(true);
789 conn.setDoInput(true);
790 // 获取URLConnection对象对应的输出流
791 out = new PrintWriter(conn.getOutputStream());
792 // 发送请求参数
793 out.print(param);
794 // flush输出流的缓冲
795 out.flush();
796 // 定义BufferedReader输入流来读取URL的响应
797 in = new BufferedReader(
798 new InputStreamReader(conn.getInputStream()));
799 String line;
800 while ((line = in.readLine()) != null) {
801 result += line;
802 }
803 } catch (ConnectException ce) {
804 System.out.println("发送 POST 请求出现异常(Connection timed out!)");
805 //logger.info(url+" (post failed)");
806 ce.printStackTrace();
807 } catch (Exception e) {
808 System.out.println("发送 POST 请求出现异常!"+e);
809 e.printStackTrace();
810 }finally{//使用finally块来关闭输出流、输入流
811 try{
812 if(out!=null){
813 out.close();
814 }
815 if(in!=null){
816 in.close();
817 }
818 }
819 catch(IOException ex){
820 ex.printStackTrace();
821 }
822 }
823 return result;
824 }*/
825
826 /**
827 * 处理用户上传
828 */
829 public static String handleUpload(HttpServletRequest request, HttpServletResponse response, String strFilePath,String strFileName)
830 throws Exception {
831 //String strFileName = request.getParameter("fileName");
832 //strFileName = new String(strFileName.getBytes("ISO-8859-1"),"UTF-8");
833 //String overFlg = request.getParameter("over"); // 0:go on;1:over
834 //System.out.println("get: " + fileName);
835 byte[] buf = new byte[4096];
836 if (strFilePath.charAt(strFilePath.length()-1)!='/'){
837 strFilePath+="/";
838 }
839 strFileName=strFilePath+strFileName;
840 File file = new File(strFileName);
841 InputStream is = null;
842 BufferedOutputStream fileOut
843 = new BufferedOutputStream(new FileOutputStream(file, true));
844 try {
845 is = request.getInputStream();
846
847 while (true) {
848 int bytesIn = is.read(buf, 0, 4096);
849 //System.out.println(bytesIn);
850 if (bytesIn == -1) {
851 break;
852 } else {
853 fileOut.write(buf, 0, bytesIn);
854 }
855 }
856
857 fileOut.flush();
858 fileOut.close();
859 //System.out.println(file.getAbsolutePath());
860 } catch (IOException e) {
861 throw e;
862 }
863 return strFileName;
864 }
865
866
867
868
869
870
871
872 }
1 spring:
2 datasource:
3 url: jdbc:mysql://139.196.192.242:3306/cms_test?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
4 username: root
5 password: Tjlh@2017
6 driver-class-name: com.mysql.jdbc.Driver
7 hikari:
8 maximum-pool-size: 10
9 minimum-idle: 5
10 idle-timeout: 180000
11 auto-commit: true
12 connection-timeout: 30000
13 connection-test-query: SELECT 1
1 spring:
2 datasource:
3 url: jdbc:mysql://139.196.192.242:3306/cms_test?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&autoReconnect=true
4 username: root
5 password: Topdraw1qaz
6 driver-class-name: com.mysql.jdbc.Driver
7 hikari:
8 maximum-pool-size: 10
9 minimum-idle: 5
10 idle-timeout: 180000
11 auto-commit: true
12 connection-timeout: 30000
13 connection-test-query: SELECT 1
1 server:
2 port: 18080
3
4 scheduler:
5 auto-bind:
6 app-enabled: true
7 service-enabled: true
8 media-online-enabled: true
9
10 cron:
11 auto-bind:
12 app: 0/10 * * * * ?
13 service: 0/10 * * * * ?
14 media-online: 0/10 * * * * ?
15
16 spring:
17 mail:
18 host: smtp.ym.163.com
19 username: test@topdraw.cn
20 password: 123456789
21 protocol: smtp
22 default-encoding: utf-8
23 developer-mail-address: wanghongyan@topdraw.cn
24
25 profiles:
26 active: dev
27
28 entity:
29 appId: 63
30 serviceId: 1
1 <?xml version="1.0" encoding="UTF-8"?>
2 <configuration scan="true" scanPeriod="60 seconds" debug="false">
3
4 <!--定义参数,后面可以通过${app.name}使用-->
5 <property name="app.name" value="cms.scheduler"/>
6 <property name="log.path" value="./logs"/>
7 <property name="log.pattern" value="%d [%thread] %-5level %logger{36} [%file : %line] - %msg%n"/>
8
9 <!--输出到控制台-->
10 <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
11 <!-- encoder 默认配置为PatternLayoutEncoder -->
12 <!--定义控制台输出格式-->
13 <encoder>
14 <pattern>%red(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}) - %msg %n</pattern>
15 <charset>utf-8</charset>
16 </encoder>
17 </appender>
18
19 <!--获取比info级别高(包括info级别)但除error级别的日志-->
20 <appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender">
21 <filter class="ch.qos.logback.classic.filter.LevelFilter">
22 <level>ERROR</level>
23 <onMatch>DENY</onMatch>
24 <onMismatch>ACCEPT</onMismatch>
25 </filter>
26 <encoder>
27 <pattern>${log.pattern}</pattern>
28 </encoder>
29 <!--滚动策略-->
30 <file>${log.path}/${app.name}-info.log</file>
31 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
32 <!--路径-->
33 <fileNamePattern>${log.path}/info/${app.name}-%d{yyyy-MM-dd}.log</fileNamePattern>
34 <maxHistory>30</maxHistory>
35 <totalSizeCap>10GB</totalSizeCap>
36 </rollingPolicy>
37 <!-- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
38 <!-- &lt;!&ndash;每个日志文件最大100MB&ndash;&gt;-->
39 <!-- <maxFileSize>100MB</maxFileSize>-->
40 <!-- </triggeringPolicy>-->
41 </appender>
42
43 <appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
44 <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
45 <level>ERROR</level>
46 </filter>
47 <encoder>
48 <pattern>${log.pattern}</pattern>
49 </encoder>
50 <!--滚动策略-->
51 <file>${log.path}/${app.name}-error.log</file>
52 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
53 <!--路径-->
54 <fileNamePattern>${log.path}/error/${app.name}-%d{yyyy-MM-dd}.log</fileNamePattern>
55 <maxHistory>30</maxHistory>
56 <totalSizeCap>10GB</totalSizeCap>
57 </rollingPolicy>
58 <!-- <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">-->
59 <!-- &lt;!&ndash;每个日志文件最大50MB&ndash;&gt;-->
60 <!-- <maxFileSize>50MB</maxFileSize>-->
61 <!-- </triggeringPolicy>-->
62 </appender>
63
64 <!--普通日志输出到控制台-->
65 <root level="info">
66 <appender-ref ref="console" />
67 <appender-ref ref="info" />
68 <appender-ref ref="error" />
69 </root>
70
71 <!--监控sql日志输出 -->
72 <logger name="jdbc.sqlonly" level="INFO" additivity="false">
73 <appender-ref ref="console" />
74 </logger>
75
76 <logger name="jdbc.resultset" level="ERROR" additivity="false">
77 <appender-ref ref="console" />
78 </logger>
79
80 <!-- 如想看到表格数据,将OFF改为INFO -->
81 <logger name="jdbc.resultsettable" level="OFF" additivity="false">
82 <appender-ref ref="console" />
83 </logger>
84
85 <logger name="jdbc.connection" level="OFF" additivity="false">
86 <appender-ref ref="console" />
87 </logger>
88
89 <logger name="jdbc.sqltiming" level="OFF" additivity="false">
90 <appender-ref ref="console" />
91 </logger>
92
93 <logger name="jdbc.audit" level="OFF" additivity="false">
94 <appender-ref ref="console" />
95 </logger>
96 </configuration>
1 package com.topdraw.platform;
2
3 import org.junit.jupiter.api.Test;
4 import org.springframework.boot.test.context.SpringBootTest;
5
6 @SpringBootTest
7 class LeviathanSchedulerApplicationTests {
8
9 @Test
10 void contextLoads() {
11 }
12
13 }