CX 7 ヶ月 前
コミット
73fb65069e
共有69 個のファイルを変更した7249 個の追加0 個の削除を含む
  1. 2 0
      META-INF/MANIFEST.MF
  2. 193 0
      pom.xml
  3. 34 0
      src/main/java/com/dashitech/Application.java
  4. 28 0
      src/main/java/com/dashitech/api/rest/ApiRest.java
  5. 43 0
      src/main/java/com/dashitech/bean/BaseBean.java
  6. 73 0
      src/main/java/com/dashitech/bean/ResultMsg.java
  7. 58 0
      src/main/java/com/dashitech/config/ApiFilterConfig.java
  8. 48 0
      src/main/java/com/dashitech/config/ApiWeblogFilterConfig.java
  9. 45 0
      src/main/java/com/dashitech/config/DataSourceConfig.java
  10. 16 0
      src/main/java/com/dashitech/config/DruidConfig.java
  11. 14 0
      src/main/java/com/dashitech/config/DruidFilter.java
  12. 22 0
      src/main/java/com/dashitech/config/JdbcTemplateConfig.java
  13. 17 0
      src/main/java/com/dashitech/config/ScheduleConfig.java
  14. 36 0
      src/main/java/com/dashitech/config/SessionFactoryConfig.java
  15. 30 0
      src/main/java/com/dashitech/config/TomcatConfig.java
  16. 32 0
      src/main/java/com/dashitech/config/WebServiceConfig.java
  17. 26 0
      src/main/java/com/dashitech/migration/BaseTask.java
  18. 19 0
      src/main/java/com/dashitech/migration/SqlTask.java
  19. 30 0
      src/main/java/com/dashitech/migration/StartApplication.java
  20. 123 0
      src/main/java/com/dashitech/migration/core/DataMapper.java
  21. 84 0
      src/main/java/com/dashitech/migration/core/DataMigrationter.java
  22. 194 0
      src/main/java/com/dashitech/migration/core/FieldMapper.java
  23. 72 0
      src/main/java/com/dashitech/migration/task/uc/GroupTask.java
  24. 44 0
      src/main/java/com/dashitech/migration/task/uc/UserTask.java
  25. 78 0
      src/main/java/com/dashitech/migration/util/JdbcRow.java
  26. 258 0
      src/main/java/com/dashitech/migration/util/JdbcUtil.java
  27. 71 0
      src/main/java/com/dashitech/redis/core/JedisPoolFactory.java
  28. 162 0
      src/main/java/com/dashitech/redis/core/RedisHashCmd.java
  29. 41 0
      src/main/java/com/dashitech/redis/core/RedisKeys.java
  30. 181 0
      src/main/java/com/dashitech/redis/core/RedisListCmd.java
  31. 46 0
      src/main/java/com/dashitech/redis/core/RedisPubSubCmd.java
  32. 5 0
      src/main/java/com/dashitech/redis/core/RedisQueueMonitor.java
  33. 149 0
      src/main/java/com/dashitech/redis/core/RedisStringCmd.java
  34. 107 0
      src/main/java/com/dashitech/utils/CaptchaUtil.java
  35. 228 0
      src/main/java/com/dashitech/utils/CaptchaUtil2.java
  36. 250 0
      src/main/java/com/dashitech/utils/CommonUtil.java
  37. 318 0
      src/main/java/com/dashitech/utils/DateUtil.java
  38. 670 0
      src/main/java/com/dashitech/utils/DateUtil2.java
  39. 49 0
      src/main/java/com/dashitech/utils/DecimalUtil.java
  40. 675 0
      src/main/java/com/dashitech/utils/FileUtil.java
  41. 372 0
      src/main/java/com/dashitech/utils/HttpUtil.java
  42. 20 0
      src/main/java/com/dashitech/utils/I18n.java
  43. 81 0
      src/main/java/com/dashitech/utils/JDBCLearn.java
  44. 120 0
      src/main/java/com/dashitech/utils/JsonParam.java
  45. 100 0
      src/main/java/com/dashitech/utils/JsonResponse.java
  46. 163 0
      src/main/java/com/dashitech/utils/JsonUtil.java
  47. 17 0
      src/main/java/com/dashitech/utils/MyObjectMapper.java
  48. 119 0
      src/main/java/com/dashitech/utils/MyObjectMapperDateFormat.java
  49. 18 0
      src/main/java/com/dashitech/utils/MyX509TrustManager.java
  50. 272 0
      src/main/java/com/dashitech/utils/OracleConn.java
  51. 49 0
      src/main/java/com/dashitech/utils/Page.java
  52. 61 0
      src/main/java/com/dashitech/utils/PortalVerifystUtils.java
  53. 506 0
      src/main/java/com/dashitech/utils/PropertiesHelper.java
  54. 179 0
      src/main/java/com/dashitech/utils/PropertiesUtil.java
  55. 69 0
      src/main/java/com/dashitech/utils/Sha1Util.java
  56. 68 0
      src/main/java/com/dashitech/utils/SpringContextHolder.java
  57. 31 0
      src/main/java/com/dashitech/utils/ThreadPoolFactory.java
  58. 131 0
      src/main/java/com/dashitech/utils/XmlToJson.java
  59. 83 0
      src/main/java/com/dashitech/utils/XmlToMap.java
  60. 32 0
      src/main/resources/application-context.xml
  61. 1 0
      src/main/resources/application-custom.properties
  62. 55 0
      src/main/resources/application.properties
  63. 22 0
      src/main/resources/banner.txt
  64. 5 0
      src/main/resources/log4j.properties
  65. 5 0
      src/main/resources/start.bat
  66. 15 0
      src/main/resources/start.sh
  67. 20 0
      src/main/resources/startCollect.sh
  68. 26 0
      src/main/webapp/WEB-INF/web.xml
  69. 38 0
      src/test/java/com/dashitech/mc/AppTest.java

+ 2 - 0
META-INF/MANIFEST.MF

@@ -0,0 +1,2 @@
1
+Manifest-Version: 1.0
2
+

+ 193 - 0
pom.xml

@@ -0,0 +1,193 @@
1
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3
+	<modelVersion>4.0.0</modelVersion>
4
+
5
+	<groupId>com.dashitech</groupId>
6
+	<artifactId>HSMSV1-DataMigration</artifactId>
7
+	<version>1.0.0</version>
8
+	<packaging>jar</packaging>
9
+
10
+	<name>HSMSV1-DataMigration</name>
11
+
12
+	<parent>
13
+		<groupId>org.springframework.boot</groupId>
14
+		<artifactId>spring-boot-starter-parent</artifactId>
15
+		<version>1.5.8.RELEASE</version>
16
+		<relativePath />
17
+	</parent>
18
+<!--	<artifactId>spring-boot-starter-logging</artifactId>
19
+	<name>Spring Boot Logging Starter</name>
20
+	<description>Starter for logging using Logback. Default logging starter</description>
21
+	<url>http://projects.spring.io/spring-boot/</url>-->
22
+	<properties>
23
+		<tomcat.version>7.0.59</tomcat.version>
24
+		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
25
+		<java.version>1.8</java.version>
26
+	</properties>
27
+
28
+	<dependencies>
29
+
30
+
31
+
32
+		<dependency>
33
+			<groupId>org.springframework.boot</groupId>
34
+			<artifactId>spring-boot-starter-test</artifactId>
35
+			<scope>test</scope>
36
+		</dependency>
37
+
38
+		<dependency>
39
+			<groupId>org.springframework.boot</groupId>
40
+			<artifactId>spring-boot-starter-web</artifactId>
41
+		</dependency>
42
+
43
+		<dependency>
44
+			<groupId>org.springframework.boot</groupId>
45
+			<artifactId>spring-boot-starter-aop</artifactId>
46
+		</dependency>
47
+
48
+		<dependency>
49
+			<groupId>org.springframework.boot</groupId>
50
+			<artifactId>spring-boot-devtools</artifactId>
51
+			<optional>true</optional>
52
+		</dependency>
53
+
54
+		<dependency>
55
+			<groupId>org.apache.commons</groupId>
56
+			<artifactId>commons-lang3</artifactId>
57
+			<version>3.3.2</version>
58
+		</dependency>
59
+
60
+		<dependency>
61
+			<groupId>net.sf.json-lib</groupId>
62
+			<artifactId>json-lib</artifactId>
63
+			<version>2.4</version>
64
+			<classifier>jdk15</classifier>
65
+		</dependency>
66
+
67
+		<dependency>
68
+			<groupId>commons-httpclient</groupId>
69
+			<artifactId>commons-httpclient</artifactId>
70
+			<version>3.0.1</version>
71
+		</dependency>
72
+
73
+		<dependency>
74
+			<groupId>org.apache.httpcomponents</groupId>
75
+			<artifactId>httpmime</artifactId>
76
+			<version>4.3.4</version>
77
+		</dependency>
78
+
79
+
80
+		<dependency>
81
+			<groupId>org.springframework</groupId>
82
+			<artifactId>spring-context-support</artifactId>
83
+			<version>4.2.4.RELEASE</version>
84
+		</dependency>
85
+
86
+
87
+
88
+		<!-- db -->
89
+		<dependency>
90
+			<groupId>org.springframework.boot</groupId>
91
+			<artifactId>spring-boot-starter-data-jpa</artifactId>
92
+			<exclusions>
93
+				<exclusion>
94
+					<groupId>javax.transaction</groupId>
95
+					<artifactId>javax.transaction-api</artifactId>
96
+				</exclusion>
97
+			</exclusions>
98
+		</dependency>
99
+
100
+		<dependency>
101
+			<groupId>org.jboss.spec.javax.transaction</groupId>
102
+			<artifactId>jboss-transaction-api_1.2_spec</artifactId>
103
+			<version>1.0.0.Final</version>
104
+		</dependency>
105
+
106
+		<dependency>
107
+			<groupId>org.hibernate</groupId>
108
+			<artifactId>hibernate-entitymanager</artifactId>
109
+		</dependency>
110
+
111
+		<dependency>
112
+			<groupId>com.alibaba</groupId>
113
+			<artifactId>druid</artifactId>
114
+			<version>1.0.18</version>
115
+		</dependency>
116
+
117
+		<dependency>
118
+			<groupId>com.alibaba</groupId>
119
+			<artifactId>fastjson</artifactId>
120
+			<version>1.2.83</version>
121
+		</dependency>
122
+
123
+		<dependency>
124
+			<groupId>mysql</groupId>
125
+			<artifactId>mysql-connector-java</artifactId>
126
+			<version>5.1.34</version>
127
+		</dependency>
128
+		<dependency>
129
+			<groupId>com.microsoft.sqlserver</groupId>
130
+			<artifactId>sqljdbc4</artifactId>
131
+			<version>4.0</version>
132
+		</dependency>
133
+		<dependency>
134
+			<groupId>redis.clients</groupId>
135
+			<artifactId>jedis</artifactId>
136
+			<version>2.9.0</version>
137
+		</dependency>
138
+		<dependency>
139
+			<groupId>org.atmosphere</groupId>
140
+			<artifactId>atmosphere-runtime</artifactId>
141
+			<version>2.4.28</version>
142
+		</dependency>
143
+		<dependency>
144
+			<groupId>org.jboss.netty</groupId>
145
+			<artifactId>netty</artifactId>
146
+			<version>3.2.5.Final</version>
147
+		</dependency>
148
+		<dependency>
149
+			<groupId>com.belerweb</groupId>
150
+			<artifactId>pinyin4j</artifactId>
151
+			<version>2.5.0</version>
152
+		</dependency>
153
+		<dependency>
154
+			<groupId>com.oracle.database.jdbc</groupId>
155
+			<artifactId>ojdbc8</artifactId>
156
+			<version>12.2.0.1</version>
157
+		</dependency>
158
+
159
+
160
+		<dependency>
161
+			<groupId>org.springframework.boot</groupId>
162
+			<artifactId>spring-boot-autoconfigure</artifactId>
163
+			<scope>compile</scope>
164
+		</dependency>
165
+		<dependency>
166
+			<groupId>org.springframework.boot</groupId>
167
+			<artifactId>spring-boot-configuration-processor</artifactId>
168
+			<scope>compile</scope>
169
+		</dependency>
170
+	</dependencies>
171
+	<build>
172
+
173
+		<plugins>
174
+			<plugin>
175
+				<groupId>org.springframework.boot</groupId>
176
+				<artifactId>spring-boot-maven-plugin</artifactId>
177
+				<executions>
178
+					<execution>
179
+						<goals>
180
+							<goal>repackage</goal>
181
+						</goals>
182
+					</execution>
183
+				</executions>
184
+			</plugin>
185
+		</plugins>
186
+	</build>
187
+    <repositories>
188
+        <repository>
189
+            <id>clojars</id>
190
+            <url>http://clojars.org/repo/</url>
191
+        </repository>
192
+    </repositories>
193
+</project>

+ 34 - 0
src/main/java/com/dashitech/Application.java

@@ -0,0 +1,34 @@
1
+package com.dashitech;
2
+
3
+import org.springframework.boot.SpringApplication;
4
+import org.springframework.boot.autoconfigure.SpringBootApplication;
5
+import org.springframework.context.annotation.ComponentScan;
6
+import org.springframework.context.annotation.ImportResource;
7
+import org.springframework.context.annotation.PropertySource;
8
+import org.springframework.scheduling.annotation.EnableAsync;
9
+import org.springframework.scheduling.annotation.EnableScheduling;
10
+
11
+import java.text.SimpleDateFormat;
12
+import java.util.Date;
13
+
14
+
15
+
16
+@SpringBootApplication
17
+@EnableAsync
18
+@EnableScheduling
19
+@ComponentScan(basePackages = {"com.dashitech"})
20
+@PropertySource({"classpath:application-custom.properties", "application.properties"})
21
+@ImportResource(locations = "classpath*:/application-context.xml")
22
+//@Import({DynamicDataSourceRegister.class}) // 注册动态多数据源
23
+//@MapperScan("com.dashitech.dao.mysqldb1")//将项目中对应的mapper类的路径加进来就可以了
24
+//@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})    //不连数据库
25
+public class Application {
26
+
27
+    public static void main(String[] args) {
28
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
29
+        System.out.println("hsmsV1>>>>>>>>>>>>>>>>>>startData" + sdf.format(new Date()));
30
+        SpringApplication.run(Application.class, args);
31
+    }
32
+
33
+
34
+}

+ 28 - 0
src/main/java/com/dashitech/api/rest/ApiRest.java

@@ -0,0 +1,28 @@
1
+package com.dashitech.api.rest;
2
+
3
+import com.dashitech.migration.StartApplication;
4
+import org.springframework.beans.factory.annotation.Autowired;
5
+import org.springframework.web.bind.annotation.RequestMapping;
6
+import org.springframework.web.bind.annotation.RequestMethod;
7
+import org.springframework.web.bind.annotation.ResponseBody;
8
+import org.springframework.web.bind.annotation.RestController;
9
+
10
+@RestController
11
+@RequestMapping(value = "/api")
12
+public class ApiRest {
13
+
14
+    @Autowired
15
+    StartApplication startApplication;
16
+
17
+
18
+    @RequestMapping(value = "/start", method = RequestMethod.GET)
19
+    @ResponseBody
20
+    public String start() {
21
+
22
+        startApplication.start();
23
+
24
+        return "ok";
25
+    }
26
+
27
+
28
+}

+ 43 - 0
src/main/java/com/dashitech/bean/BaseBean.java

@@ -0,0 +1,43 @@
1
+package com.dashitech.bean;
2
+
3
+import java.io.Serializable;
4
+import java.util.List;
5
+
6
+/**
7
+ * Created by chi on 2019/9/9.
8
+ */
9
+public class BaseBean implements Serializable {
10
+    /**
11
+     * bean类型
12
+     */
13
+    private String beanType;
14
+
15
+    /**
16
+     *对象数组
17
+    */
18
+    private List<Object> objectList;
19
+
20
+    public String getBeanType() {
21
+        return beanType;
22
+    }
23
+
24
+    public void setBeanType(String beanType) {
25
+        this.beanType = beanType;
26
+    }
27
+
28
+    public List<Object> getObjectList() {
29
+        return objectList;
30
+    }
31
+
32
+    public void setObjectList(List<Object> objectList) {
33
+        this.objectList = objectList;
34
+    }
35
+
36
+    @Override
37
+    public String toString() {
38
+        return "BaseBean{" +
39
+                "beanType='" + beanType + '\'' +
40
+                ", objectList=" + objectList +
41
+                '}';
42
+    }
43
+}

+ 73 - 0
src/main/java/com/dashitech/bean/ResultMsg.java

@@ -0,0 +1,73 @@
1
+package com.dashitech.bean;
2
+
3
+//import com.dashitech.jsondata.entity.*;
4
+
5
+import javax.xml.bind.annotation.XmlSeeAlso;
6
+import java.io.Serializable;
7
+
8
+/**
9
+ * Created by chi on 2019/9/10.
10
+ */
11
+
12
+//@XmlSeeAlso({CallOnJSONEntity.class, PatientJSONEntity.class, DrugsBagJSONEntity.class, InspectJSONEntity.class, JPDetailsJSONEntity.class,DrugsJSONEntity.class,JPBagJSONEntity.class,SpecimenJSONEntity.class,BarthleJSONEntity.class,BuildingJSONEntity.class,DepartmentJSONEntity.class
13
+//,FloorJSONEntity.class,UserJSONEntity.class})
14
+public class ResultMsg implements Serializable {
15
+
16
+    /**
17
+     * 调用是否成功唯一标识
18
+     */
19
+    private Boolean success;
20
+    /**
21
+     * 描述
22
+     */
23
+    private String msg;
24
+
25
+    private int successCount;
26
+
27
+    private int failCount;
28
+
29
+    private String failReason;
30
+
31
+    public Boolean getSuccess() {
32
+        return success;
33
+    }
34
+
35
+    public void setSuccess(Boolean success) {
36
+        this.success = success;
37
+    }
38
+
39
+    public String getMsg() {
40
+        return msg;
41
+    }
42
+
43
+    public void setMsg(String msg) {
44
+        this.msg = msg;
45
+    }
46
+
47
+    public int getSuccessCount() {
48
+        return successCount;
49
+    }
50
+
51
+    public void setSuccessCount(int successCount) {
52
+        this.successCount = successCount;
53
+    }
54
+
55
+    public int getFailCount() {
56
+        return failCount;
57
+    }
58
+
59
+    public void setFailCount(int failCount) {
60
+        this.failCount = failCount;
61
+    }
62
+
63
+    @Override
64
+    public String toString() {
65
+        return "ResultMsg{" +
66
+                "success=" + success +
67
+                ", msg='" + msg + '\'' +
68
+                ", successCount=" + successCount +
69
+                ", failCount=" + failCount +
70
+                ", failReason='" + failReason + '\'' +
71
+                '}';
72
+    }
73
+}

+ 58 - 0
src/main/java/com/dashitech/config/ApiFilterConfig.java

@@ -0,0 +1,58 @@
1
+package com.dashitech.config;
2
+
3
+import org.apache.commons.logging.Log;
4
+import org.apache.commons.logging.LogFactory;
5
+import org.springframework.web.servlet.ModelAndView;
6
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
7
+
8
+import javax.servlet.http.HttpServletRequest;
9
+import javax.servlet.http.HttpServletResponse;
10
+
11
+/**
12
+ * API-rest服务拦截器 <br/>
13
+ * 对请求进行ip校验,出错返回拒绝信息
14
+ */
15
+public class ApiFilterConfig extends HandlerInterceptorAdapter {
16
+    private static Log log = LogFactory.getLog(ApiFilterConfig.class);
17
+
18
+    @Override
19
+    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
20
+        super.postHandle(request, response, handler, modelAndView);
21
+    }
22
+
23
+    @Override
24
+    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
25
+        super.afterCompletion(request, response, handler, ex);
26
+    }
27
+
28
+    @Override
29
+    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
30
+        response.setCharacterEncoding("UTF-8");
31
+
32
+//        HandlerMethod hm = (HandlerMethod) handler;
33
+//        String visitMethod = hm.getMethod().getName();
34
+
35
+        //校验
36
+        boolean flag = check(request.getRemoteHost());
37
+
38
+        //验证失败,拒绝请求
39
+  /*      if (!flag) {
40
+            MessageResult result = new MessageResult();
41
+            result.setSuccess(false);
42
+            result.setMsg("403 forbidden");
43
+            response.getWriter().print(JsonUtil.toJsonString(result));
44
+        }else {
45
+            log.error("ApiFilter Check Error:"+ request.getRequestURL().toString() + "  IP:"+ request.getRemoteAddr());
46
+        }*/
47
+
48
+        return flag;
49
+    }
50
+
51
+    private boolean check(String ip) {
52
+//        if (StringUtils.isNotEmpty(ip) && (ip.equals("127.0.0.1") || ip.equals("localhost") || ip.equals("0:0:0:0:0:0:0:1"))) {
53
+//            return true;
54
+//        }
55
+//        return false;
56
+        return true;
57
+    }
58
+}

+ 48 - 0
src/main/java/com/dashitech/config/ApiWeblogFilterConfig.java

@@ -0,0 +1,48 @@
1
+package com.dashitech.config;
2
+
3
+import org.apache.commons.logging.Log;
4
+import org.apache.commons.logging.LogFactory;
5
+import org.aspectj.lang.JoinPoint;
6
+import org.aspectj.lang.annotation.AfterReturning;
7
+import org.aspectj.lang.annotation.Aspect;
8
+import org.aspectj.lang.annotation.Before;
9
+import org.aspectj.lang.annotation.Pointcut;
10
+import org.springframework.core.annotation.Order;
11
+import org.springframework.stereotype.Component;
12
+import org.springframework.web.context.request.RequestContextHolder;
13
+import org.springframework.web.context.request.ServletRequestAttributes;
14
+
15
+import javax.servlet.http.HttpServletRequest;
16
+
17
+/**
18
+ * 路径拦截器
19
+ */
20
+@Aspect
21
+@Order(2)
22
+@Component
23
+public class ApiWeblogFilterConfig {
24
+    private static Log log = LogFactory.getLog(ApiWeblogFilterConfig.class);
25
+
26
+    ThreadLocal<Long> startTime = new ThreadLocal<Long>();
27
+
28
+    @Pointcut("execution(public * com.dashitech.api..*.*(..))")
29
+    public void webLog() {
30
+        log.info("show()");
31
+    }
32
+
33
+    @Before("webLog()")
34
+    public void doBefore(JoinPoint joinPoint) throws Throwable {
35
+        startTime.set(System.currentTimeMillis());
36
+        // 接收到请求,记录请求内容
37
+        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
38
+        HttpServletRequest request = attributes.getRequest();
39
+        // 记录下请求内容
40
+        log.info(Thread.currentThread().getName() + "   ApiLog-URL : " + request.getRequestURL().toString() + "   IP : " + request.getRemoteAddr());
41
+//        log.info(Thread.currentThread().getName() + "   ApiLog-ARGS : " + Arrays.toString(joinPoint.getArgs()));
42
+    }
43
+
44
+    @AfterReturning(returning = "ret", pointcut = "webLog()")
45
+    public void doAfterReturning(Object ret) throws Throwable {
46
+        log.info(Thread.currentThread().getName() + "   ApiLog-AVG/MS : " + (System.currentTimeMillis() - startTime.get()) + "/ms ");
47
+    }
48
+}

+ 45 - 0
src/main/java/com/dashitech/config/DataSourceConfig.java

@@ -0,0 +1,45 @@
1
+
2
+package com.dashitech.config;
3
+
4
+import org.springframework.beans.factory.annotation.Qualifier;
5
+import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
6
+import org.springframework.boot.context.properties.ConfigurationProperties;
7
+import org.springframework.context.annotation.Bean;
8
+import org.springframework.context.annotation.Configuration;
9
+import org.springframework.context.annotation.Primary;
10
+
11
+import javax.sql.DataSource;
12
+
13
+
14
+/**
15
+ * Created by chi on 2019/9/20.
16
+ */
17
+
18
+@Configuration
19
+public class DataSourceConfig {
20
+
21
+    /**
22
+     *  数据源2
23
+     */
24
+    @Primary
25
+    @Bean(name = "mysql2DataSource")
26
+    @Qualifier(value = "mysql2DataSource")
27
+    @ConfigurationProperties(prefix = "mysql2.spring.datasource")
28
+    public DataSource mysql2DataSource(){
29
+        return DataSourceBuilder.create().build();
30
+    }
31
+
32
+
33
+    /**
34
+     *  数据源3
35
+     */
36
+
37
+    @Bean(name = "mysql3DataSource")
38
+    @Qualifier(value = "mysql3DataSource")
39
+    @ConfigurationProperties(prefix = "mysql3.spring.datasource")
40
+    public DataSource mysql3DataSource(){
41
+        return DataSourceBuilder.create().build();
42
+    }
43
+
44
+}
45
+

+ 16 - 0
src/main/java/com/dashitech/config/DruidConfig.java

@@ -0,0 +1,16 @@
1
+package com.dashitech.config;
2
+
3
+import javax.servlet.annotation.WebInitParam;
4
+import javax.servlet.annotation.WebServlet;
5
+
6
+@WebServlet(urlPatterns = "/druid/*", 
7
+    initParams={
8
+            @WebInitParam(name="allow",value="127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问)
9
+            @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow)
10
+            @WebInitParam(name="loginUsername",value="itsm"),// 用户名
11
+            @WebInitParam(name="loginPassword",value="100100"),// 密码
12
+            @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
13
+    })
14
+public class DruidConfig {
15
+
16
+}

+ 14 - 0
src/main/java/com/dashitech/config/DruidFilter.java

@@ -0,0 +1,14 @@
1
+package com.dashitech.config;
2
+
3
+import com.alibaba.druid.support.http.WebStatFilter;
4
+
5
+import javax.servlet.annotation.WebFilter;
6
+import javax.servlet.annotation.WebInitParam;
7
+
8
+@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
9
+	    initParams={
10
+	        @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
11
+	})
12
+public class DruidFilter extends WebStatFilter{
13
+
14
+}

+ 22 - 0
src/main/java/com/dashitech/config/JdbcTemplateConfig.java

@@ -0,0 +1,22 @@
1
+package com.dashitech.config;
2
+
3
+import org.springframework.beans.factory.annotation.Qualifier;
4
+import org.springframework.context.annotation.Bean;
5
+import org.springframework.context.annotation.Configuration;
6
+import org.springframework.context.annotation.Primary;
7
+import org.springframework.jdbc.core.JdbcTemplate;
8
+
9
+import javax.sql.DataSource;
10
+
11
+@Configuration
12
+public class JdbcTemplateConfig {
13
+    @Bean
14
+    @Primary
15
+    public JdbcTemplate jdbcTemplateHsms(@Qualifier("mysql2DataSource")DataSource dataSource){
16
+        return new JdbcTemplate(dataSource);
17
+    }
18
+    @Bean
19
+    public JdbcTemplate jdbcTemplateMdv2(@Qualifier("mysql3DataSource")DataSource dataSource){
20
+        return new JdbcTemplate(dataSource);
21
+    }
22
+}

+ 17 - 0
src/main/java/com/dashitech/config/ScheduleConfig.java

@@ -0,0 +1,17 @@
1
+package com.dashitech.config;
2
+
3
+import org.springframework.beans.factory.annotation.Configurable;
4
+import org.springframework.context.annotation.Configuration;
5
+import org.springframework.scheduling.SchedulingTaskExecutor;
6
+import org.springframework.scheduling.annotation.SchedulingConfigurer;
7
+import org.springframework.scheduling.config.ScheduledTaskRegistrar;
8
+
9
+import java.util.concurrent.Executors;
10
+
11
+@Configuration
12
+public class ScheduleConfig implements SchedulingConfigurer {
13
+    @Override
14
+    public void configureTasks(ScheduledTaskRegistrar taskRegistrar){
15
+        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(15));
16
+    }
17
+}

+ 36 - 0
src/main/java/com/dashitech/config/SessionFactoryConfig.java

@@ -0,0 +1,36 @@
1
+/*
2
+package com.dashitech.config;
3
+
4
+import org.springframework.beans.factory.annotation.Autowired;
5
+import org.springframework.context.annotation.Bean;
6
+import org.springframework.context.annotation.Configuration;
7
+import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
8
+import org.springframework.transaction.annotation.EnableTransactionManagement;
9
+
10
+import javax.sql.DataSource;
11
+import java.util.Properties;
12
+
13
+@Configuration
14
+@EnableTransactionManagement
15
+public class SessionFactoryConfig {
16
+	
17
+	@Autowired
18
+	DataSource dataSource;
19
+	
20
+	@Bean
21
+	public LocalSessionFactoryBean sessionFactory() {
22
+		LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
23
+		sessionFactoryBean.setDataSource(dataSource);
24
+		Properties properties1 = new Properties();
25
+		properties1.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
26
+		properties1.setProperty("hibernate.show_sql", "false");
27
+		sessionFactoryBean.setHibernateProperties(properties1);
28
+		sessionFactoryBean.setPackagesToScan("com.dashitech.entity.mysqldatabase1");
29
+		
30
+		return sessionFactoryBean;
31
+	}
32
+	
33
+	
34
+}
35
+
36
+*/

+ 30 - 0
src/main/java/com/dashitech/config/TomcatConfig.java

@@ -0,0 +1,30 @@
1
+package com.dashitech.config;
2
+
3
+import org.apache.catalina.connector.Connector;
4
+import org.apache.coyote.http11.Http11NioProtocol;
5
+import org.springframework.boot.context.embedded.EmbeddedServletContainer;
6
+//import org.springframework.boot.context.embedded.ServletContextInitializer;
7
+import org.springframework.boot.web.servlet.ServletContextInitializer;
8
+import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
9
+import org.springframework.stereotype.Component;
10
+
11
+import java.nio.charset.Charset;
12
+
13
+@Component
14
+public class TomcatConfig extends TomcatEmbeddedServletContainerFactory {
15
+	public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) {
16
+		return super.getEmbeddedServletContainer(initializers);
17
+	}
18
+
19
+	protected void customizeConnector(Connector connector) {
20
+		super.customizeConnector(connector);
21
+		setUriEncoding(Charset.forName("UTF-8"));
22
+		Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
23
+		// 设置最大连接数
24
+		protocol.setMaxConnections(1000);
25
+		// 设置最大线程数
26
+		protocol.setMaxThreads(1000);
27
+		protocol.setConnectionTimeout(30000);
28
+	}
29
+
30
+}

+ 32 - 0
src/main/java/com/dashitech/config/WebServiceConfig.java

@@ -0,0 +1,32 @@
1
+package com.dashitech.config;
2
+
3
+
4
+/**
5
+ * Created by chi on 2019/9/16.
6
+ */
7
+/*@Configuration
8
+public class WebServiceConfig {
9
+
10
+    @Autowired
11
+    private ApiWebService apiWebService;
12
+
13
+
14
+    @Bean
15
+    public ServletRegistrationBean disServlet() {
16
+        return new ServletRegistrationBean(new CXFServlet(),"/web/*");
17
+    }
18
+
19
+    @Bean(name = Bus.DEFAULT_BUS_ID)
20
+    public SpringBus springBus() {
21
+        return new SpringBus();
22
+    }
23
+
24
+    @Bean
25
+    public Endpoint endpoint() {
26
+        EndpointImpl endpoint = new EndpointImpl(springBus(), apiWebService);
27
+        endpoint.publish("/service");
28
+        return endpoint;
29
+    }
30
+
31
+
32
+}*/

+ 26 - 0
src/main/java/com/dashitech/migration/BaseTask.java

@@ -0,0 +1,26 @@
1
+package com.dashitech.migration;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.beans.factory.annotation.Qualifier;
5
+import org.springframework.jdbc.core.JdbcTemplate;
6
+
7
+import java.util.LinkedHashMap;
8
+import java.util.Map;
9
+
10
+/**
11
+ * Created by CX on 2024/10/10.
12
+ */
13
+public abstract class BaseTask implements SqlTask {
14
+
15
+    protected Map cache = new LinkedHashMap();
16
+
17
+    @Autowired
18
+    @Qualifier("jdbcTemplateHsms")
19
+    protected JdbcTemplate jdbcTemplateHsms;
20
+
21
+    @Autowired
22
+    @Qualifier("jdbcTemplateMdv2")
23
+    protected JdbcTemplate jdbcTemplateMdv2;
24
+
25
+
26
+}

+ 19 - 0
src/main/java/com/dashitech/migration/SqlTask.java

@@ -0,0 +1,19 @@
1
+package com.dashitech.migration;
2
+
3
+import com.dashitech.migration.core.FieldMapper;
4
+
5
+/**
6
+ * Created by CX on 2024/10/10.
7
+ */
8
+public interface SqlTask {
9
+
10
+    /**
11
+     * 不需要try/catch,有错就抛出来处理
12
+     */
13
+    FieldMapper start(FieldMapper fieldMapper);
14
+
15
+    /**
16
+     * 如果之前执行有报错,需要重新加载特定字段缓存数据
17
+     */
18
+    FieldMapper loadCache();
19
+}

+ 30 - 0
src/main/java/com/dashitech/migration/StartApplication.java

@@ -0,0 +1,30 @@
1
+package com.dashitech.migration;
2
+
3
+import com.dashitech.migration.core.FieldMapper;
4
+import org.apache.commons.logging.Log;
5
+import org.apache.commons.logging.LogFactory;
6
+import org.springframework.beans.factory.annotation.Autowired;
7
+import org.springframework.stereotype.Service;
8
+
9
+/**
10
+ * 迁移数据启动类
11
+ * Created by CX on 2024/10/10.
12
+ */
13
+@Service
14
+public class StartApplication {
15
+
16
+    public static Log log = LogFactory.getLog(StartApplication.class);
17
+
18
+    @Autowired
19
+    SqlTask groupTask;
20
+
21
+    public void start() {
22
+        //工作组
23
+        FieldMapper groupMapper = groupTask.start(null);
24
+//        FieldMapper groupMapper = groupTask.loadCache();
25
+        System.out.println(groupMapper);
26
+
27
+    }
28
+
29
+
30
+}

+ 123 - 0
src/main/java/com/dashitech/migration/core/DataMapper.java

@@ -0,0 +1,123 @@
1
+package com.dashitech.migration.core;
2
+
3
+import java.io.Serializable;
4
+import java.util.HashMap;
5
+import java.util.Map;
6
+
7
+/**
8
+ * 数据匹配器
9
+ */
10
+public class DataMapper implements Serializable{
11
+
12
+    private String targetName;
13
+    private Object targetValue;
14
+    private Long targetId;
15
+    private String sourceName;
16
+    private Object sourceValue;
17
+    private Long sourceId;
18
+    private boolean remove = false;
19
+    private boolean update = false;
20
+    private boolean add = false;
21
+    private boolean replace = false;
22
+    /**
23
+     * 匹配完成后的id对照,source:target
24
+     */
25
+    private Map<Long, Long> idCache = new HashMap<>();
26
+
27
+    public DataMapper() {
28
+    }
29
+
30
+    public DataMapper(String targetName, String sourceName) {
31
+        this.targetName = targetName;
32
+        this.sourceName = sourceName;
33
+    }
34
+
35
+    public boolean isAdd() {
36
+        return add;
37
+    }
38
+
39
+    public void setAdd(boolean add) {
40
+        this.add = add;
41
+    }
42
+
43
+    public boolean isReplace() {
44
+        return replace;
45
+    }
46
+
47
+    public void setReplace(boolean replace) {
48
+        this.replace = replace;
49
+    }
50
+
51
+    public Map<Long, Long> getIdCache() {
52
+        return idCache;
53
+    }
54
+
55
+    public void setIdCache(Map<Long, Long> idCache) {
56
+        this.idCache = idCache;
57
+    }
58
+
59
+    public boolean isRemove() {
60
+        return remove;
61
+    }
62
+
63
+    public void setRemove(boolean remove) {
64
+        this.remove = remove;
65
+    }
66
+
67
+    public boolean isUpdate() {
68
+        return update;
69
+    }
70
+
71
+    public void setUpdate(boolean update) {
72
+        this.update = update;
73
+    }
74
+
75
+    public String getTargetName() {
76
+        return targetName;
77
+    }
78
+
79
+    public void setTargetName(String targetName) {
80
+        this.targetName = targetName;
81
+    }
82
+
83
+    public Object getTargetValue() {
84
+        return targetValue;
85
+    }
86
+
87
+    public void setTargetValue(Object targetValue) {
88
+        this.targetValue = targetValue;
89
+    }
90
+
91
+    public Long getTargetId() {
92
+        return targetId;
93
+    }
94
+
95
+    public void setTargetId(Long targetId) {
96
+        this.targetId = targetId;
97
+    }
98
+
99
+    public String getSourceName() {
100
+        return sourceName;
101
+    }
102
+
103
+    public void setSourceName(String sourceName) {
104
+        this.sourceName = sourceName;
105
+    }
106
+
107
+    public Object getSourceValue() {
108
+        return sourceValue;
109
+    }
110
+
111
+    public void setSourceValue(Object sourceValue) {
112
+        this.sourceValue = sourceValue;
113
+    }
114
+
115
+    public Long getSourceId() {
116
+        return sourceId;
117
+    }
118
+
119
+    public void setSourceId(Long sourceId) {
120
+        this.sourceId = sourceId;
121
+    }
122
+
123
+}

+ 84 - 0
src/main/java/com/dashitech/migration/core/DataMigrationter.java

@@ -0,0 +1,84 @@
1
+package com.dashitech.migration.core;
2
+
3
+import org.apache.commons.logging.Log;
4
+import org.apache.commons.logging.LogFactory;
5
+
6
+import java.util.ArrayList;
7
+import java.util.HashMap;
8
+import java.util.List;
9
+import java.util.Map;
10
+
11
+/**
12
+ * 数据迁移处理
13
+ */
14
+public class DataMigrationter {
15
+    public static Log log = LogFactory.getLog(DataMigrationter.class);
16
+
17
+    public static void loadCache(List<Map<String, Object>> targetList, List<Map<String, Object>> sourceList, FieldMapper mapper) {
18
+        mapperData(targetList, sourceList, mapper);
19
+        trans2IdCache(mapper);
20
+    }
21
+
22
+    /**
23
+     * 待匹配字段,根据fieldList组成联合key,缓存成联合主键key:id
24
+     */
25
+    public static List<FieldMapper> mapperData(List<Map<String, Object>> targetList, List<Map<String, Object>> sourceList, FieldMapper mapper) {
26
+        List<FieldMapper> result = new ArrayList<>();
27
+        if (targetList != null && targetList.size() > 0 && sourceList != null && sourceList.size() > 0 && mapper != null && mapper.getFieldList().size() > 0) {
28
+
29
+            //源数据
30
+            for (Map<String, Object> map : sourceList) {
31
+                setSourceKey(map, mapper);
32
+            }
33
+
34
+            //目标数据
35
+            for (Map<String, Object> map : targetList) {
36
+                setTargetKey(map, mapper);
37
+            }
38
+
39
+        }
40
+        return result;
41
+    }
42
+
43
+    /**
44
+     * key:源数据id,value:目标数据id
45
+     */
46
+    public static void trans2IdCache(FieldMapper mapper) {
47
+        Map<Long, Long> cache = new HashMap<>();
48
+        Map<String, Long> sourceCache = mapper.getSourceCache();
49
+        for (Map.Entry<String, Long> entry : mapper.getTargetCache().entrySet()) {
50
+            Long sourceId = sourceCache.get(entry.getKey());
51
+            Long targetId = entry.getValue();
52
+            if (sourceId != null && targetId != null) {
53
+                cache.put(sourceId, targetId);
54
+            }else if(sourceId != null){
55
+                cache.put(sourceId, null);
56
+            }
57
+        }
58
+        mapper.setIdCache(cache);
59
+    }
60
+
61
+
62
+    public static void setSourceKey(Map<String, Object> map, FieldMapper mapper) {
63
+        StringBuffer source = new StringBuffer();
64
+        Object id = map.get("id");
65
+        for (DataMapper dataMapper : mapper.getFieldList()) {
66
+            Object value = map.get(dataMapper.getSourceName());
67
+            source.append(value).append("_");
68
+        }
69
+        source.deleteCharAt(source.length() - 1);
70
+        mapper.getSourceCache().put(source.toString(), id == null ? null : Long.valueOf(id.toString()));
71
+    }
72
+
73
+    public static void setTargetKey(Map<String, Object> map, FieldMapper mapper) {
74
+        StringBuffer target = new StringBuffer();
75
+        Object id = map.get("id");
76
+        for (DataMapper dataMapper : mapper.getFieldList()) {
77
+            Object value = map.get(dataMapper.getTargetName());
78
+            target.append(value).append("_");
79
+        }
80
+        target.deleteCharAt(target.length() - 1);
81
+        mapper.getTargetCache().put(target.toString(), id == null ? null : Long.valueOf(id.toString()));
82
+    }
83
+
84
+}

+ 194 - 0
src/main/java/com/dashitech/migration/core/FieldMapper.java

@@ -0,0 +1,194 @@
1
+package com.dashitech.migration.core;
2
+
3
+import com.dashitech.migration.util.JdbcRow;
4
+
5
+import java.util.ArrayList;
6
+import java.util.HashMap;
7
+import java.util.List;
8
+import java.util.Map;
9
+
10
+/**
11
+ * 字段匹配器
12
+ * Created by CX on 2024/10/10.
13
+ */
14
+public class FieldMapper {
15
+
16
+    /**
17
+     * 待匹配字段
18
+     */
19
+    private List<DataMapper> fieldList = new ArrayList<>();
20
+    private Map<String, Long> sourceCache = new HashMap<>();
21
+    private Map<String, Long> targetCache = new HashMap<>();
22
+    /**
23
+     * 匹配完成后的id对照,source:target
24
+     */
25
+    private Map<Long, Long> idCache = new HashMap<>();
26
+    /**
27
+     * 待转换的插入数据
28
+     */
29
+    private List<JdbcRow> rows = new ArrayList<>();
30
+    /**
31
+     * 插入数据,需要替换或删除的字段
32
+     */
33
+    private List<DataMapper> rowsOperationList = new ArrayList<>();
34
+
35
+    /**
36
+     * 根据rowsOperationList ,处理成可以直接插入的最终数据
37
+     *
38
+     * @param list 原始数据:List<Map<String,Object>> 类型
39
+     */
40
+    public void trans2JdbcRow(List list) {
41
+        if (list != null && list.size() > 0) {
42
+            for (Object object : list) {
43
+                Map<String, Object> row = (Map<String, Object>) object;
44
+
45
+                for (DataMapper dataMapper : rowsOperationList) {
46
+                    //如果是删除,直接删除旧key
47
+                    if (dataMapper.isRemove() && row.containsKey(dataMapper.getSourceName())) {
48
+                        row.remove(dataMapper.getSourceName());
49
+                    }
50
+                    //如果是修改,先删除旧的key,在新增新的key:value
51
+                    if (dataMapper.isUpdate() && row.containsKey(dataMapper.getSourceName())) {
52
+                        Object value = row.get(dataMapper.getSourceName());
53
+                        row.remove(dataMapper.getSourceName());
54
+                        row.put(dataMapper.getTargetName(), value);
55
+                    }
56
+                    //如果是新增,直接put
57
+                    if (dataMapper.isAdd()) {
58
+                        row.put(dataMapper.getSourceName(),dataMapper.getTargetValue());
59
+                    }
60
+                    //如果是要替换的,使用id缓存替换
61
+                    if (dataMapper.isReplace() && row.containsKey(dataMapper.getSourceName())) {
62
+                        Object value = row.get(dataMapper.getSourceName());
63
+                        if(value != null) {
64
+                            Long id = dataMapper.getIdCache().get(value);
65
+                            row.put(dataMapper.getSourceName(),id);
66
+                        }else {
67
+                            row.put(dataMapper.getSourceName(),null);
68
+                        }
69
+                    }
70
+                }
71
+
72
+                JdbcRow jdbcRow = row2JdbcRow(row);
73
+                rows.add(jdbcRow);
74
+            }
75
+        }
76
+    }
77
+
78
+    private JdbcRow row2JdbcRow(Map<String, Object> row) {
79
+        JdbcRow jdbcRow = new JdbcRow();
80
+        jdbcRow.setRow(row);
81
+        return jdbcRow;
82
+    }
83
+
84
+
85
+    /**
86
+     * 增加待匹配字段,形成联合主键key
87
+     */
88
+    public FieldMapper addFieldMapper(String target, String source) {
89
+        fieldList.add(new DataMapper(target, source));
90
+        return this;
91
+    }
92
+
93
+    /**
94
+     * 待删除的字段
95
+     */
96
+    public FieldMapper addOperationRemove(String name) {
97
+        DataMapper mapper = new DataMapper(name, name);
98
+        mapper.setRemove(true);
99
+        rowsOperationList.add(mapper);
100
+        return this;
101
+    }
102
+
103
+    /**
104
+     * 待修改的字段
105
+     */
106
+    public FieldMapper addOperationUpdate(String target, String source) {
107
+        DataMapper mapper = new DataMapper(target, source);
108
+        mapper.setUpdate(true);
109
+        rowsOperationList.add(mapper);
110
+        return this;
111
+    }
112
+
113
+    /**
114
+     * 待新增的默认字段
115
+     */
116
+    public FieldMapper addOperationAdd(String name, Object value) {
117
+        DataMapper mapper = new DataMapper(name, name);
118
+        mapper.setAdd(true);
119
+        mapper.setTargetValue(value);
120
+        rowsOperationList.add(mapper);
121
+        return this;
122
+    }
123
+
124
+    /**
125
+     * 待替换的字段。注意:name是旧source名称,不是新target名称,每次加入都在队列最前面
126
+     */
127
+    public FieldMapper addOperationReplace(String name, Map<Long, Long> idCache) {
128
+        DataMapper mapper = new DataMapper(name, name);
129
+        mapper.setReplace(true);
130
+        mapper.setIdCache(idCache);
131
+        //TODO 替换,必须放在第一个,避免被修改字段名称后,导致使用新名称的错误
132
+        rowsOperationList.add(0,mapper);
133
+        return this;
134
+    }
135
+
136
+    /**
137
+     * 使用完显式清空,释放内存
138
+     */
139
+    public void clear() {
140
+        this.fieldList.clear();
141
+        this.targetCache.clear();
142
+        this.targetCache.clear();
143
+        this.idCache.clear();
144
+        this.rows.clear();
145
+    }
146
+
147
+    public List<DataMapper> getFieldList() {
148
+        return fieldList;
149
+    }
150
+
151
+    public void setFieldList(List<DataMapper> fieldList) {
152
+        this.fieldList = fieldList;
153
+    }
154
+
155
+    public Map<String, Long> getSourceCache() {
156
+        return sourceCache;
157
+    }
158
+
159
+    public void setSourceCache(Map<String, Long> sourceCache) {
160
+        this.sourceCache = sourceCache;
161
+    }
162
+
163
+    public Map<String, Long> getTargetCache() {
164
+        return targetCache;
165
+    }
166
+
167
+    public void setTargetCache(Map<String, Long> targetCache) {
168
+        this.targetCache = targetCache;
169
+    }
170
+
171
+    public Map<Long, Long> getIdCache() {
172
+        return idCache;
173
+    }
174
+
175
+    public void setIdCache(Map<Long, Long> idCache) {
176
+        this.idCache = idCache;
177
+    }
178
+
179
+    public List<JdbcRow> getRows() {
180
+        return rows;
181
+    }
182
+
183
+    public void setRows(List<JdbcRow> rows) {
184
+        this.rows = rows;
185
+    }
186
+
187
+    public List<DataMapper> getRowsOperationList() {
188
+        return rowsOperationList;
189
+    }
190
+
191
+    public void setRowsOperationList(List<DataMapper> rowsOperationList) {
192
+        this.rowsOperationList = rowsOperationList;
193
+    }
194
+}

+ 72 - 0
src/main/java/com/dashitech/migration/task/uc/GroupTask.java

@@ -0,0 +1,72 @@
1
+package com.dashitech.migration.task.uc;
2
+
3
+import com.dashitech.migration.BaseTask;
4
+import com.dashitech.migration.core.DataMigrationter;
5
+import com.dashitech.migration.core.FieldMapper;
6
+import com.dashitech.migration.util.JdbcUtil;
7
+import org.apache.commons.logging.Log;
8
+import org.apache.commons.logging.LogFactory;
9
+import org.springframework.stereotype.Component;
10
+import org.springframework.transaction.annotation.Transactional;
11
+
12
+import java.util.HashMap;
13
+import java.util.List;
14
+import java.util.Map;
15
+
16
+/**
17
+ * Created by CX on 2024/10/10.
18
+ */
19
+@Component
20
+public class GroupTask extends BaseTask {
21
+
22
+    public static Log log = LogFactory.getLog(GroupTask.class);
23
+
24
+    @Override
25
+    @Transactional
26
+    public FieldMapper start(FieldMapper fieldMapper) {
27
+        log.info(" *** 工作组group转换开始 *** ");
28
+
29
+        StringBuffer sb = new StringBuffer();
30
+        sb.append(" select * from itsm_uc_groups ");
31
+
32
+        List list = jdbcTemplateMdv2.queryForList(sb.toString());
33
+
34
+        //测试
35
+        FieldMapper mapper = new FieldMapper();
36
+        mapper.addOperationRemove("id").addOperationRemove("duty_id");
37
+        mapper.addOperationUpdate("_hospital_id", "branch_id");
38
+        mapper.addOperationAdd("type", 3);
39
+        Map<Long, Long> hosIdCache = new HashMap<>();
40
+        hosIdCache.put(1L, 4L);
41
+        mapper.addOperationReplace("branch_id", hosIdCache);
42
+        mapper.trans2JdbcRow(list);
43
+
44
+        JdbcUtil jdbcUtil = new JdbcUtil(jdbcTemplateHsms);
45
+        jdbcUtil.batchPageInsert("itsm_uc_groups", mapper.getRows());
46
+
47
+        //不需要缓存id的话,clear释放内存
48
+        mapper.clear();
49
+
50
+        mapper = loadCache();
51
+
52
+        return mapper;
53
+    }
54
+
55
+    @Override
56
+    public FieldMapper loadCache() {
57
+        log.info(" *** 加载工作组group缓存 *** ");
58
+
59
+        String sql = " select id,groupname,delete_flag from itsm_uc_groups ";
60
+        List<Map<String, Object>> list = jdbcTemplateHsms.queryForList(sql);
61
+        sql = " select id,groupname,delete_flag from itsm_uc_groups ";
62
+        List<Map<String, Object>> list2 = jdbcTemplateMdv2.queryForList(sql);
63
+
64
+        FieldMapper mapper = new FieldMapper();
65
+        mapper.addFieldMapper("groupname", "groupname");
66
+        mapper.addFieldMapper("delete_flag", "delete_flag");
67
+
68
+        DataMigrationter.loadCache(list, list2, mapper);
69
+
70
+        return mapper;
71
+    }
72
+}

+ 44 - 0
src/main/java/com/dashitech/migration/task/uc/UserTask.java

@@ -0,0 +1,44 @@
1
+package com.dashitech.migration.task.uc;
2
+
3
+import com.dashitech.migration.BaseTask;
4
+import com.dashitech.migration.core.DataMigrationter;
5
+import com.dashitech.migration.core.FieldMapper;
6
+import org.apache.commons.logging.Log;
7
+import org.apache.commons.logging.LogFactory;
8
+import org.springframework.stereotype.Component;
9
+import org.springframework.transaction.annotation.Transactional;
10
+
11
+import java.util.List;
12
+import java.util.Map;
13
+
14
+/**
15
+ * Created by CX on 2024/10/10.
16
+ */
17
+@Component
18
+public class UserTask extends BaseTask {
19
+
20
+    public static Log log = LogFactory.getLog(UserTask.class);
21
+
22
+    @Override
23
+    @Transactional
24
+    public FieldMapper start(FieldMapper fieldMapper) {
25
+        log.info(" *** 用户user转换开始 *** ");
26
+
27
+        StringBuffer sb = new StringBuffer();
28
+        sb.append(" select * from itsm_uc_user ");
29
+
30
+        List list = jdbcTemplateHsms.queryForList(sb.toString());
31
+
32
+
33
+        return fieldMapper;
34
+    }
35
+
36
+    @Override
37
+    public FieldMapper loadCache() {
38
+        log.info(" *** 加载用户user缓存 *** ");
39
+
40
+
41
+
42
+        return null;
43
+    }
44
+}

+ 78 - 0
src/main/java/com/dashitech/migration/util/JdbcRow.java

@@ -0,0 +1,78 @@
1
+package com.dashitech.migration.util;
2
+
3
+import java.util.ArrayList;
4
+import java.util.LinkedHashMap;
5
+import java.util.List;
6
+import java.util.Map;
7
+
8
+/**
9
+ * JdbcUtil工具类使用,表示一行数据的新增或者修改
10
+ * Created by CX on 2020/10/14.
11
+ */
12
+public class JdbcRow {
13
+
14
+    private Map<String, Object> row = new LinkedHashMap<String, Object>();
15
+    private List params = new ArrayList();
16
+    private StringBuffer where = new StringBuffer(" where 1 = 1 ");
17
+
18
+    public static JdbcRow newInstance() {
19
+        return new JdbcRow();
20
+    }
21
+
22
+    /**
23
+     * 设置行的数据项
24
+     * @param field 数据库字段名称
25
+     * @param value 需存储数据
26
+     */
27
+    public JdbcRow setAttribute(String field,Object value) {
28
+        row.put(field, value);
29
+        return this;
30
+    }
31
+
32
+    /**
33
+     * 设置简单等于的参数,这样就不用追加参数了
34
+     * @param field 数据库表的字段名称
35
+     * @param value 匹配数据
36
+     */
37
+    public JdbcRow setWhere(String field,Object value) {
38
+        where.append(" and ");
39
+        where.append(field);
40
+        where.append(" = ? ");
41
+        params.add(value);
42
+        return this;
43
+    }
44
+
45
+    /**
46
+     * 自定义查询语句,自己选择,怎么拼接sql。可以是 and ,or , = ,in ,BETWEEN ,order by ,group by 等任何语句
47
+     */
48
+    public JdbcRow setWhere(String condition) {
49
+        where.append(" ");
50
+        where.append(condition);
51
+        where.append(" ");
52
+        return this;
53
+    }
54
+
55
+    /**
56
+     * 手动追加参数
57
+     */
58
+    public JdbcRow setParams(String value) {
59
+        params.add(value);
60
+        return this;
61
+    }
62
+
63
+    public Map<String, Object> getRow() {
64
+        return row;
65
+    }
66
+
67
+    public void setRow(Map<String, Object> row) {
68
+        this.row = row;
69
+    }
70
+
71
+    public String getWhere() {
72
+        return where.toString();
73
+    }
74
+
75
+    public List getParams() {
76
+        return params;
77
+    }
78
+}

+ 258 - 0
src/main/java/com/dashitech/migration/util/JdbcUtil.java

@@ -0,0 +1,258 @@
1
+package com.dashitech.migration.util;
2
+
3
+import com.dashitech.utils.CommonUtil;
4
+import com.dashitech.utils.DateUtil;
5
+import com.dashitech.utils.DecimalUtil;
6
+import com.dashitech.utils.SpringContextHolder;
7
+import org.apache.commons.lang.StringUtils;
8
+import org.slf4j.Logger;
9
+import org.slf4j.LoggerFactory;
10
+import org.springframework.core.annotation.AnnotationUtils;
11
+import org.springframework.jdbc.core.BatchPreparedStatementSetter;
12
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
13
+import org.springframework.jdbc.core.JdbcTemplate;
14
+
15
+import javax.persistence.Column;
16
+import javax.persistence.JoinColumn;
17
+import javax.persistence.Table;
18
+import java.beans.BeanInfo;
19
+import java.beans.Introspector;
20
+import java.beans.PropertyDescriptor;
21
+import java.lang.annotation.Annotation;
22
+import java.lang.reflect.Field;
23
+import java.math.BigInteger;
24
+import java.sql.PreparedStatement;
25
+import java.sql.SQLException;
26
+import java.util.*;
27
+
28
+
29
+/**
30
+ * 数据库批量操作工具类
31
+ */
32
+public class JdbcUtil {
33
+    private static final Logger log = LoggerFactory.getLogger(JdbcUtil.class);
34
+    private JdbcTemplate jdbcTemplate;
35
+
36
+    public JdbcUtil(JdbcTemplate jdbcTemplate) {
37
+        this.jdbcTemplate = jdbcTemplate;
38
+    }
39
+
40
+
41
+
42
+    /**
43
+     * 获取插入语句
44
+     */
45
+    private String getInsertSql(String table,List<JdbcRow> rows) {
46
+        Map<String, Object> cols = new LinkedHashMap<>();
47
+
48
+        //顺序覆盖参数和传值
49
+        for (JdbcRow row : rows) {
50
+            cols.putAll(row.getRow());
51
+        }
52
+        //整理数据,没有的传值,补null
53
+        for (JdbcRow row : rows) {
54
+            Map<String, Object> _row = row.getRow();
55
+            for(Map.Entry<String,Object> entry : cols.entrySet()) {
56
+                //没有这个参数的,补齐null值,要不然批量新增参数不对报错
57
+                if(!_row.containsKey(entry.getKey())) {
58
+                    _row.put(entry.getKey(), null);
59
+                }
60
+            }
61
+        }
62
+
63
+        String result = "";
64
+        StringBuffer sb = new StringBuffer();
65
+        // 设置执行语句
66
+        sb.append("insert into " + table + "( ");
67
+        for (Map.Entry<String, Object> entry : cols.entrySet()) {
68
+            sb.append(entry.getKey()).append(",");
69
+        }
70
+        if (sb.toString().endsWith(",")) {
71
+            sb = sb.delete(sb.length() - 1, sb.length());
72
+        }
73
+        sb.append(" ) values( ");
74
+        for (Map.Entry<String, Object> entry : cols.entrySet()) {
75
+            sb.append("?,");
76
+        }
77
+        if (sb.toString().endsWith(",")) {
78
+            sb = sb.delete(sb.length() - 1, sb.length());
79
+        }
80
+        sb.append(" )");    //批量语句,结尾不能加上分号;
81
+        result = sb.toString();
82
+        return result;
83
+    }
84
+
85
+    /**
86
+     * 获取修改语句,必须带上条件!
87
+     */
88
+    private static String getUpdateSql(String table,JdbcRow row) {
89
+        String result = "";
90
+        StringBuffer sb = new StringBuffer();
91
+        // 设置执行语句
92
+        sb.append(" update " + table + " set ");
93
+        for (Map.Entry<String, Object> entry : row.getRow().entrySet()) {
94
+            sb.append(entry.getKey()).append(" = ? ").append(",");
95
+        }
96
+        if (sb.toString().endsWith(",")) {
97
+            sb = sb.delete(sb.length() - 1, sb.length());
98
+        }
99
+
100
+        //设置条件语句
101
+        sb.append(row.getWhere());
102
+        //批量语句,结尾不能加上分号;
103
+        result = sb.toString();
104
+        return result;
105
+    }
106
+
107
+
108
+    /**
109
+     * 批量执行修改数据
110
+     */
111
+    private boolean jdbcTemplateBatchUpdate(String sql, final List<JdbcRow> rows) {
112
+        if (jdbcTemplate != null && StringUtils.isNotEmpty(sql) && rows != null && rows.size() > 0) {
113
+            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
114
+                public void setValues(PreparedStatement ps, int i) throws SQLException {
115
+                    //设置数据参数
116
+                    Map<String, Object> row = rows.get(i).getRow();
117
+                    int index = 1;
118
+                    for (Map.Entry<String, Object> entry : row.entrySet()) {
119
+                        ps.setObject(index++, entry.getValue());
120
+                    }
121
+
122
+                    //设置where参数
123
+                    List params = rows.get(i).getParams();
124
+                    if (params.size() > 0) {
125
+                        for (Object param : params) {
126
+                            ps.setObject(index++, param);
127
+                        }
128
+                    }
129
+                }
130
+
131
+                public int getBatchSize() {
132
+                    return rows == null ? 0 : rows.size();
133
+                }
134
+            });
135
+            return true;
136
+        }
137
+        return false;
138
+    }
139
+
140
+    /**
141
+     * 批量执行新增数据 <br/>
142
+     * 新增不需要where条件
143
+     * @param table        插入数据的表名
144
+     * @param rows         行数据
145
+     */
146
+    private boolean batchInsert(String table, final List<JdbcRow> rows) {
147
+        if (table == null || table.length()== 0 || rows == null || rows.size() == 0) {
148
+            return false;
149
+        }
150
+        String insertSql = getInsertSql(table,rows);
151
+        log.info("开始批量新增"+table+", 条数:"+rows.size());
152
+        return jdbcTemplateBatchUpdate(insertSql, rows);
153
+    }
154
+
155
+    /**
156
+     * 批量执行修改数据 <br/>
157
+     * 修改必须带上where条件
158
+     * @param table        插入数据的表名
159
+     * @param rows         行数据
160
+     */
161
+    private boolean batchUpdate(String table, final List<JdbcRow> rows) {
162
+        if (table == null || table.length()== 0 || rows == null || rows.size() == 0) {
163
+            return false;
164
+        }
165
+        String updateSql = getUpdateSql(table,rows.get(0));
166
+        log.info("开始批量修改"+table+", 条数:"+rows.size());
167
+        return jdbcTemplateBatchUpdate(updateSql, rows);
168
+    }
169
+
170
+    /**
171
+     * 返回分页后的列表
172
+     * @param rows 总数据
173
+     * @param page 一批要分为多少条
174
+     */
175
+    private static List<List<JdbcRow>> pageList(List<JdbcRow> rows,int page) {
176
+        List<List<JdbcRow>> result = new ArrayList<List<JdbcRow>>();
177
+        if(rows != null && rows.size() > page) {
178
+            double div = Math.ceil(DecimalUtil.div(rows.size(),page).doubleValue());
179
+            int total = Double.valueOf(div).intValue();
180
+
181
+            for (int i = 1; i <= total; i++) {
182
+                List<JdbcRow> tempList = CommonUtil.paginateList(rows, i, page);
183
+                result.add(tempList);
184
+            }
185
+        }else if(rows != null && rows.size() > 0 && rows.size() <= page) {
186
+            result.add(rows);
187
+        }
188
+        return result;
189
+    }
190
+
191
+
192
+    /**
193
+     * 分批执行批量操作,默认1000条
194
+     */
195
+    public boolean batchPageInsert(String table, final List<JdbcRow> rows) {
196
+        if (table == null || table.length()== 0 || rows == null || rows.size() == 0) {
197
+            return false;
198
+        }
199
+        List<List<JdbcRow>> pageList = pageList(rows, 1000);
200
+        for (List<JdbcRow> jdbcRows : pageList) {
201
+            batchInsert(table, jdbcRows);
202
+        }
203
+        return true;
204
+    }
205
+
206
+    /**
207
+     * 分批执行批量操作,默认1000条
208
+     */
209
+    public boolean batchPageUpdate(String table, final List<JdbcRow> rows) {
210
+        if (table == null || table.length()== 0 || rows == null || rows.size() == 0) {
211
+            return false;
212
+        }
213
+        List<List<JdbcRow>> pageList = pageList(rows, 1000);
214
+        for (List<JdbcRow> jdbcRows : pageList) {
215
+            batchUpdate(table, jdbcRows);
216
+        }
217
+        return true;
218
+    }
219
+
220
+
221
+    public <T> List<T> simpleSelectDto(String sql,Class<T> _class,Object... args) {
222
+        return  jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(_class), args);
223
+    }
224
+
225
+    /**
226
+     * 返回列表的查询
227
+     */
228
+    public List simpleSelectList(String sql,Object... args) {
229
+        return  jdbcTemplate.queryForList(sql, args);
230
+    }
231
+
232
+    public static void test() {
233
+        List<JdbcRow> rows = new ArrayList<JdbcRow>();
234
+        rows.add(JdbcRow.newInstance()
235
+                .setAttribute("version", 1)
236
+                .setAttribute("_name", "fafdsafsda")
237
+                .setAttribute("_age", 1111)
238
+//                .setWhere("id",30041)
239
+        );
240
+
241
+        rows.add(JdbcRow.newInstance()
242
+                .setAttribute("version", 2)
243
+                .setAttribute("_name", "BBBBB131232132132121BBBBBB")
244
+                .setAttribute("_age", 22222)
245
+//                .setWhere("id",30042)
246
+        );
247
+
248
+//        JdbcUtil.batchInsert("test",rows);
249
+//        JdbcUtil.batchUpdate("test",rows);
250
+
251
+    }
252
+
253
+
254
+    public static void main(String[] args) {
255
+        test();
256
+    }
257
+
258
+}

+ 71 - 0
src/main/java/com/dashitech/redis/core/JedisPoolFactory.java

@@ -0,0 +1,71 @@
1
+package com.dashitech.redis.core;
2
+
3
+import com.dashitech.utils.PropertiesUtil;
4
+import redis.clients.jedis.Jedis;
5
+import redis.clients.jedis.JedisPool;
6
+import redis.clients.jedis.JedisPoolConfig;
7
+
8
+/**
9
+ * Redis抽象工厂实例类,务必在Spring的数据库配置加载完成后在调用此类!否则会报错
10
+ * Created by CX on 2018/8/20 0020.
11
+ */
12
+public abstract class JedisPoolFactory {
13
+    private static JedisPool pool;
14
+
15
+
16
+    private synchronized static JedisPool getJedisPool() {
17
+        if (pool == null) {
18
+            String host = PropertiesUtil.getProperty("spring.redis.host");
19
+            Integer port = PropertiesUtil.getInteger("spring.redis.port");
20
+            String password = PropertiesUtil.getProperty("spring.redis.password");
21
+            JedisPoolConfig config = new JedisPoolConfig();
22
+            config.setMaxTotal(PropertiesUtil.getInteger("spring.redis.pool.max-total"));
23
+            config.setMaxIdle(PropertiesUtil.getInteger("spring.redis.pool.max-idle"));
24
+            config.setMaxWaitMillis(PropertiesUtil.getInteger("spring.redis.pool.max-wait-millis"));
25
+            config.setTestOnBorrow(true);
26
+            pool = new JedisPool(config, host, port,2000,password);
27
+        }
28
+        return pool;
29
+    }
30
+
31
+
32
+    private synchronized static JedisPool getDefaultJedisPool() {
33
+        if (pool == null) {
34
+            String host = "127.0.0.1";
35
+            Integer port = 6379;
36
+            JedisPoolConfig config = new JedisPoolConfig();
37
+            config.setMaxTotal(100);
38
+            config.setMaxIdle(20);
39
+            config.setMaxWaitMillis(10000);
40
+            config.setTestOnBorrow(true);
41
+            pool = new JedisPool(config, host, port);
42
+        }
43
+        return pool;
44
+    }
45
+
46
+    /**
47
+     * 使用默认127.0.0.1和默认6379端口
48
+     *
49
+     * @return
50
+     */
51
+    public synchronized static Jedis getDefaultJedis() {
52
+        if (pool == null) {
53
+            return getDefaultJedisPool().getResource();
54
+        } else {
55
+            return pool.getResource();
56
+        }
57
+    }
58
+
59
+
60
+    /**
61
+     * 读数据库userRedisIp和userRedisPort,如果没有读取到报错
62
+     */
63
+    public synchronized static Jedis getJedis() {
64
+        if (pool == null) {
65
+            return getJedisPool().getResource();
66
+        } else {
67
+            return pool.getResource();
68
+        }
69
+    }
70
+
71
+}

+ 162 - 0
src/main/java/com/dashitech/redis/core/RedisHashCmd.java

@@ -0,0 +1,162 @@
1
+package com.dashitech.redis.core;
2
+
3
+import redis.clients.jedis.Jedis;
4
+
5
+import java.util.HashMap;
6
+import java.util.List;
7
+import java.util.Map;
8
+import java.util.Set;
9
+
10
+/**
11
+ * Redis键值队列,元素key不可重复,注意并发问题
12
+ * Created by CX on 2018/8/20 0020.
13
+ */
14
+public class RedisHashCmd {
15
+
16
+    public static void main(String[] args) {
17
+        Map<String, String> map = new HashMap<>();
18
+        map.put("A", "1");
19
+        map.put("B", "2");
20
+
21
+        JedisPoolFactory.getDefaultJedis();
22
+        RedisHashCmd redisMap = new RedisHashCmd();
23
+        redisMap.putAll("MapA", map);
24
+
25
+
26
+        redisMap.put("MapA", "C", "3");
27
+        redisMap.put("MapA", "C", "4");
28
+
29
+        System.out.println(redisMap.containsKey("MapA", "C"));
30
+        System.out.println(redisMap.get("MapA", "C"));
31
+        System.out.println(redisMap.values("MapA"));
32
+        redisMap.remove("MapA", "A");
33
+
34
+        redisMap.drop("MapA");
35
+    }
36
+
37
+    /**
38
+     * 新增,如果队列不存在,新建这个队列,如果存在直接覆盖键和值
39
+     *
40
+     * @param name  队列名称
41
+     * @param key   主键
42
+     * @param value 值
43
+     */
44
+    public static void put(String name, String key, String value) {
45
+        Jedis jedis = JedisPoolFactory.getJedis();
46
+        try {
47
+            jedis.hset(name, key, value);
48
+        } finally {
49
+            jedis.close();
50
+        }
51
+    }
52
+
53
+    /**
54
+     * 批量新增,如果队列不存在,新建这个队列,如果存在直接覆盖键和值
55
+     */
56
+    public static void putAll(String name, Map<String, String> map) {
57
+        Jedis jedis = JedisPoolFactory.getJedis();
58
+        try {
59
+            jedis.hmset(name, map);
60
+        } catch (Exception ex) {
61
+            ex.printStackTrace();
62
+        } finally {
63
+            jedis.close();
64
+        }
65
+    }
66
+
67
+    /**
68
+     * 删除key和对应值
69
+     */
70
+    public static void remove(String name, String key) {
71
+        Jedis jedis = JedisPoolFactory.getJedis();
72
+        try {
73
+            jedis.hdel(name, key);
74
+        }catch (Exception ex) {
75
+            ex.printStackTrace();
76
+        }finally {
77
+            jedis.close();
78
+        }
79
+    }
80
+
81
+    /**
82
+     * 直接删除队列本身
83
+     */
84
+    public static void drop(String name) {
85
+        Jedis jedis = JedisPoolFactory.getJedis();
86
+        try {
87
+            jedis.del(name);
88
+        } finally {
89
+            jedis.close();
90
+        }
91
+    }
92
+
93
+    /**
94
+     * 获取key对应值
95
+     */
96
+    public static String get(String name, String key) {
97
+        Jedis jedis = JedisPoolFactory.getJedis();
98
+        try {
99
+            return jedis.hget(name, key);
100
+        } finally {
101
+            jedis.close();
102
+        }
103
+    }
104
+
105
+    /**
106
+     * key集合
107
+     */
108
+    public static Set<String> keySet(String name) {
109
+        Jedis jedis = JedisPoolFactory.getJedis();
110
+        try {
111
+            return jedis.hkeys(name);
112
+        } finally {
113
+            jedis.close();
114
+        }
115
+    }
116
+
117
+    /**
118
+     * value集合
119
+     */
120
+    public static List<String> values(String name) {
121
+        Jedis jedis = JedisPoolFactory.getJedis();
122
+        try {
123
+            return jedis.hvals(name);
124
+        } finally {
125
+            jedis.close();
126
+        }
127
+    }
128
+
129
+    public static Map<String, String> getAll(String name) {
130
+        Jedis jedis = JedisPoolFactory.getJedis();
131
+        try {
132
+            return jedis.hgetAll(name);
133
+        } finally {
134
+            jedis.close();
135
+        }
136
+    }
137
+
138
+    /**
139
+     * 是否存在这个key
140
+     */
141
+    public static boolean containsKey(String name, String key) {
142
+        Jedis jedis = JedisPoolFactory.getJedis();
143
+        try {
144
+            return jedis.hexists(name, key);
145
+        } finally {
146
+            jedis.close();
147
+        }
148
+    }
149
+
150
+    /**
151
+     * 队列大小
152
+     */
153
+    public static Long size(String name) {
154
+        Jedis jedis = JedisPoolFactory.getJedis();
155
+        try {
156
+            return jedis.hlen(name);
157
+        } finally {
158
+            jedis.close();
159
+        }
160
+    }
161
+
162
+}

+ 41 - 0
src/main/java/com/dashitech/redis/core/RedisKeys.java

@@ -0,0 +1,41 @@
1
+package com.dashitech.redis.core;
2
+
3
+/**
4
+ * Created by chi on 2020/6/12.
5
+ */
6
+public class RedisKeys {
7
+
8
+    /**
9
+     * 自动建单订阅
10
+     */
11
+    public static final String ITSM_ORDER_CREATE_PUBSUB = "itsm_order_create_pubsub";
12
+
13
+    /**
14
+     * 任务类型
15
+     */
16
+    public static final String ITSM_TASKTYPE_HASH = "itsm_taskType_hash";
17
+
18
+    /**
19
+     * 自动建单,消息队列
20
+     */
21
+    public static final String ITSM_CREATE_ORDER_LIST = "itsm_create_order_list";
22
+    public static final String ITSM_FLOW_ORDER_LIST = "itsm_flow_order_list";
23
+
24
+    /**
25
+     * 科室变更消息订阅
26
+     */
27
+    public static final String ITSM_DEPT_CHANGED_PUBSUB = "itsm_dept_changed_pubsub";
28
+
29
+
30
+    /**
31
+     * 手术临床消息
32
+     */
33
+    public static final String ITSM_SURGERY_CLINICAL_MSG_LIST = "itsm_surgery_clinical_msg_list";
34
+
35
+
36
+    /**
37
+     * 字典表变更消息订阅
38
+     */
39
+    public static final String ITSM_DICTIONARY_CHANGED_PUBSUB = "itsm_dictionary_changed_pubsub";
40
+
41
+}

+ 181 - 0
src/main/java/com/dashitech/redis/core/RedisListCmd.java

@@ -0,0 +1,181 @@
1
+package com.dashitech.redis.core;
2
+
3
+import redis.clients.jedis.Jedis;
4
+
5
+import java.util.ArrayList;
6
+import java.util.List;
7
+
8
+/**
9
+ * Redis队列,元素可重复,注意并发问题
10
+ * Created by CX on 2018/8/20 0020.
11
+ */
12
+public class RedisListCmd {
13
+
14
+    public static void main(String[] args) {
15
+        JedisPoolFactory.getDefaultJedis();
16
+        RedisListCmd redisList = new RedisListCmd();
17
+
18
+        redisList.add("AAAAAAAAA", "A");
19
+        redisList.add("AAAAAAAAA", "B");
20
+        redisList.add("AAAAAAAAA", 0, "C");
21
+        redisList.add("AAAAAAAAA", "A");
22
+
23
+        List<String> list = new ArrayList<>();
24
+        list.add("1111");
25
+        list.add("2222");
26
+        redisList.addAll("AAAAAAAAA", list);
27
+
28
+        System.out.println(redisList.indexOf("AAAAAAAAA", "A"));
29
+        System.out.println(redisList.contains("AAAAAAAAA", "B"));
30
+        System.out.println(redisList.get("AAAAAAAAA", 1));
31
+        System.out.println(redisList.get("AAAAAAAAA"));
32
+        System.out.println(redisList.size("AAAAAAAAA"));
33
+
34
+        redisList.remove("AAAAAAAAA", "B");
35
+
36
+        redisList.drop("AAAAAAAAA");
37
+
38
+    }
39
+
40
+    /**
41
+     * 新增,如果队列不存在,新建这个队列,如果存在插入值到队列最后面
42
+     *
43
+     * @param name  队列名称
44
+     * @param value 值
45
+     */
46
+    public static void add(String name, String value) {
47
+        Jedis jedis = JedisPoolFactory.getJedis();
48
+        try {
49
+            jedis.rpush(name, value);
50
+        } finally {
51
+            jedis.close();
52
+        }
53
+    }
54
+
55
+    /**
56
+     * 在指定下标插入值,注意!原下标值会被当前值覆盖!如果下标出错,会报错
57
+     */
58
+    public static void add(String name, int index, String value) {
59
+        Jedis jedis = JedisPoolFactory.getJedis();
60
+        try {
61
+            jedis.lset(name, index, value);
62
+        } finally {
63
+            jedis.close();
64
+        }
65
+    }
66
+
67
+    /**
68
+     * 批量新增,如果队列不存在,新建这个队列,如果存在插入值到队列最后面
69
+     */
70
+    public static void addAll(String name, List<String> list) {
71
+        Jedis jedis = JedisPoolFactory.getJedis();
72
+        try {
73
+            if (list != null && list.size() > 0) {
74
+                String[] values = new String[list.size()];
75
+                for (int i = 0; i < list.size(); i++) {
76
+                    values[i] = list.get(i);
77
+                }
78
+                jedis.rpush(name, values);
79
+            }
80
+        } finally {
81
+            jedis.close();
82
+        }
83
+    }
84
+
85
+    /**
86
+     * 删除所有和value值相等的对象
87
+     */
88
+    public static void remove(String name, String value) {
89
+        Jedis jedis = JedisPoolFactory.getJedis();
90
+        try {
91
+            jedis.lrem(name, 0, value);
92
+        } finally {
93
+            jedis.close();
94
+        }
95
+    }
96
+
97
+    /**
98
+     * 直接删除队列本身
99
+     */
100
+    public static void drop(String name) {
101
+        Jedis jedis = JedisPoolFactory.getJedis();
102
+        try {
103
+            jedis.del(name);
104
+        } finally {
105
+            jedis.close();
106
+        }
107
+    }
108
+
109
+    /**
110
+     * 根据下标获取值
111
+     */
112
+    public static String get(String name, int index) {
113
+        Jedis jedis = JedisPoolFactory.getJedis();
114
+        try {
115
+            return jedis.lindex(name, index);
116
+        } finally {
117
+            jedis.close();
118
+        }
119
+    }
120
+
121
+    /**
122
+     * 获取所有值
123
+     */
124
+    public static List<String> get(String name) {
125
+        Jedis jedis = JedisPoolFactory.getJedis();
126
+        try {
127
+            return jedis.lrange(name, 0, -1);
128
+        } finally {
129
+            jedis.close();
130
+        }
131
+    }
132
+
133
+    /**
134
+     * 获取并移除列表第一个值,如果队列空了,返回null
135
+     */
136
+    public static String pop(String name) {
137
+        Jedis jedis = JedisPoolFactory.getJedis();
138
+        try {
139
+            return jedis.lpop(name);
140
+        } finally {
141
+            jedis.close();
142
+        }
143
+    }
144
+
145
+    /**
146
+     * 直接比对返回下标
147
+     */
148
+    public static int indexOf(String name, String value) {
149
+        List<String> list = get(name);
150
+        if (list != null && list.size() > 0) {
151
+            for (int i = 0; i < list.size(); i++) {
152
+                String _value = list.get(i);
153
+                if (_value.equals(value)) {
154
+                    return i;
155
+                }
156
+            }
157
+        }
158
+        return -1;
159
+    }
160
+
161
+    /**
162
+     * 直接返回是否包含
163
+     */
164
+    public static boolean contains(String name, String value) {
165
+        int index = indexOf(name, value);
166
+        return index > -1;
167
+    }
168
+
169
+    /**
170
+     * 队列大小
171
+     */
172
+    public static Long size(String name) {
173
+        Jedis jedis = JedisPoolFactory.getJedis();
174
+        try {
175
+            return jedis.llen(name);
176
+        } finally {
177
+            jedis.close();
178
+        }
179
+    }
180
+
181
+}

+ 46 - 0
src/main/java/com/dashitech/redis/core/RedisPubSubCmd.java

@@ -0,0 +1,46 @@
1
+package com.dashitech.redis.core;
2
+
3
+import org.apache.commons.logging.Log;
4
+import org.apache.commons.logging.LogFactory;
5
+import redis.clients.jedis.Jedis;
6
+import redis.clients.jedis.JedisPubSub;
7
+
8
+/**
9
+ * Redis发布和订阅
10
+ * Created by CX on 2018/8/20 0020.
11
+ */
12
+public class RedisPubSubCmd {
13
+    private static Log log = LogFactory.getLog(RedisPubSubCmd.class);
14
+
15
+    public static void main(String[] args) {
16
+        JedisPoolFactory.getDefaultJedis();
17
+
18
+    }
19
+
20
+    public static boolean subscribe(JedisPubSub jedisPubSub, String topic) {
21
+        final Jedis jedis = JedisPoolFactory.getJedis();
22
+        try {
23
+            jedis.subscribe(jedisPubSub, topic);
24
+        } catch (Exception ex) {
25
+            ex.printStackTrace();
26
+            return false;
27
+        } finally {
28
+            jedis.close();
29
+        }
30
+        return true;
31
+    }
32
+
33
+
34
+    public static void publish(String topic, String message) {
35
+        Jedis jedis = JedisPoolFactory.getJedis();
36
+        try {
37
+            jedis.publish(topic, message);
38
+        } catch (Exception ex) {
39
+            ex.printStackTrace();
40
+        } finally {
41
+            jedis.close();
42
+        }
43
+    }
44
+
45
+
46
+}

+ 5 - 0
src/main/java/com/dashitech/redis/core/RedisQueueMonitor.java

@@ -0,0 +1,5 @@
1
+package com.dashitech.redis.core;
2
+
3
+
4
+public class RedisQueueMonitor {
5
+}

+ 149 - 0
src/main/java/com/dashitech/redis/core/RedisStringCmd.java

@@ -0,0 +1,149 @@
1
+package com.dashitech.redis.core;
2
+
3
+import redis.clients.jedis.Jedis;
4
+
5
+/**
6
+ * Redis字符串,注意并发问题
7
+ * Created by CX on 2018/8/20 0020.
8
+ */
9
+public class RedisStringCmd {
10
+
11
+    public static void main(String[] args) {
12
+        JedisPoolFactory.getDefaultJedis();
13
+
14
+        RedisStringCmd.drop("testString");
15
+        RedisStringCmd.set("testString","ABC");
16
+        System.out.println(RedisStringCmd.getset("testString", "CBA"));
17
+        System.out.println(RedisStringCmd.getset("testString111", "CBA"));
18
+        RedisStringCmd.append("testString","DEF");
19
+        System.out.println(RedisStringCmd.get("testString"));
20
+    }
21
+
22
+    /**
23
+     * 新增,如果已存在,覆盖当前值
24
+     * @param name  名称
25
+     * @param value 值
26
+     */
27
+    public static void set(String name, String value) {
28
+        Jedis jedis = JedisPoolFactory.getJedis();
29
+        try {
30
+            jedis.set(name, value);
31
+        } finally {
32
+            jedis.close();
33
+        }
34
+    }
35
+
36
+    public static void set(byte[] name, byte[] value) {
37
+        Jedis jedis = JedisPoolFactory.getJedis();
38
+        try {
39
+            jedis.set(name, value);
40
+        } finally {
41
+            jedis.close();
42
+        }
43
+    }
44
+
45
+    /**
46
+     * 有生命周期的新增,如果已存在,覆盖当前值和时间
47
+     * @param seconds  时间秒数
48
+     */
49
+    public static void setex(String name, String value,int seconds) {
50
+        Jedis jedis = JedisPoolFactory.getJedis();
51
+        try {
52
+            jedis.setex(name, seconds,value);
53
+        } finally {
54
+            jedis.close();
55
+        }
56
+    }
57
+
58
+    public static void setex(byte[] name, byte[] value,int seconds) {
59
+        Jedis jedis = JedisPoolFactory.getJedis();
60
+        try {
61
+            jedis.setex(name, seconds, value);
62
+        } finally {
63
+            jedis.close();
64
+        }
65
+    }
66
+
67
+    /**
68
+     *  key不存在时才成功
69
+     * @return 成功1 失败 0
70
+     */
71
+    public static Long setnx(String name,String value) {
72
+        Jedis jedis = JedisPoolFactory.getJedis();
73
+        try {
74
+            return jedis.setnx(name, value);
75
+        } finally {
76
+            jedis.close();
77
+        }
78
+    }
79
+
80
+    /**
81
+     * 设置值,并返回旧值,旧值不存在时返回null
82
+     */
83
+    public static String getset(String name,String value) {
84
+        Jedis jedis = JedisPoolFactory.getJedis();
85
+        try {
86
+           return jedis.getSet(name, value);
87
+        } finally {
88
+            jedis.close();
89
+        }
90
+    }
91
+
92
+    /**
93
+     * 追加值到末尾,如果不存在key,新增
94
+     */
95
+    public static void append(String name,String value) {
96
+        Jedis jedis = JedisPoolFactory.getJedis();
97
+        try {
98
+            jedis.append(name, value);
99
+        } finally {
100
+            jedis.close();
101
+        }
102
+    }
103
+
104
+    /**
105
+     * 直接删除key
106
+     */
107
+    public static void drop(String name) {
108
+        Jedis jedis = JedisPoolFactory.getJedis();
109
+        try {
110
+            jedis.del(name);
111
+        } finally {
112
+            jedis.close();
113
+        }
114
+    }
115
+
116
+    /**
117
+     * 获取值
118
+     */
119
+    public static String get(String name) {
120
+        Jedis jedis = JedisPoolFactory.getJedis();
121
+        try {
122
+            return jedis.get(name);
123
+        } finally {
124
+            jedis.close();
125
+        }
126
+    }
127
+
128
+    public static byte[] get(byte[] name) {
129
+        Jedis jedis = JedisPoolFactory.getJedis();
130
+        try {
131
+            return jedis.get(name);
132
+        } finally {
133
+            jedis.close();
134
+        }
135
+    }
136
+
137
+    /**
138
+     * 值大小
139
+     */
140
+    public static Long size(String name) {
141
+        Jedis jedis = JedisPoolFactory.getJedis();
142
+        try {
143
+            return jedis.strlen(name);
144
+        } finally {
145
+            jedis.close();
146
+        }
147
+    }
148
+
149
+}

+ 107 - 0
src/main/java/com/dashitech/utils/CaptchaUtil.java

@@ -0,0 +1,107 @@
1
+package com.dashitech.utils;
2
+
3
+import java.awt.Color;
4
+import java.awt.Font;
5
+import java.awt.Graphics;
6
+import java.awt.image.BufferedImage;
7
+import java.io.IOException;
8
+import java.util.Random;
9
+
10
+import javax.imageio.ImageIO;
11
+import javax.servlet.http.HttpServletResponse;
12
+
13
+public class CaptchaUtil {
14
+	
15
+	private String code = "";
16
+	private BufferedImage image;
17
+	
18
+	public String getCode() {
19
+		return code;
20
+	}
21
+	public void setCode(String code) {
22
+		this.code = code;
23
+	}
24
+	public BufferedImage getImage() {
25
+		return image;
26
+	}
27
+	public void setImage(BufferedImage image) {
28
+		this.image = image;
29
+	}
30
+	
31
+	public CaptchaUtil() {
32
+		init();
33
+	}
34
+
35
+	private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
36
+		Random random = new Random();
37
+		if (fc > 255)
38
+			fc = 255;
39
+		if (bc > 255)
40
+			bc = 255;
41
+		int r = fc + random.nextInt(bc - fc);
42
+		int g = fc + random.nextInt(bc - fc);
43
+		int b = fc + random.nextInt(bc - fc);
44
+		return new Color(r, g, b);
45
+	}
46
+
47
+	private void init() {
48
+		// 在内存中创建图象
49
+		int width=60, height=20;
50
+		image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
51
+		
52
+		// 获取图形上下文
53
+		Graphics g = image.getGraphics();
54
+		
55
+		//生成随机类
56
+		Random random = new Random();
57
+		
58
+		// 设定背景色
59
+		g.setColor(getRandColor(200,250));
60
+		g.fillRect(0, 0, width, height);
61
+		
62
+		//设定字体
63
+		g.setFont(new Font("Times New Roman",Font.PLAIN,18));
64
+		
65
+		//画边框
66
+		//g.setColor(new Color());
67
+		//g.drawRect(0,0,width-1,height-1);
68
+		
69
+		// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
70
+		g.setColor(getRandColor(160,200));
71
+		for (int i=0;i<155;i++)
72
+		{
73
+		 int x = random.nextInt(width);
74
+		 int y = random.nextInt(height);
75
+		        int xl = random.nextInt(12);
76
+		        int yl = random.nextInt(12);
77
+		 g.drawLine(x,y,x+xl,y+yl);
78
+		}
79
+		
80
+		// 取随机产生的认证码(4位数字)
81
+		for (int i=0;i<4;i++){
82
+		    String rand=String.valueOf(random.nextInt(10));
83
+		    code+=rand;
84
+		    // 将认证码显示到图象中
85
+		    g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
86
+		//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
87
+		    g.drawString(rand,13*i+6,16);
88
+		}
89
+		
90
+		// 图象生效
91
+		g.dispose();
92
+		
93
+	}
94
+	
95
+	public static void writeCaptcha(HttpServletResponse resp,CaptchaUtil captcha) {
96
+		resp.setHeader("Pragma","No-cache");
97
+		resp.setHeader("Cache-Control","no-cache");
98
+		resp.setDateHeader("Expires", 0);
99
+		BufferedImage image = captcha.getImage();
100
+		// 输出图象到页面
101
+		try {
102
+			ImageIO.write(image, "JPEG", resp.getOutputStream());
103
+		} catch (IOException e) {
104
+			e.printStackTrace();
105
+		}
106
+	}
107
+}

+ 228 - 0
src/main/java/com/dashitech/utils/CaptchaUtil2.java

@@ -0,0 +1,228 @@
1
+package com.dashitech.utils;
2
+
3
+import java.awt.Color;
4
+import java.awt.Font;
5
+import java.awt.Graphics;
6
+import java.awt.image.BufferedImage;
7
+import java.util.Random;
8
+
9
+public class CaptchaUtil2 {
10
+
11
+	/**
12
+	 * 验证码类型为仅数字,即0~9
13
+	 */
14
+	public static final int TYPE_NUM_ONLY = 0;
15
+
16
+	/**
17
+	 * 验证码类型为仅字母,即大小写字母混合
18
+	 */
19
+	public static final int TYPE_LETTER_ONLY = 1;
20
+
21
+	/**
22
+	 * 验证码类型为数字和大小写字母混合
23
+	 */
24
+	public static final int TYPE_ALL_MIXED = 2;
25
+
26
+	/**
27
+	 * 验证码类型为数字和大写字母混合
28
+	 */
29
+	public static final int TYPE_NUM_UPPER = 3;
30
+
31
+	/**
32
+	 * 验证码类型为数字和小写字母混合
33
+	 */
34
+	public static final int TYPE_NUM_LOWER = 4;
35
+
36
+	/**
37
+	 * 验证码类型为仅大写字母
38
+	 */
39
+	public static final int TYPE_UPPER_ONLY = 5;
40
+
41
+	/**
42
+	 * 验证码类型为仅小写字母
43
+	 */
44
+	public static final int TYPE_LOWER_ONLY = 6;
45
+
46
+	/**
47
+	 * 生成随机颜色
48
+	 */
49
+	private static Color generateRandomColor() {
50
+		Random random = new Random();
51
+		return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
52
+	}
53
+
54
+	/**
55
+	 * 生成图片验证码
56
+	 * 
57
+	 * @param type
58
+	 *            验证码类型,参见本类的静态属性
59
+	 * @param length
60
+	 *            验证码字符长度,要求大于0的整数
61
+	 * @param excludeString
62
+	 *            需排除的特殊字符
63
+	 * @param width
64
+	 *            图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)
65
+	 * @param height
66
+	 *            图片高度
67
+	 * @param interLine
68
+	 *            图片中干扰线的条数
69
+	 * @param randomLocation
70
+	 *            每个字符的高低位置是否随机
71
+	 * @param backColor
72
+	 *            图片颜色,若为null则表示采用随机颜色
73
+	 * @param foreColor
74
+	 *            字体颜色,若为null则表示采用随机颜色
75
+	 * @param lineColor
76
+	 *            干扰线颜色,若为null则表示采用随机颜色
77
+	 * @return 图片缓存对象
78
+	 */
79
+	public static BufferedImage generateImageCode(int type, int length, String excludeString, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor) {
80
+		String textCode = generateTextCode(type, length, excludeString);
81
+		return generateImageCode(textCode, width, height, interLine, randomLocation, backColor, foreColor, lineColor);
82
+	}
83
+
84
+	/**
85
+	 * 生成验证码字符串
86
+	 * 
87
+	 * @param type
88
+	 *            验证码类型,参见本类的静态属性
89
+	 * @param length
90
+	 *            验证码长度,要求大于0的整数
91
+	 * @param excludeString
92
+	 *            需排除的特殊字符(无需排除则为null)
93
+	 * @return 验证码字符串
94
+	 */
95
+	public static String generateTextCode(int type, int length, String excludeString) {
96
+		if (length <= 0) {
97
+			return "";
98
+		}
99
+		StringBuffer verifyCode = new StringBuffer();
100
+		int i = 0;
101
+		Random random = new Random();
102
+		switch (type) {
103
+		case TYPE_NUM_ONLY:
104
+			while (i < length) {
105
+				int t = random.nextInt(10);
106
+				// 排除特殊字符
107
+				if (null == excludeString || excludeString.indexOf(t + "") < 0) {
108
+					verifyCode.append(t);
109
+					i++;
110
+				}
111
+			}
112
+			break;
113
+		case TYPE_LETTER_ONLY:
114
+			while (i < length) {
115
+				int t = random.nextInt(123);
116
+				if ((t >= 97 || (t >= 65 && t <= 90)) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
117
+					verifyCode.append((char) t);
118
+					i++;
119
+				}
120
+			}
121
+			break;
122
+		case TYPE_ALL_MIXED:
123
+			while (i < length) {
124
+				int t = random.nextInt(123);
125
+				if ((t >= 97 || (t >= 65 && t <= 90) || (t >= 48 && t <= 57)) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
126
+					verifyCode.append((char) t);
127
+					i++;
128
+				}
129
+			}
130
+			break;
131
+		case TYPE_NUM_UPPER:
132
+			while (i < length) {
133
+				int t = random.nextInt(91);
134
+				if ((t >= 65 || (t >= 48 && t <= 57)) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
135
+					verifyCode.append((char) t);
136
+					i++;
137
+				}
138
+			}
139
+			break;
140
+		case TYPE_NUM_LOWER:
141
+			while (i < length) {
142
+				int t = random.nextInt(123);
143
+				if ((t >= 97 || (t >= 48 && t <= 57)) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
144
+					verifyCode.append((char) t);
145
+					i++;
146
+				}
147
+			}
148
+			break;
149
+		case TYPE_UPPER_ONLY:
150
+			while (i < length) {
151
+				int t = random.nextInt(91);
152
+				if ((t >= 65) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
153
+					verifyCode.append((char) t);
154
+					i++;
155
+				}
156
+			}
157
+			break;
158
+		case TYPE_LOWER_ONLY:
159
+			while (i < length) {
160
+				int t = random.nextInt(123);
161
+				if ((t >= 97) && (null == excludeString || excludeString.indexOf((char) t) < 0)) {
162
+					verifyCode.append((char) t);
163
+					i++;
164
+				}
165
+			}
166
+			break;
167
+		}
168
+		return verifyCode.toString();
169
+	}
170
+
171
+	/**
172
+	 * 已有验证码,生成验证码图片
173
+	 * 
174
+	 * @param textCode
175
+	 *            文本验证码
176
+	 * @param width
177
+	 *            图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)
178
+	 * @param height
179
+	 *            图片高度
180
+	 * @param interLine
181
+	 *            图片中干扰线的条数
182
+	 * @param randomLocation
183
+	 *            每个字符的高低位置是否随机
184
+	 * @param backColor
185
+	 *            图片颜色,若为null则表示采用随机颜色
186
+	 * @param foreColor
187
+	 *            字体颜色,若为null则表示采用随机颜色
188
+	 * @param lineColor
189
+	 *            干扰线颜色,若为null则表示采用随机颜色
190
+	 * @return 图片缓存对象
191
+	 */
192
+	public static BufferedImage generateImageCode(String textCode, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor) {
193
+		// 创建内存图像
194
+		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
195
+		// 获取图形上下文
196
+		Graphics graphics = bufferedImage.getGraphics();
197
+		// 画背景图
198
+		graphics.setColor(null == backColor ? generateRandomColor() : backColor);
199
+		graphics.fillRect(0, 0, width, height);
200
+		// 画干扰线
201
+		Random random = new Random();
202
+		if (interLine > 0) {
203
+			int x = 0, y = 0, x1 = width, y1 = 0;
204
+			for (int i = 0; i < interLine; i++) {
205
+				graphics.setColor(null == lineColor ? generateRandomColor() : lineColor);
206
+				y = random.nextInt(height);
207
+				y1 = random.nextInt(height);
208
+				graphics.drawLine(x, y, x1, y1);
209
+			}
210
+		}
211
+		// 字体大小为图片高度的80%
212
+		int fsize = (int) (height * 0.8);
213
+		int fx = height - fsize;
214
+		int fy = fsize;
215
+		// 设定字体
216
+		graphics.setFont(new Font("Default", Font.PLAIN, fsize));
217
+		// 写验证码字符
218
+		for (int i = 0; i < textCode.length(); i++) {
219
+			fy = randomLocation ? (int) ((Math.random() * 0.3 + 0.6) * height) : fy;
220
+			graphics.setColor(null == foreColor ? generateRandomColor() : foreColor);
221
+			// 将验证码字符显示到图象中
222
+			graphics.drawString(textCode.charAt(i) + "", fx, fy);
223
+			fx += fsize * 0.9;
224
+		}
225
+		graphics.dispose();
226
+		return bufferedImage;
227
+	}
228
+}

+ 250 - 0
src/main/java/com/dashitech/utils/CommonUtil.java

@@ -0,0 +1,250 @@
1
+package com.dashitech.utils;
2
+
3
+import org.apache.commons.lang.StringUtils;
4
+import org.slf4j.Logger;
5
+import org.slf4j.LoggerFactory;
6
+
7
+import java.io.File;
8
+import java.io.UnsupportedEncodingException;
9
+import java.lang.reflect.Method;
10
+import java.net.URL;
11
+import java.net.URLClassLoader;
12
+import java.net.URLDecoder;
13
+import java.net.URLEncoder;
14
+import java.util.*;
15
+
16
+/**
17
+ * 混杂工具类
18
+ * Created by CX on 2017/3/31 0031.
19
+ */
20
+public class CommonUtil {
21
+    private static final Logger LOG = LoggerFactory.getLogger(CommonUtil.class);
22
+
23
+    private CommonUtil(){}
24
+
25
+    public static <T> List<?> transList(List<?> list) {
26
+        return list;
27
+    }
28
+
29
+    /**
30
+     * 把新地址加入到classpath中
31
+     * @param path 新地址,绝对路劲
32
+     * @return  是否成功
33
+     */
34
+    public static boolean addJavaClassPath(String path) {
35
+        try {
36
+            File programRootDir = new File(path);
37
+            URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
38
+            Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
39
+            add.setAccessible(true);
40
+            add.invoke(classLoader, programRootDir.toURI().toURL());
41
+            return true;
42
+        } catch (Exception e) {
43
+            e.printStackTrace();
44
+        }
45
+        return false;
46
+    }
47
+
48
+    /**
49
+     * 在source的下标 start和end中间插入newStr
50
+     */
51
+    public static String cutInsertString(String source, int start, int end, String newStr) {
52
+        String startStr = source.substring(0, start);
53
+        String endStr = source.substring(end, source.length());
54
+        String result = startStr + newStr + endStr;
55
+        return result;
56
+    }
57
+
58
+    /**
59
+     * 获取中文类型长度,中文长度2,其他1
60
+     */
61
+    public static int getChineseLength(String source) {
62
+        int valueLength = 0;
63
+        String chinese = "[\u0391-\uFFE5]";
64
+		/* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */
65
+        for (int i = 0; i < source.length(); i++) {
66
+			/* 获取一个字符 */
67
+            String temp = source.substring(i, i + 1);
68
+			/* 判断是否为中文字符 */
69
+            if (temp.matches(chinese)) {
70
+				/* 中文字符长度为2 */
71
+                valueLength += 2;
72
+            } else {
73
+				/* 其他字符长度为1 */
74
+                valueLength += 1;
75
+            }
76
+        }
77
+        return valueLength;
78
+    }
79
+
80
+    /**
81
+     * 获取翻页数
82
+     *
83
+     * @param itemTotal
84
+     *            总条数
85
+     * @param PageCount
86
+     *            一页数
87
+     * @return 翻页数
88
+     */
89
+    public static int getPageTotal(Integer itemTotal, int PageCount) {
90
+        // 设置总页数
91
+        int total = 0;
92
+        if (itemTotal % PageCount == 0) {
93
+            total = itemTotal / PageCount;
94
+        } else {
95
+            total = (itemTotal / PageCount) + 1;
96
+        }
97
+        return total;
98
+    }
99
+
100
+    /**
101
+     * 自己写sql分页必须处理pageIndex
102
+     */
103
+    public static int getPageIndex(int pageIndex,int showCount) {
104
+        int result = 0;
105
+        if(pageIndex <= 1) {
106
+            result = 0;
107
+        }else if(pageIndex > 1) {
108
+            result = ((pageIndex * showCount) - showCount);
109
+        }
110
+        return result;
111
+    }
112
+
113
+    /**
114
+     * url中文编码
115
+     */
116
+    public static String urlEncode(String url) {
117
+        String s = url;
118
+        try {
119
+            s = URLEncoder.encode(url, "UTF-8");
120
+        } catch (UnsupportedEncodingException e) {
121
+            e.printStackTrace();
122
+        }
123
+        return s;
124
+    }
125
+
126
+    /**
127
+     * url中文解码
128
+     */
129
+    public static String urlDecode(String url) {
130
+        String s = url;
131
+        try {
132
+            s = URLDecoder.decode(url, "UTF-8");
133
+        } catch (UnsupportedEncodingException e) {
134
+            e.printStackTrace();
135
+        }
136
+        return s;
137
+    }
138
+
139
+    /**
140
+     * 排序
141
+     * @param list
142
+     * @param field 字段名称,必须有get方法
143
+     * @param fieldType 字段类型
144
+     */
145
+    public static void sort(List<?> list,final String field,final String fieldType) {
146
+        Collections.sort(list, new Comparator<Object>() {
147
+            public int compare(Object o1, Object o2) {
148
+                Method m = null;
149
+                try {
150
+                    String getKey = "get" + field.toUpperCase().charAt(0) + field.substring(1, field.length());
151
+                    m = o1.getClass().getMethod(getKey);
152
+                    Object o1Value = m.invoke(o1);
153
+
154
+                    m = o2.getClass().getMethod(getKey);
155
+                    Object o2Value = m.invoke(o2);
156
+
157
+                    if(o1Value == null && o2Value == null) {
158
+                        return 0;
159
+                    }else if(o1Value == null && o2Value != null) {
160
+                        return -1;
161
+                    }else if(o1Value != null && o2Value == null) {
162
+                        return 1;
163
+                    }
164
+
165
+                    if("Integer".equals(fieldType.toString())) {
166
+                        Integer _o1 = (Integer)o1Value;
167
+                        Integer _o2 = (Integer)o2Value;
168
+                        return _o1.compareTo(_o2);
169
+                    }else if("String".equals(fieldType.toString())) {
170
+                        String _o1 = (String)o1Value;
171
+                        String _o2 = (String)o2Value;
172
+                        return _o1.compareTo(_o2);
173
+                    }else if("StringNumber".equals(fieldType.toString())) {
174
+                        try{
175
+                            Double _o1 = Double.valueOf(o1Value.toString());
176
+                            Double _o2 = Double.valueOf(o2Value.toString());
177
+                            return _o1.compareTo(_o2);
178
+                        }catch (NumberFormatException ex) {
179
+                            ex.printStackTrace();
180
+                        }
181
+                    }
182
+                }catch (Exception e) {
183
+                    e.printStackTrace();
184
+                }
185
+                return 0;
186
+            }
187
+        });
188
+    }
189
+
190
+    /**
191
+     * 逻辑分页
192
+     *
193
+     * @param src
194
+     *            源数据
195
+     * @param start
196
+     *            分页页数,1起始
197
+     * @param size
198
+     *            分页limit
199
+     * @return 新的分页后的List
200
+     * @throws Exception
201
+     */
202
+    public static <T> List<T> paginateList(List<T> src, int start, int size) {
203
+        if(src == null) {
204
+            return Collections.emptyList();
205
+        }
206
+
207
+        List<T> list = null;
208
+        if(start <= 1) {
209
+            start = 0;
210
+        }else {
211
+            start = (start-1) * size;
212
+        }
213
+
214
+        size = size + start;
215
+        if (size > src.size()) {
216
+            size = src.size();
217
+        }
218
+
219
+        try {
220
+            list = src.subList(start, size);
221
+        } catch (Exception e) {
222
+            System.out.println("list.size:"+src.size()+"start:" + start + " , size" + size);
223
+            e.printStackTrace();
224
+        }
225
+        return list;
226
+    }
227
+
228
+
229
+    /**
230
+     * map.toString之后,转回map
231
+     */
232
+    public static Map<String,String> string2Map(String mapString) {
233
+        Map<String,String> map = new LinkedHashMap<String,String>();
234
+        try {
235
+            if(StringUtils.isNotEmpty(mapString)) {
236
+                String args = mapString.substring(1,mapString.length()-1);
237
+                String[] argArr = args.split(", ");
238
+                for (String entry : argArr) {
239
+                    int index = entry.indexOf("=");
240
+                    String key = entry.substring(0,index);
241
+                    String value = entry.substring(index+1);
242
+                    map.put(key, value);
243
+                }
244
+            }
245
+        }catch (Exception ex) {
246
+            ex.printStackTrace();
247
+        }
248
+        return map;
249
+    }
250
+}

+ 318 - 0
src/main/java/com/dashitech/utils/DateUtil.java

@@ -0,0 +1,318 @@
1
+package com.dashitech.utils;
2
+
3
+import java.text.ParseException;
4
+import java.text.SimpleDateFormat;
5
+import java.util.ArrayList;
6
+import java.util.Arrays;
7
+import java.util.Calendar;
8
+import java.util.Date;
9
+import java.util.List;
10
+import java.util.Locale;
11
+
12
+public class DateUtil {
13
+    private static final int FIRST_DAY = Calendar.MONDAY;
14
+    public final static SimpleDateFormat SDF_DATE = new SimpleDateFormat("yyyy-MM-dd");
15
+    public final static SimpleDateFormat SDF_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
16
+    
17
+    
18
+	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
19
+	
20
+	public static String formatTimestamp(Date date){
21
+		String formattedDate = dateFormat.format(date);
22
+		return formattedDate;
23
+	}
24
+	
25
+	public static Date parseTimestamp(String text){
26
+		try {
27
+			return dateFormat.parse(text);
28
+		} catch (ParseException e) {
29
+			// TODO Auto-generated catch block
30
+			e.printStackTrace();
31
+		}
32
+		return null;
33
+	}
34
+
35
+    private static void setToFirstDay(Calendar calendar) {
36
+        while (calendar.get(Calendar.DAY_OF_WEEK) != FIRST_DAY) {
37
+            calendar.add(Calendar.DATE, -1);
38
+        }
39
+    }
40
+    
41
+    public static String formatDateTime (Date date) {
42
+    	return SDF_DATETIME.format(date);
43
+    }
44
+    
45
+    public static String formatDate (Date date) {
46
+    	return SDF_DATE.format(date);
47
+    }
48
+
49
+	public static Date parseUTCDateTime(String date){
50
+		Date d = null;
51
+		try {
52
+			date = date.replace("Z", " UTC");//注意是空格+UTC
53
+			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//注意格式化的表达式
54
+			d = format.parse(date);
55
+		} catch (ParseException e) {
56
+			e.printStackTrace();
57
+		}
58
+		return d;
59
+	}
60
+    
61
+    public static Date parseDateTime(String date){
62
+    	Date d = null;
63
+    	try {
64
+			d = SDF_DATETIME.parse(date);
65
+		} catch (ParseException e) {
66
+			e.printStackTrace();
67
+		}
68
+		return d;
69
+    }
70
+    
71
+    public static Date parseDate(String date){
72
+    	Date d = null;
73
+    	try {
74
+			d = SDF_DATE.parse(date);
75
+		} catch (ParseException e) {
76
+			e.printStackTrace();
77
+		}
78
+		return d;
79
+    }
80
+
81
+    /**
82
+     * 从周一开始7天
83
+     */
84
+    public static List<String> getWeekdays(Date date) {
85
+        List<String> list = new ArrayList<String>();
86
+        Calendar calendar = Calendar.getInstance();
87
+        calendar.setTime(date);
88
+        
89
+        setToFirstDay(calendar);
90
+        
91
+        for (int i = 0; i < 7; i++) {
92
+            list.add(SDF_DATE.format(calendar.getTime()));
93
+            calendar.add(Calendar.DATE, 1);
94
+        }
95
+        return list;
96
+    }
97
+    
98
+    /**
99
+     * 从周一开始7天
100
+     */
101
+    public static List<String> getWeekdaysAndColor(Date date) {
102
+        List<String> list = new ArrayList<String>();
103
+        Calendar calendar = Calendar.getInstance();
104
+        calendar.setTime(date);
105
+        
106
+        setToFirstDay(calendar);
107
+        
108
+        for (int i = 0; i < 7; i++) {
109
+        	if(i == 6 || i == 5)
110
+                list.add("<font class='weekColor'>" + SDF_DATE.format(calendar.getTime()) + "</font>");
111
+        	else
112
+        		list.add(SDF_DATE.format(calendar.getTime()));
113
+            calendar.add(Calendar.DATE, 1);
114
+        }
115
+        return list;
116
+    }
117
+    public static String getMonday(Date date) {
118
+        Calendar calendar = Calendar.getInstance();
119
+        calendar.setTime(date);
120
+        setToFirstDay(calendar);
121
+        return SDF_DATE.format(calendar.getTime());
122
+    }
123
+    
124
+    public static String getSunday(Date date) {
125
+        Calendar calendar = Calendar.getInstance();
126
+        calendar.setTime(date);
127
+        setToFirstDay(calendar);
128
+        calendar.add(Calendar.DATE, 6);
129
+        return SDF_DATE.format(calendar.getTime());
130
+    }
131
+    
132
+    /**
133
+     * 当前日期  + 7
134
+     * @param date
135
+     * @return
136
+     */
137
+    public static Date getAfterWeekByDay(Date date) {
138
+        Calendar calendar = Calendar.getInstance();
139
+        calendar.setTime(date);
140
+        calendar.add(Calendar.DATE, 7);
141
+        return calendar.getTime();
142
+    }
143
+    
144
+    /**
145
+     * 当前日期  - 7
146
+     * @param date
147
+     * @return
148
+     */
149
+    public static Date getBeforeWeekByDay(Date date) {
150
+        Calendar calendar = Calendar.getInstance();
151
+        calendar.setTime(date);
152
+        calendar.add(Calendar.DATE, -7);
153
+        return calendar.getTime();
154
+    }
155
+
156
+    /**
157
+	 * 获取星期一
158
+	 * 
159
+	 * @param date 传入的日期
160
+	 * @return
161
+	 */
162
+	public static Date getMOnday(Date date) {
163
+		Calendar cal = Calendar.getInstance();
164
+		cal.setTime(date);
165
+		// 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
166
+		int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
167
+		if (1 == dayWeek) {
168
+			cal.add(Calendar.DAY_OF_MONTH, -1);
169
+		}
170
+		cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
171
+		int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
172
+		cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
173
+		return cal.getTime();
174
+	}
175
+
176
+	/**
177
+	 * 判断传入的日期的周数是否大于当前日期的周数
178
+	 * @param dutyDate 传入的日期
179
+	 * @return
180
+	 */
181
+	public static boolean isBeforeThisWeek(Date dutyDate){ 
182
+		return getMOnday(new Date()).getTime() < getMOnday(dutyDate).getTime();
183
+	}
184
+	
185
+	public static boolean equals(Date d1,Date d2,SimpleDateFormat sdf) {
186
+	    String a = sdf.format(d1);
187
+	    String b = sdf.format(d2);
188
+	    if(a != null && b != null) {
189
+	        return a.equals(b);
190
+	    }
191
+	    return false;
192
+	}
193
+
194
+	public static String ignoreFrmat(String source,SimpleDateFormat sdf) {
195
+	    List<String> list = Arrays.asList("yyyy-M-d","yyyy-MM-dd","yyyy-M","yyyy-MM","yyyy/M/d","yyyy/MM/dd","yyyy/M","yyyy/MM");
196
+	    String result = "";
197
+	    for(int i = 0;i<list.size();i++) {
198
+	        try {
199
+                Date d = new SimpleDateFormat(list.get(i)).parse(source);
200
+                result = sdf.format(d);
201
+                return result;
202
+            } catch (Exception e) {
203
+                
204
+            }
205
+	    }
206
+	    try {
207
+            Date d = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",Locale.US).parse(source);
208
+            result = sdf.format(d);
209
+        } catch (Exception e) {
210
+        }
211
+	    return result;
212
+	}
213
+	
214
+	public static Date ignoreFrmat_Date(String source,SimpleDateFormat sdf) {
215
+	    String result = ignoreFrmat(source,sdf);
216
+	    Date d = null;
217
+        try {
218
+            d = sdf.parse(result);
219
+        } catch (ParseException e) {
220
+            e.printStackTrace();
221
+        }
222
+	    return d;
223
+	}
224
+	
225
+	/**
226
+	 * 两个时间相差天数
227
+	 * date1  开始时间
228
+	 * date2  结束时间
229
+	 * 
230
+	 * */
231
+	public static int getMonthSpace(String staticTime, String endTime) throws ParseException {
232
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
233
+		long startT=sdf.parse(staticTime).getTime(); //定义开始时间
234
+		long endT=sdf.parse(endTime).getTime();  //定义结束时间
235
+		long overDay=(endT-startT) /(1000 * 60 * 60 * 24);
236
+		int day = Integer.parseInt(String.valueOf(overDay));
237
+		return day;
238
+	}
239
+	
240
+	/**
241
+	 * 获取年份
242
+	 * */
243
+	private static int getYear(String date1) throws ParseException { 
244
+	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
245
+	    Calendar cal = Calendar.getInstance(); 
246
+	    Date dt = null; 
247
+	    try { 
248
+	      dt = sdf.parse(date1); 
249
+	      cal.setTime(dt); 
250
+	    } catch (ParseException e) { 
251
+	      // TODO Auto-generated catch block 
252
+	      e.printStackTrace(); 
253
+	    } 
254
+	    int year = cal.get(Calendar.YEAR); 
255
+	    int month = cal.get(Calendar.MONTH) + 1; 
256
+	    int day = cal.get(Calendar.DAY_OF_MONTH); 
257
+	    int hour = cal.get(Calendar.HOUR_OF_DAY); 
258
+	    int minute = cal.get(Calendar.MINUTE); 
259
+	    int second = cal.get(Calendar.SECOND); 
260
+	    return year;
261
+	  }
262
+
263
+	public static boolean isInDates(Date date, Date startDate, Date endDate) {
264
+		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
265
+		Date myDate = null;
266
+		Date dateBegin = null;
267
+		Date dateEnd = null;
268
+		String strDate = sd.format(date);
269
+		String strDateBegin = sd.format(startDate);
270
+		String strDateEnd = sd.format(endDate);
271
+		try {
272
+			myDate = sd.parse(strDate);
273
+			dateBegin = sd.parse(strDateBegin);
274
+			dateEnd = sd.parse(strDateEnd);
275
+		} catch (ParseException e) {
276
+			// TODO Auto-generated catch block
277
+			e.printStackTrace();
278
+		}
279
+		strDate = String.valueOf(myDate);
280
+		strDateBegin = String.valueOf(dateBegin);
281
+		strDateEnd = String.valueOf(dateEnd);
282
+
283
+		int strDateH = Integer.parseInt(strDate.substring(11, 13));
284
+		int strDateM = Integer.parseInt(strDate.substring(14, 16));
285
+		int strDateS = Integer.parseInt(strDate.substring(17, 19));
286
+
287
+		int strDateBeginH = Integer.parseInt(strDateBegin.substring(11, 13));
288
+		int strDateBeginM = Integer.parseInt(strDateBegin.substring(14, 16));
289
+		//int strDateBeginS = Integer.parseInt(strDateBegin.substring(17,19));
290
+
291
+		int strDateEndH = Integer.parseInt(strDateEnd.substring(11, 13));
292
+		int strDateEndM = Integer.parseInt(strDateEnd.substring(14, 16));
293
+		//int strDateEndS = Integer.parseInt(strDateEnd.substring(17,19));
294
+
295
+		if ((strDateH >= strDateBeginH && strDateH <= strDateEndH)) {
296
+			if (strDateH > strDateBeginH && strDateH < strDateEndH) {
297
+				return true;
298
+			} else if (strDateH == strDateBeginH && strDateM > strDateBeginM && strDateH < strDateEndH) {
299
+				return true;
300
+			} else if (strDateH == strDateBeginH && strDateM == strDateBeginM && strDateH < strDateEndH) {
301
+				return true;
302
+			} else if (strDateH == strDateBeginH && strDateM == strDateBeginM && strDateH < strDateEndH) {
303
+				return true;
304
+			} else if (strDateH > strDateBeginH && strDateH == strDateEndH && strDateM < strDateEndM) {
305
+				return true;
306
+			} else if (strDateH > strDateBeginH && strDateH == strDateEndH && strDateM == strDateEndM) {
307
+				return true;
308
+			} else if (strDateH > strDateBeginH && strDateH == strDateEndH && strDateM == strDateEndM) {
309
+				return true;
310
+			} else {
311
+				return false;
312
+			}
313
+		} else {
314
+			return false;
315
+		}
316
+	}
317
+	
318
+}	

+ 670 - 0
src/main/java/com/dashitech/utils/DateUtil2.java

@@ -0,0 +1,670 @@
1
+package com.dashitech.utils;
2
+
3
+import java.text.ParseException;
4
+import java.text.SimpleDateFormat;
5
+import java.util.ArrayList;
6
+import java.util.Calendar;
7
+import java.util.Date;
8
+import java.util.GregorianCalendar;
9
+import java.util.HashMap;
10
+import java.util.List;
11
+import java.util.Map;
12
+
13
+import org.apache.commons.lang.StringUtils;
14
+
15
+public class DateUtil2 {
16
+
17
+    public static final String FORMAT_DATE = "yyyy-MM-dd";
18
+
19
+    public static final String FORMAT_TIME = "HH:mm:ss";
20
+
21
+    public static final String FORMAT_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
22
+
23
+    public static final SimpleDateFormat SDFD = new SimpleDateFormat(FORMAT_DATE);
24
+
25
+    public static final SimpleDateFormat SDFT = new SimpleDateFormat(FORMAT_TIME);
26
+
27
+    public static final SimpleDateFormat SDFDT = new SimpleDateFormat(FORMAT_DATE_TIME);
28
+
29
+    /**
30
+     * 得到以yyyy-MM-dd格式表示的当前日期字符串
31
+     */
32
+    public static String getCurrentDate() {
33
+        // return sdfd.format(new Date());
34
+        GregorianCalendar tGCalendar = new GregorianCalendar();
35
+        StringBuffer tStringBuffer = new StringBuffer(10);
36
+        int sYears = tGCalendar.get(Calendar.YEAR);
37
+        tStringBuffer.append(sYears);
38
+        tStringBuffer.append('-');
39
+        int sMonths = tGCalendar.get(Calendar.MONTH) + 1;
40
+        if (sMonths < 10) {
41
+            tStringBuffer.append('0');
42
+        }
43
+        tStringBuffer.append(sMonths);
44
+        tStringBuffer.append('-');
45
+        int sDays = tGCalendar.get(Calendar.DAY_OF_MONTH);
46
+        if (sDays < 10) {
47
+            tStringBuffer.append('0');
48
+        }
49
+        tStringBuffer.append(sDays);
50
+        String tString = tStringBuffer.toString();
51
+        return tString;
52
+    }
53
+
54
+    /**
55
+     * 得到以format格式表示的当前日期字符串
56
+     */
57
+    public static String getCurrentDate(String format) {
58
+        SimpleDateFormat t = new SimpleDateFormat(format);
59
+        return t.format(new Date());
60
+    }
61
+
62
+    /**
63
+     * 得到以HH:mm:ss表示的当前时间字符串
64
+     */
65
+    public static String getCurrentTime() {
66
+        // return sdft.format(new Date());
67
+        GregorianCalendar tGCalendar = new GregorianCalendar();
68
+        StringBuffer tStringBuffer = new StringBuffer(8);
69
+        int sHOUR = tGCalendar.get(Calendar.HOUR_OF_DAY);
70
+        if (sHOUR < 10) {
71
+            tStringBuffer.append('0');
72
+        }
73
+        tStringBuffer.append(sHOUR);
74
+        tStringBuffer.append(':');
75
+        int sMINUTE = tGCalendar.get(Calendar.MINUTE);
76
+        if (sMINUTE < 10) {
77
+            tStringBuffer.append('0');
78
+        }
79
+        tStringBuffer.append(sMINUTE);
80
+        tStringBuffer.append(':');
81
+        int sSECOND = tGCalendar.get(Calendar.SECOND);
82
+        if (sSECOND < 10) {
83
+            tStringBuffer.append('0');
84
+        }
85
+        tStringBuffer.append(sSECOND);
86
+        String tString = tStringBuffer.toString();
87
+        return tString;
88
+    }
89
+
90
+    /**
91
+     * 得到以format格式表示的当前时间字符串
92
+     */
93
+    public static String getCurrentTime(String format) {
94
+        SimpleDateFormat t = new SimpleDateFormat(format);
95
+        return t.format(new Date());
96
+    }
97
+
98
+    /**
99
+     * 得到以yyyy-MM-dd HH:mm:ss表示的当前时间字符串
100
+     */
101
+    public static String getCurrentDateTime() {
102
+        String format = FORMAT_DATE + " " + FORMAT_TIME;
103
+        return getCurrentDateTime(format);
104
+    }
105
+
106
+    public static int getDayOfWeek() {
107
+        Calendar cal = Calendar.getInstance();
108
+        return cal.get(Calendar.DAY_OF_WEEK);
109
+    }
110
+
111
+    public static int getDayOfWeek(Date date) {
112
+        Calendar cal = Calendar.getInstance();
113
+        cal.setTime(date);
114
+        return cal.get(Calendar.DAY_OF_WEEK);
115
+    }
116
+
117
+    public static int getDayOfMonth() {
118
+        Calendar cal = Calendar.getInstance();
119
+        return cal.get(Calendar.DAY_OF_MONTH);
120
+    }
121
+
122
+    public static int getDayOfMonth(Date date) {
123
+        Calendar cal = Calendar.getInstance();
124
+        cal.setTime(date);
125
+        return cal.get(Calendar.DAY_OF_MONTH);
126
+    }
127
+
128
+    // 获取某一个月的天数
129
+    public static int getMaxDayOfMonth(Date date) {
130
+        Calendar cal = Calendar.getInstance();
131
+        cal.setTime(date);
132
+        return cal.getActualMaximum(Calendar.DATE);
133
+    }
134
+
135
+    // 获取某月的第一天
136
+    public static String getFirstDayOfMonth(String date) {
137
+        Calendar cal = Calendar.getInstance();
138
+        cal.setTime(parse(date));
139
+        cal.set(Calendar.DAY_OF_MONTH, 1);
140
+        return SDFD.format(cal.getTime());
141
+    }
142
+
143
+    public static int getDayOfYear() {
144
+        Calendar cal = Calendar.getInstance();
145
+        return cal.get(Calendar.DAY_OF_YEAR);
146
+    }
147
+
148
+    public static int getDayOfYear(Date date) {
149
+        Calendar cal = Calendar.getInstance();
150
+        cal.setTime(date);
151
+        return cal.get(Calendar.DAY_OF_YEAR);
152
+    }
153
+
154
+    public static int getDayOfWeek(String date) {
155
+        Calendar cal = Calendar.getInstance();
156
+        cal.setTime(parse(date));
157
+        return cal.get(Calendar.DAY_OF_WEEK);
158
+    }
159
+
160
+    public static int getDayOfMonth(String date) {
161
+        Calendar cal = Calendar.getInstance();
162
+        cal.setTime(parse(date));
163
+        return cal.get(Calendar.DAY_OF_MONTH);
164
+    }
165
+
166
+    public static int getDayOfYear(String date) {
167
+        Calendar cal = Calendar.getInstance();
168
+        cal.setTime(parse(date));
169
+        return cal.get(Calendar.DAY_OF_YEAR);
170
+    }
171
+
172
+    public static String getCurrentDateTime(String format) {
173
+        SimpleDateFormat t = new SimpleDateFormat(format);
174
+        return t.format(new Date());
175
+    }
176
+
177
+    /**
178
+     * 输出只带日期的字符串
179
+     */
180
+    public static String toString(Date date) {
181
+        if (date == null) {
182
+            return "";
183
+        }
184
+        return SDFD.format(date);
185
+    }
186
+
187
+    /**
188
+     * 输出带有日期和时间的字符串
189
+     */
190
+    public static String toDateTimeString(Date date) {
191
+        if (date == null) {
192
+            return "";
193
+        }
194
+        return SDFDT.format(date);
195
+    }
196
+
197
+    /**
198
+     * 按指定的format输出日期字符串
199
+     */
200
+    public static String toString(Date date, String format) {
201
+        SimpleDateFormat t = new SimpleDateFormat(format);
202
+        return t.format(date);
203
+    }
204
+
205
+    /**
206
+     * 输出只带时间的字符串
207
+     */
208
+    public static String toTimeString(Date date) {
209
+        if (date == null) {
210
+            return "";
211
+        }
212
+        return SDFDT.format(date);
213
+    }
214
+
215
+    public static int compare(String date1, String date2) {
216
+        return compare(date1, date2, FORMAT_DATE);
217
+    }
218
+
219
+    public static int compareTime(String time1, String time2) {
220
+        return compareTime(time1, time2, FORMAT_TIME);
221
+    }
222
+
223
+    public static int compare(String date1, String date2, String format) {
224
+        Date d1 = parse(date1, format);
225
+        Date d2 = parse(date2, format);
226
+        return d1.compareTo(d2);
227
+    }
228
+
229
+    public static int compareTime(String time1, String time2, String format) {
230
+        String[] arr1 = time1.split(":");
231
+        String[] arr2 = time2.split(":");
232
+        if (arr1.length < 2) {
233
+            throw new RuntimeException("错误的时间值:" + time1);
234
+        }
235
+        if (arr2.length < 2) {
236
+            throw new RuntimeException("错误的时间值:" + time2);
237
+        }
238
+        int h1 = Integer.parseInt(arr1[0]);
239
+        int m1 = Integer.parseInt(arr1[1]);
240
+        int h2 = Integer.parseInt(arr2[0]);
241
+        int m2 = Integer.parseInt(arr2[1]);
242
+        int s1 = 0, s2 = 0;
243
+        if (arr1.length == 3) {
244
+            s1 = Integer.parseInt(arr1[2]);
245
+        }
246
+        if (arr2.length == 3) {
247
+            s2 = Integer.parseInt(arr2[2]);
248
+        }
249
+        if (h1 < 0 || h1 > 23 || m1 < 0 || m1 > 59 || s1 < 0 || s1 > 59) {
250
+            throw new RuntimeException("错误的时间值:" + time1);
251
+        }
252
+        if (h2 < 0 || h2 > 23 || m2 < 0 || m2 > 59 || s2 < 0 || s2 > 59) {
253
+            throw new RuntimeException("错误的时间值:" + time2);
254
+        }
255
+        if (h1 != h2) {
256
+            return h1 > h2 ? 1 : -1;
257
+        } else {
258
+            if (m1 == m2) {
259
+                if (s1 == s2) {
260
+                    return 0;
261
+                } else {
262
+                    return s1 > s2 ? 1 : -1;
263
+                }
264
+            } else {
265
+                return m1 > m2 ? 1 : -1;
266
+            }
267
+        }
268
+    }
269
+
270
+    public static boolean isTime(String time) {
271
+        String[] arr = time.split(":");
272
+        if (arr.length < 2) {
273
+            return false;
274
+        }
275
+        try {
276
+            int h = Integer.parseInt(arr[0]);
277
+            int m = Integer.parseInt(arr[1]);
278
+            int s = 0;
279
+            if (arr.length == 3) {
280
+                s = Integer.parseInt(arr[2]);
281
+            }
282
+            if (h < 0 || h > 23 || m < 0 || m > 59 || s < 0 || s > 59) {
283
+                return false;
284
+            }
285
+        } catch (Exception e) {
286
+            return false;
287
+        }
288
+        return true;
289
+    }
290
+
291
+    public static boolean isDate(String date) {
292
+        String[] arr = date.split("-");
293
+        if (arr.length < 3) {
294
+            return false;
295
+        }
296
+        try {
297
+            int y = Integer.parseInt(arr[0]);
298
+            int m = Integer.parseInt(arr[1]);
299
+            int d = Integer.parseInt(arr[2]);
300
+            if (y < 0 || m > 12 || m < 0 || d < 0 || d > 31) {
301
+                return false;
302
+            }
303
+        } catch (Exception e) {
304
+            return false;
305
+        }
306
+        return true;
307
+    }
308
+
309
+    public static boolean isWeekend(Date date) {
310
+        Calendar cal = Calendar.getInstance();
311
+        cal.setTime(date);
312
+        int t = cal.get(Calendar.DAY_OF_WEEK);
313
+        if (t == Calendar.SATURDAY || t == Calendar.SUNDAY) {
314
+            return true;
315
+        }
316
+        return false;
317
+    }
318
+
319
+    public static boolean isWeekend(String str) {
320
+        return isWeekend(parse(str));
321
+    }
322
+
323
+    public static Date parse(String str) {
324
+        if (StringUtils.isEmpty(str)) {
325
+            return null;
326
+        }
327
+        try {
328
+            return SDFD.parse(str);
329
+        } catch (ParseException e) {
330
+            e.printStackTrace();
331
+            return null;
332
+        }
333
+    }
334
+
335
+    public static Date parse(String str, String format) {
336
+        if (StringUtils.isEmpty(str)) {
337
+            return null;
338
+        }
339
+        try {
340
+            SimpleDateFormat t = new SimpleDateFormat(format);
341
+            return t.parse(str);
342
+        } catch (ParseException e) {
343
+            e.printStackTrace();
344
+            return null;
345
+        }
346
+    }
347
+
348
+    public static Date parseDateTime(String str) {
349
+        if (StringUtils.isEmpty(str)) {
350
+            return null;
351
+        }
352
+        if (str.length() == 10) {
353
+            return parse(str);
354
+        }
355
+        try {
356
+            return SDFDT.parse(str);
357
+        } catch (ParseException e) {
358
+            e.printStackTrace();
359
+            return null;
360
+        }
361
+    }
362
+
363
+    public static Date parseDateTime(String str, String format) {
364
+        if (StringUtils.isEmpty(str)) {
365
+            return null;
366
+        }
367
+        try {
368
+            SimpleDateFormat t = new SimpleDateFormat(format);
369
+            return t.parse(str);
370
+        } catch (ParseException e) {
371
+            e.printStackTrace();
372
+            return null;
373
+        }
374
+    }
375
+
376
+    /**
377
+     * 格式化时间,按照yyyy-MM-dd HH:mm:ss格式
378
+     * 
379
+     * @param date
380
+     *            时间
381
+     * 
382
+     * @return String
383
+     */
384
+    public static String formatDateTime(Date date) {
385
+        return SDFDT.format(date);
386
+    }
387
+
388
+    /**
389
+     * 格式化时间,按照yyyy-MM-dd格式
390
+     * 
391
+     * @param date
392
+     *            时间
393
+     * 
394
+     * @return String
395
+     */
396
+    public static String formatDate(Date date) {
397
+        return SDFD.format(date);
398
+    }
399
+
400
+    /**
401
+     * 日期date上加count分钟,count为负表示减
402
+     */
403
+    public static Date addMinute(Date date, int count) {
404
+        return new Date(date.getTime() + 60000L * count);
405
+    }
406
+
407
+    /**
408
+     * 日期date上加count妙,count为负表示减
409
+     */
410
+    public static Date addSeconds(Date date, int count) {
411
+        return new Date(date.getTime() + 1000L * count);
412
+    }
413
+
414
+    /**
415
+     * 日期date上加count小时,count为负表示减
416
+     */
417
+    public static Date addHour(Date date, int count) {
418
+        return new Date(date.getTime() + 3600000L * count);
419
+    }
420
+
421
+    /**
422
+     * 日期date上加count天,count为负表示减
423
+     */
424
+    public static Date addDay(Date date, int count) {
425
+        return new Date(date.getTime() + 86400000L * count);
426
+    }
427
+
428
+    /**
429
+     * 日期date上加count星期,count为负表示减
430
+     */
431
+    public static Date addWeek(Date date, int count) {
432
+        Calendar c = Calendar.getInstance();
433
+        c.setTime(date);
434
+        c.add(Calendar.WEEK_OF_YEAR, count);
435
+        return c.getTime();
436
+    }
437
+
438
+    /**
439
+     * 日期date上加count月,count为负表示减
440
+     */
441
+    public static Date addMonth(Date date, int count) {
442
+        /* ${_ZVING_LICENSE_CODE_} */
443
+
444
+        Calendar c = Calendar.getInstance();
445
+        c.setTime(date);
446
+        c.add(Calendar.MONTH, count);
447
+        return c.getTime();
448
+    }
449
+
450
+    /**
451
+     * 日期date上加count年,count为负表示减
452
+     */
453
+    public static Date addYear(Date date, int count) {
454
+        Calendar c = Calendar.getInstance();
455
+        c.setTime(date);
456
+        c.add(Calendar.YEAR, count);
457
+        return c.getTime();
458
+    }
459
+
460
+    /**
461
+     * 根据一个日期,返回是星期几的字符串
462
+     * 
463
+     * @param date
464
+     * @return
465
+     */
466
+    public static String getWeek(String date) {
467
+        String[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
468
+        Calendar cal = Calendar.getInstance();
469
+        cal.setTime(parse(date));
470
+        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
471
+        if (week_index < 0) {
472
+            week_index = 0;
473
+        }
474
+        return weeks[week_index];
475
+    }
476
+
477
+    /**
478
+     * 获取一周列表
479
+     * 
480
+     * @return List
481
+     * 
482
+     */
483
+    public static List<Map<String, String>> getWeekdayList() {
484
+        String[] weekday = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
485
+        List<Map<String, String>> weekdayList = new ArrayList<Map<String, String>>();
486
+        for (int i = 0; i < weekday.length; i++) {
487
+            Map<String, String> map = new HashMap<String, String>();
488
+            map.put("name", weekday[i]);
489
+            map.put("value", String.valueOf(i + 1));
490
+            map.put("checked", "");
491
+            weekdayList.add(map);
492
+        }
493
+        return weekdayList;
494
+    }
495
+
496
+    /**
497
+     * 日期返回星期几
498
+     * 
499
+     * @param date
500
+     * 
501
+     * @return int
502
+     */
503
+    public static int dayOfWeek(String date) {
504
+        try {
505
+            Calendar c = Calendar.getInstance();
506
+            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
507
+            c.setTime(dateFormat.parse(date));
508
+            int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
509
+            return dayOfWeek == 0 ? 7 : dayOfWeek;
510
+        } catch (Exception e) {
511
+            e.printStackTrace();
512
+            return 0;
513
+        }
514
+    }
515
+
516
+    /**
517
+     * 取得当前日期是多少周
518
+     * 
519
+     * @param date
520
+     * @return
521
+     */
522
+    public static int getWeekOfYear(Date date) {
523
+        Calendar c = new GregorianCalendar();
524
+        c.setFirstDayOfWeek(Calendar.MONDAY);
525
+        c.setMinimalDaysInFirstWeek(7);
526
+        c.setTime(date);
527
+
528
+        return c.get(Calendar.WEEK_OF_YEAR);
529
+    }
530
+
531
+    /**
532
+     * 得到某年某周的第一天
533
+     * 
534
+     * @param year
535
+     * @param week
536
+     * @return
537
+     */
538
+    public static String getFirstDayOfWeek(int year, int week) {
539
+        Calendar c = new GregorianCalendar();
540
+        c.set(Calendar.YEAR, year);
541
+        c.set(Calendar.MONTH, Calendar.JANUARY);
542
+        c.set(Calendar.DATE, 1);
543
+
544
+        Calendar cal = (GregorianCalendar) c.clone();
545
+        cal.add(Calendar.DATE, week * 7);
546
+
547
+        return formatDate(getFirstDayOfWeek(cal.getTime()));
548
+    }
549
+
550
+    /**
551
+     * 得到某年某周的最后一天
552
+     * 
553
+     * @param year
554
+     * @param week
555
+     * @return
556
+     */
557
+    public static String getLastDayOfWeek(int year, int week) {
558
+        Calendar c = new GregorianCalendar();
559
+        c.set(Calendar.YEAR, year);
560
+        c.set(Calendar.MONTH, Calendar.JANUARY);
561
+        c.set(Calendar.DATE, 1);
562
+
563
+        Calendar cal = (GregorianCalendar) c.clone();
564
+        cal.add(Calendar.DATE, week * 7);
565
+
566
+        return formatDate(getLastDayOfWeek(cal.getTime()));
567
+    }
568
+
569
+    /**
570
+     * 取得当前日期所在周的第一天
571
+     * 
572
+     * @param date
573
+     * @return
574
+     */
575
+    public static Date getFirstDayOfWeek(Date date) {
576
+        Calendar c = new GregorianCalendar();
577
+        c.setFirstDayOfWeek(Calendar.MONDAY);
578
+        c.setTime(date);
579
+        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
580
+        return c.getTime();
581
+    }
582
+
583
+    /**
584
+     * 取得当前日期所在周的最后一天
585
+     * 
586
+     * @param date
587
+     * @return
588
+     */
589
+    public static Date getLastDayOfWeek(Date date) {
590
+        Calendar c = new GregorianCalendar();
591
+        c.setFirstDayOfWeek(Calendar.MONDAY);
592
+        c.setTime(date);
593
+        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
594
+        return c.getTime();
595
+    }
596
+
597
+    /**
598
+     * 取得当前月份的第一天
599
+     * 
600
+     * @param date
601
+     * @return
602
+     */
603
+    public static String getFirstDayOfMonth(Date date) {
604
+        Calendar c = new GregorianCalendar();
605
+        c.setTime(date);
606
+        c.set(Calendar.DAY_OF_MONTH, 1);
607
+        return formatDate(c.getTime());
608
+    }
609
+
610
+    /**
611
+     * 获取N天前的日期
612
+     * 
613
+     * @param date
614
+     *            当前日期 num 几天前
615
+     * @return
616
+     * */
617
+    public static Date getBeginData(Date date, int num) {
618
+        Calendar c = new GregorianCalendar();
619
+        c.setTime(date);
620
+        c.add(Calendar.DATE, -num);
621
+        return c.getTime();
622
+    }
623
+
624
+    public static int getBetweenDays(Date d1, Date nextD) {
625
+        Calendar c1 = new GregorianCalendar();
626
+        c1.setTime(d1);
627
+        Calendar c2 = new GregorianCalendar();
628
+        c2.setTime(nextD);
629
+        return c1.get(Calendar.DAY_OF_YEAR) - c2.get(Calendar.DAY_OF_YEAR);
630
+    }
631
+
632
+    public static int getBetweenMinutes(Date max, Date min) {
633
+        Calendar c1 = new GregorianCalendar();
634
+        c1.setTime(max);
635
+        Calendar c2 = new GregorianCalendar();
636
+        c2.setTime(min);
637
+        return (int) ((c1.getTimeInMillis() - c2.getTimeInMillis()) / (1000 * 60));
638
+    }
639
+
640
+    /**
641
+     * 获取当前年
642
+     * 
643
+     * @return
644
+     */
645
+    public static int getCurrentYear() {
646
+        Calendar cal = Calendar.getInstance();
647
+        int year = cal.get(Calendar.YEAR);
648
+        return year;
649
+    }
650
+
651
+    /**
652
+     * 获取当前月
653
+     * 
654
+     * @return
655
+     */
656
+    public static int getCurrentMonth() {
657
+        Calendar cal = Calendar.getInstance();
658
+        int month = cal.get(Calendar.MONTH) + 1;
659
+        return month;
660
+    }
661
+    
662
+    /**
663
+     * 把年月日变数字
664
+     * */
665
+    public static int getDate(String date){
666
+    	String [] date1 = date.split("-");
667
+    	int date2 = Integer.parseInt(date1[0]+date1[1]+date1[2]);
668
+    	return date2;
669
+    }
670
+}

+ 49 - 0
src/main/java/com/dashitech/utils/DecimalUtil.java

@@ -0,0 +1,49 @@
1
+package com.dashitech.utils;
2
+
3
+import java.math.BigDecimal;
4
+
5
+
6
+
7
+/**
8
+ * 价格计算工具类
9
+ */
10
+public class DecimalUtil {
11
+	private static final int DIV_SCALE = 50;
12
+ 
13
+	/**
14
+	 * 相加
15
+	 */
16
+	public static BigDecimal sum(Object first,Object second) {
17
+		BigDecimal _first = new BigDecimal(first.toString());
18
+		BigDecimal _second = new BigDecimal(second.toString());
19
+		return _first.add(_second);
20
+	}
21
+	
22
+	/**
23
+	 * 相减
24
+	 */
25
+	public static BigDecimal sub(Object first,Object second) {
26
+		BigDecimal _first = new BigDecimal(first.toString());
27
+		BigDecimal _second = new BigDecimal(second.toString());
28
+		return _first.subtract(_second);
29
+	}
30
+	
31
+	/**
32
+	 * 相乘
33
+	 */
34
+	public static BigDecimal ride(Object first,Object second) {
35
+		BigDecimal _first = new BigDecimal(first.toString());
36
+		BigDecimal _second = new BigDecimal(second.toString());
37
+		return _first.multiply(_second);
38
+    }
39
+	
40
+	/**
41
+	 * 相除
42
+	 */
43
+	public static BigDecimal div(Object first,Object second) {
44
+		BigDecimal _first = new BigDecimal(first.toString());
45
+		BigDecimal _second = new BigDecimal(second.toString());
46
+		 return _first.divide(_second,DIV_SCALE,BigDecimal.ROUND_HALF_DOWN);
47
+	}
48
+
49
+}

+ 675 - 0
src/main/java/com/dashitech/utils/FileUtil.java

@@ -0,0 +1,675 @@
1
+package com.dashitech.utils;
2
+
3
+import org.apache.commons.logging.Log;
4
+import org.apache.commons.logging.LogFactory;
5
+
6
+import java.io.*;
7
+import java.net.URL;
8
+import java.util.ArrayList;
9
+import java.util.Collections;
10
+import java.util.Comparator;
11
+import java.util.List;
12
+import java.util.zip.ZipInputStream;
13
+
14
+public class FileUtil {
15
+	private static Log log = LogFactory.getLog(FileUtil.class);
16
+	
17
+	/**
18
+	 * 根据日期给文件排序,
19
+	 * @param list
20
+	 * @param desc true为倒序(最新日期在前面),false正序
21
+	 */
22
+	public static void sortByDate(List<File> list,final boolean desc) {
23
+		Collections.sort(list, new Comparator<File>() {
24
+			public int compare(File o1, File o2) {
25
+				Long a = o1.lastModified();
26
+				Long b = o2.lastModified();
27
+				int sort = 0;
28
+				if(desc) {
29
+					sort = b.compareTo(a);
30
+				}else {
31
+					sort = a.compareTo(b);
32
+				}
33
+				return sort;
34
+			}
35
+		});
36
+	}
37
+
38
+	/**
39
+	 * 写文件
40
+	 * 
41
+	 * @param f
42
+	 * @param content
43
+	 */
44
+	public static void writeFile(File f, String content) {
45
+		writeFile(f, content, "utf-8");
46
+	}
47
+
48
+	/**
49
+	 * 写文件
50
+	 * 
51
+	 * @param f
52
+	 * @param content
53
+	 */
54
+	public static void writeFile(File f, String content, String encode) {
55
+		try {
56
+			// 如果目录不存在,创建目录
57
+			File parent = new File(f.getParent());
58
+			parent.mkdirs();
59
+
60
+			if (!f.exists()) {
61
+				f.createNewFile();
62
+			}
63
+			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f), encode);
64
+			BufferedWriter utput = new BufferedWriter(osw);
65
+			FileOutputStream fo = null;
66
+			try {
67
+				fo = new FileOutputStream(f);
68
+				osw = new OutputStreamWriter(fo, encode);
69
+				utput = new BufferedWriter(osw);
70
+				utput.write(content);
71
+				utput.flush();
72
+			} catch (IOException ioException) {
73
+				ioException.printStackTrace();
74
+			} finally {
75
+				try {
76
+					if (fo != null) {
77
+						fo.close();
78
+					}
79
+					if (utput != null) {
80
+						utput.close();
81
+					}
82
+					if (osw != null) {
83
+						osw.close();
84
+					}
85
+				} catch (IOException e) {
86
+					log.error(e.getMessage(), e);
87
+				}
88
+			}
89
+		} catch (Exception e) {
90
+			log.error(e.getMessage(), e);
91
+		}
92
+	}
93
+
94
+	/**
95
+	 * 写出url内容为文件
96
+	 * @param file 写出的文件
97
+	 * @param url 写出的内容
98
+	 */
99
+	public static void writeFileByUrl(String file, String url) {
100
+		byte[] bytes = null;
101
+		InputStream in = null;
102
+		ByteArrayOutputStream bos = null;
103
+		
104
+		try {
105
+			URL resourceUrl = new URL(url);
106
+			in = (InputStream) resourceUrl.getContent();
107
+			
108
+			bos = new ByteArrayOutputStream();
109
+			byte[] b = new byte[1024];
110
+			int n;
111
+			while ((n = in.read(b)) != -1) {
112
+				bos.write(b, 0, n);
113
+			}
114
+			
115
+			bytes = bos.toByteArray();
116
+			
117
+			File f = new File(file);
118
+			
119
+			writeFile(f, bytes);
120
+			
121
+		} catch (IOException e) {
122
+			log.error(file+"   "+url);
123
+			log.error(e.getMessage(),e);
124
+		} finally {
125
+			try {
126
+				if (in != null) {
127
+					in.close();
128
+				}
129
+				if (bos != null) {
130
+					bos.close();
131
+				}
132
+			} catch (IOException e) {
133
+				log.error(e.getMessage(), e);
134
+			}
135
+		}
136
+	}
137
+
138
+	/**
139
+	 * 写文件
140
+	 * 
141
+	 * @param f
142
+	 * @param bytes
143
+	 */
144
+	public static void writeFile(File f, byte[] bytes) {
145
+		try {
146
+			// 如果目录不存在,创建目录
147
+			File parent = new File(f.getParent());
148
+			parent.mkdirs();
149
+
150
+			if (!f.exists()) {
151
+				f.createNewFile();
152
+			}
153
+
154
+			BufferedOutputStream bos = null;
155
+			FileOutputStream fo = null;
156
+			try {
157
+				fo = new FileOutputStream(f);
158
+				bos = new BufferedOutputStream(fo);
159
+				bos.write(bytes);
160
+				bos.flush();
161
+			} catch (IOException ioException) {
162
+				ioException.printStackTrace();
163
+			} finally {
164
+				try {
165
+					if (fo != null) {
166
+						fo.close();
167
+					}
168
+					if (bos != null) {
169
+						bos.close();
170
+					}
171
+				} catch (IOException e) {
172
+					log.error(e.getMessage(), e);
173
+				}
174
+			}
175
+		} catch (Exception e) {
176
+			log.error(e.getMessage(), e);
177
+		}
178
+	}
179
+
180
+	/**
181
+	 * 写文件
182
+	 * 
183
+	 * @param path
184
+	 * @param content
185
+	 */
186
+	public static void writeFile(String path, String content, String encode) {
187
+		File f = new File(path);
188
+		writeFile(f, content, encode);
189
+	}
190
+
191
+	/**
192
+	 * 写文件
193
+	 * 
194
+	 * @param path
195
+	 * @param content
196
+	 */
197
+	public static void writeFile(String path, String content) {
198
+		File f = new File(path);
199
+		writeFile(f, content, "utf-8");
200
+	}
201
+
202
+	/**
203
+	 * 读取文件
204
+	 * 
205
+	 * @param file
206
+	 * @return
207
+	 */
208
+	public static String readFile(File file) {
209
+		return readFile(file, "UTF-8");
210
+	}
211
+
212
+	/**
213
+	 * 读取文件
214
+	 * 
215
+	 * @param file
216
+	 * @return
217
+	 */
218
+	public static String readFile(File file, String encode) {
219
+		String output = "";
220
+		InputStreamReader isr = null;
221
+		BufferedReader input = null;
222
+
223
+		if (file.exists()) {
224
+			if (file.isFile()) {
225
+				try {
226
+					isr = new InputStreamReader(new FileInputStream(file), encode);
227
+					input = new BufferedReader(isr);
228
+					StringBuffer buffer = new StringBuffer();
229
+					String text;
230
+					while ((text = input.readLine()) != null)
231
+						buffer.append(text + "\n");
232
+					output = buffer.toString();
233
+
234
+				} catch (IOException ioException) {
235
+					ioException.printStackTrace();
236
+				} finally {
237
+					try {
238
+						if (input != null) {
239
+							input.close();
240
+						}
241
+						if (isr != null) {
242
+							isr.close();
243
+						}
244
+					} catch (IOException e) {
245
+						log.error(e.getMessage(), e);
246
+					}
247
+				}
248
+			} else if (file.isDirectory()) {
249
+				throw new RuntimeException(file.getPath() + " isDirectory!");
250
+			}
251
+
252
+		} else {
253
+			throw new RuntimeException(file.getPath() + " Does not exist!");
254
+		}
255
+
256
+		return output;
257
+	}
258
+
259
+	public static byte[] readFileBytes(File file) {
260
+		byte[] bytes = null;
261
+		FileInputStream fis = null;
262
+		ByteArrayOutputStream bos = null;
263
+		if (file.exists()) {
264
+			if (file.isFile()) {
265
+				try {
266
+					fis = new FileInputStream(file);
267
+					bos = new ByteArrayOutputStream();
268
+					byte[] b = new byte[1024];
269
+					int n;
270
+					while ((n = fis.read(b)) != -1) {
271
+						bos.write(b, 0, n);
272
+					}
273
+					fis.close();
274
+					bos.close();
275
+					bytes = bos.toByteArray();
276
+				} catch (IOException ioException) {
277
+					ioException.printStackTrace();
278
+				} finally {
279
+					try {
280
+						if (fis != null) {
281
+							fis.close();
282
+						}
283
+						if (bos != null) {
284
+							bos.close();
285
+						}
286
+					} catch (IOException e) {
287
+						log.error(e.getMessage(), e);
288
+					}
289
+				}
290
+			} else if (file.isDirectory()) {
291
+				throw new RuntimeException(file.getPath() + " isDirectory!");
292
+			}
293
+
294
+		} else {
295
+			throw new RuntimeException(file.getPath() + " Does not exist!");
296
+		}
297
+
298
+		return bytes;
299
+	}
300
+
301
+	/**
302
+	 * 读取文件
303
+	 * 
304
+	 * @param fileName
305
+	 * @return
306
+	 */
307
+	public static String readFile(String fileName, String encode) {
308
+		File file = new File(fileName);
309
+		return readFile(file, encode);
310
+	}
311
+
312
+	/**
313
+	 * 读取文件
314
+	 * 
315
+	 * @param fileName
316
+	 * @return
317
+	 */
318
+	public static String readFile(String fileName) {
319
+		return readFile(fileName, "utf-8");
320
+	}
321
+
322
+	/**
323
+	 * 获取目录下所有文件,一级
324
+	 * 
325
+	 * @param folder
326
+	 * @return
327
+	 */
328
+	public static List<File> getFiles(String folder) {
329
+		return getFiles(folder, null);
330
+	}
331
+
332
+	/**
333
+	 * 获取目录下所有文件,一级,后缀区分
334
+	 * 
335
+	 * @param folder
336
+	 * @return
337
+	 */
338
+	public static List<File> getFiles(String folder, String suffix) {
339
+		File file = new File(folder);
340
+		List<File> list = new ArrayList<File>();
341
+		if (file.exists() && file.isDirectory()) {
342
+			File[] files = file.listFiles();
343
+			for (File f : files) {
344
+				String fileName = f.getName();
345
+				if (suffix == null) {
346
+					list.add(f);
347
+				} else if (fileName.endsWith(suffix)) {
348
+					list.add(f);
349
+				}
350
+			}
351
+		}
352
+		return list;
353
+	}
354
+
355
+	/**
356
+	 * 遍历所有文件夹,取出文件
357
+	 */
358
+	public static List<File> getFileDeeps(String folder, String suffix) {
359
+		File file = new File(folder);
360
+		List<File> list = new ArrayList<File>();
361
+		if (file.exists() && file.isDirectory()) {
362
+			File[] files = file.listFiles();
363
+
364
+			for (File f : files) {
365
+				if (f.isFile()) {
366
+					String fileName = f.getName();
367
+					if (suffix == null) {
368
+						list.add(f);
369
+					} else if (fileName.endsWith(suffix)) {
370
+						list.add(f);
371
+					}
372
+				} else if (f.isDirectory()) {
373
+					list.addAll(getFileDeeps(f.getAbsolutePath(), suffix));
374
+				}
375
+			}
376
+		}
377
+		return list;
378
+	}
379
+
380
+	/**
381
+	 * 遍历所有文件夹,取出文件
382
+	 */
383
+	public static List<File> getFileDeeps(String folder, List<String> suffixs) {
384
+		File file = new File(folder);
385
+		List<File> list = new ArrayList<File>();
386
+		if (file.exists() && file.isDirectory()) {
387
+			File[] files = file.listFiles();
388
+
389
+			for (File f : files) {
390
+				if (f.isFile()) {
391
+					String fileName = f.getName();
392
+					for (String suffix : suffixs) {
393
+						if (suffix == null) {
394
+							list.add(f);
395
+						} else if (fileName.toLowerCase().endsWith(suffix)) {
396
+							list.add(f);
397
+						}
398
+					}
399
+				} else if (f.isDirectory()) {
400
+					list.addAll(getFileDeeps(f.getAbsolutePath(), suffixs));
401
+				}
402
+			}
403
+		}
404
+		return list;
405
+	}
406
+
407
+	/**
408
+	 * 获取目录下所有文件夹,一级
409
+	 * 
410
+	 * @param folder
411
+	 * @return
412
+	 */
413
+	public static List<File> getFolders(String folder) {
414
+		File file = new File(folder);
415
+		List<File> files = new ArrayList<File>();
416
+		if (file.exists()) {
417
+			File[] sonFiles = file.listFiles();
418
+			if (sonFiles != null && sonFiles.length > 0) {
419
+				for (int i = 0; i < sonFiles.length; i++) {
420
+					if (sonFiles[i].isDirectory()) {
421
+						files.add(sonFiles[i]);
422
+					}
423
+				}
424
+			}
425
+		}
426
+		return files;
427
+	}
428
+
429
+	/**
430
+	 * 判断是否有子目录
431
+	 * 
432
+	 * @param folder
433
+	 * @return
434
+	 */
435
+	public static boolean hasSonFolder(String folder) {
436
+		File file = new File(folder);
437
+		return hasSonFolder(file);
438
+	}
439
+
440
+	/**
441
+	 * 判断是否有子目录
442
+	 * 
443
+	 * @param file
444
+	 * @return
445
+	 */
446
+	public static boolean hasSonFolder(File file) {
447
+		if (file.exists()) {
448
+			File[] sonFiles = file.listFiles();
449
+			if (sonFiles != null && sonFiles.length > 0) {
450
+				for (int i = 0; i < sonFiles.length; i++) {
451
+					if (sonFiles[i].isDirectory()) {
452
+						return true;
453
+					}
454
+				}
455
+			}
456
+		}
457
+		return false;
458
+	}
459
+
460
+	/**
461
+	 * 创建目录
462
+	 * 
463
+	 * @param folder
464
+	 */
465
+	public static void mkdirs(String folder) {
466
+		File file = new File(folder);
467
+		if (!file.exists()) {
468
+			file.mkdirs();
469
+		}
470
+	}
471
+
472
+	/**
473
+	 * 复制文件
474
+	 * 
475
+	 * @param src
476
+	 * @param dst
477
+	 */
478
+	public static void copy(File src, File dst) {
479
+		try {
480
+			// 如果是文件夹,并且已存在则什么都不做
481
+			if (dst.isDirectory() && dst.exists()) {
482
+				return;
483
+			}
484
+			if (!dst.getParentFile().exists()) {
485
+				dst.getParentFile().mkdirs();
486
+			}
487
+
488
+			int BUFFER_SIZE = 32 * 1024;
489
+			InputStream in = null;
490
+			OutputStream out = null;
491
+			try {
492
+				in = new FileInputStream(src);
493
+				out = new FileOutputStream(dst);
494
+				byte[] buffer = new byte[BUFFER_SIZE];
495
+				int count;
496
+				while ((count = in.read(buffer)) != -1) {
497
+					out.write(buffer, 0, count);
498
+				}
499
+				out.flush();
500
+			} catch (Exception e) {
501
+				log.error(src.getAbsolutePath() + "," + dst.getAbsolutePath() + ";" + e.getMessage(), e);
502
+			} finally {
503
+				if (null != in) {
504
+					in.close();
505
+				}
506
+				if (null != out) {
507
+					out.close();
508
+				}
509
+			}
510
+		} catch (Exception e2) {
511
+			log.error(e2.getMessage(), e2);
512
+		}
513
+	}
514
+
515
+	/**
516
+	 * 复制文件夹,包含内容,如果已有覆盖已有文件
517
+	 * 
518
+	 * @param overwrite
519
+	 *            是否覆盖文件
520
+	 */
521
+	public static void copyDirectiory(String sourceDir, String targetDir, boolean overwrite) throws IOException {
522
+		if (new File(sourceDir).exists()) {
523
+			// 新建目标目录
524
+			File targetFolder = new File(targetDir);
525
+			if (!targetFolder.exists()) {
526
+				targetFolder.mkdirs();
527
+			}
528
+			// 获取源文件夹当前下的文件或目录
529
+			File[] file = (new File(sourceDir)).listFiles();
530
+			for (int i = 0; i < file.length; i++) {
531
+
532
+				try {
533
+					if (file[i].isFile()) {
534
+						// 源文件
535
+						File sourceFile = file[i];
536
+						// 目标文件
537
+						File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
538
+
539
+						// 如果重写为true,直接覆盖现有文件
540
+						if (overwrite) {
541
+							copy(sourceFile, targetFile);
542
+						} else if (!targetFile.exists()) {
543
+							// 如果文件不存在才写文件
544
+							copy(sourceFile, targetFile);
545
+						}
546
+
547
+					}
548
+					if (file[i].isDirectory()) {
549
+						// 准备复制的源文件夹
550
+						String dir1 = sourceDir + "/" + file[i].getName();
551
+						// 准备复制的目标文件夹
552
+						String dir2 = targetDir + "/" + file[i].getName();
553
+						File fileDir2 = new File(targetDir);
554
+						if (!fileDir2.exists()) {
555
+							fileDir2.mkdirs();
556
+						}
557
+						copyDirectiory(dir1, dir2, overwrite);
558
+					}
559
+				} catch (Exception e) {
560
+					log.error(e.getMessage(), e);
561
+				}
562
+
563
+			}
564
+		}
565
+	}
566
+
567
+	/**
568
+	 * 获取扩展名 .jpg
569
+	 */
570
+	public static String getExt(File src) {
571
+		if (src != null) {
572
+			String name = src.getName();
573
+			return name.substring(name.lastIndexOf("."), name.length());
574
+		}
575
+		return "";
576
+	}
577
+
578
+	/**
579
+	 * 获取扩展名 .jpg
580
+	 */
581
+	public static String getExt(String src) {
582
+		if (src != null) {
583
+			return src.substring(src.lastIndexOf("."), src.length());
584
+		}
585
+		return "";
586
+	}
587
+
588
+	/**
589
+	 * 删除指定文件
590
+	 * 
591
+	 * @param path
592
+	 */
593
+	public static void del(String path) {
594
+		File file = new File(path);
595
+		deleteFile(file);
596
+	}
597
+
598
+	/**
599
+	 * 递归删除文件夹下所有文件
600
+	 * 
601
+	 * @param file
602
+	 */
603
+	public static void deleteFile(File file) {
604
+		if (file.exists() && file.canRead()) { // 判断文件是否存在
605
+			try {
606
+				if (file.isFile()) { // 判断是否是文件
607
+					file.delete(); // delete()方法 你应该知道 是删除的意思;
608
+				} else if (file.isDirectory()) { // 否则如果它是一个目录
609
+					File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
610
+					for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
611
+						deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
612
+					}
613
+				}
614
+				file.delete();
615
+			} catch (Exception e) {
616
+				log.error(e.getMessage(), e);
617
+			}
618
+		}
619
+	}
620
+
621
+	public static void deleteFile(List<File> files) {
622
+		for (File f : files) {
623
+			deleteFile(f);
624
+		}
625
+	}
626
+
627
+
628
+
629
+	/**
630
+	 * 解压缩
631
+	 * 
632
+	 * @param sZipPathFile
633
+	 *            要解压的文件
634
+	 * @param sDestPath
635
+	 *            解压到某文件夹
636
+	 * @return
637
+	 */
638
+	public static List<String> unzip(String sZipPathFile, String sDestPath) {
639
+		List<String> allFileName = new ArrayList<String>();
640
+		try {
641
+			// 先指定压缩档的位置和档名,建立FileInputStream对象
642
+			FileInputStream fins = new FileInputStream(sZipPathFile);
643
+			// 将fins传入ZipInputStream中
644
+			ZipInputStream zins = new ZipInputStream(fins);
645
+			java.util.zip.ZipEntry ze = null;
646
+			byte[] ch = new byte[256];
647
+			while ((ze = zins.getNextEntry()) != null) {
648
+				File zfile = new File(sDestPath + ze.getName());
649
+				File fpath = new File(zfile.getParentFile().getPath());
650
+				if (ze.isDirectory()) {
651
+					if (!zfile.exists())
652
+						zfile.mkdirs();
653
+					zins.closeEntry();
654
+				} else {
655
+					if (!fpath.exists())
656
+						fpath.mkdirs();
657
+					FileOutputStream fouts = new FileOutputStream(zfile);
658
+					int i;
659
+					allFileName.add(zfile.getAbsolutePath());
660
+					while ((i = zins.read(ch)) != -1)
661
+						fouts.write(ch, 0, i);
662
+					zins.closeEntry();
663
+					fouts.close();
664
+				}
665
+			}
666
+			fins.close();
667
+			zins.close();
668
+		} catch (Exception e) {
669
+			log.error(e.getMessage(), e);
670
+		}
671
+		return allFileName;
672
+	}
673
+
674
+
675
+}

+ 372 - 0
src/main/java/com/dashitech/utils/HttpUtil.java

@@ -0,0 +1,372 @@
1
+package com.dashitech.utils;
2
+
3
+import com.alibaba.fastjson.JSONObject;
4
+import org.apache.commons.lang.StringUtils;
5
+import org.apache.http.HttpEntity;
6
+import org.apache.http.NameValuePair;
7
+import org.apache.http.client.config.RequestConfig;
8
+import org.apache.http.client.entity.UrlEncodedFormEntity;
9
+import org.apache.http.client.methods.CloseableHttpResponse;
10
+import org.apache.http.client.methods.HttpGet;
11
+import org.apache.http.client.methods.HttpPost;
12
+import org.apache.http.impl.client.CloseableHttpClient;
13
+import org.apache.http.impl.client.HttpClientBuilder;
14
+import org.apache.http.message.BasicNameValuePair;
15
+import org.apache.http.util.EntityUtils;
16
+
17
+import javax.servlet.http.HttpServletResponse;
18
+import java.io.*;
19
+import java.net.HttpURLConnection;
20
+import java.net.MalformedURLException;
21
+import java.net.SocketException;
22
+import java.net.URL;
23
+import java.util.ArrayList;
24
+import java.util.List;
25
+import java.util.Map;
26
+
27
+public class HttpUtil {
28
+
29
+    public static CloseableHttpClient getHttpClient() {
30
+    	 RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
31
+    	 CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
32
+         return httpClient;
33
+    }
34
+
35
+    /**
36
+     * HTTP Get 获取内容
37
+     * @param url  请求的url地址 ?之前的地址
38
+     * @param params	请求的参数
39
+     * @param charset	编码格式
40
+     * @return	页面内容
41
+     */
42
+    public static String doGet(String url,Map<String,String> params,String charset){
43
+    	if(StringUtils.isBlank(url)){
44
+    		return null;
45
+    	}
46
+    	try {
47
+    		if(params != null && !params.isEmpty()){
48
+    			List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
49
+    			for(Map.Entry<String,String> entry : params.entrySet()){
50
+    				String value = entry.getValue();
51
+    				if(value != null){
52
+    					pairs.add(new BasicNameValuePair(entry.getKey(),value));
53
+    				}
54
+    			}
55
+    			url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
56
+    		}
57
+    		HttpGet httpGet = new HttpGet(url);
58
+    		CloseableHttpResponse response = getHttpClient().execute(httpGet);
59
+    		int statusCode = response.getStatusLine().getStatusCode();
60
+    		if (statusCode != 200) {
61
+    			httpGet.abort();
62
+    			throw new RuntimeException("HttpClient,error status code :" + statusCode);
63
+    		}
64
+    		HttpEntity entity = response.getEntity();
65
+    		String result = null;
66
+    		if (entity != null){
67
+    			result = EntityUtils.toString(entity, charset);
68
+    		}
69
+    		EntityUtils.consume(entity);
70
+    		response.close();
71
+    		return result;
72
+    	} catch (Exception e) {
73
+    		e.printStackTrace();
74
+    	}
75
+    	return null;
76
+    }
77
+    
78
+    /**
79
+     * HTTP Post 获取内容
80
+     * @param url  请求的url地址 ?之前的地址
81
+     * @param params	请求的参数
82
+     * @param charset	编码格式
83
+     * @return	页面内容
84
+     */
85
+    public static String doPost(String url,Map<String,String> params,String charset){
86
+    	if(StringUtils.isBlank(url)){
87
+    		return null;
88
+    	}
89
+    	try {
90
+    		List<NameValuePair> pairs = null;
91
+    		if(params != null && !params.isEmpty()){
92
+    			pairs = new ArrayList<NameValuePair>(params.size());
93
+    			for(Map.Entry<String,String> entry : params.entrySet()){
94
+    				String value = entry.getValue();
95
+    				if(value != null){
96
+    					pairs.add(new BasicNameValuePair(entry.getKey(),value));
97
+    				}
98
+    			}
99
+    		}
100
+    		HttpPost httpPost = new HttpPost(url);
101
+    		if(pairs != null && pairs.size() > 0){
102
+    			httpPost.setEntity(new UrlEncodedFormEntity(pairs,charset));
103
+    		}
104
+    		CloseableHttpResponse response = getHttpClient().execute(httpPost);
105
+    		int statusCode = response.getStatusLine().getStatusCode();
106
+    		if (statusCode != 200) {
107
+    			httpPost.abort();
108
+    			throw new RuntimeException("HttpClient,error status code :" + statusCode);
109
+    		}
110
+    		HttpEntity entity = response.getEntity();
111
+    		String result = null;
112
+    		if (entity != null){
113
+    			result = EntityUtils.toString(entity, charset);
114
+    		}
115
+    		EntityUtils.consume(entity);
116
+    		response.close();
117
+    		return result;
118
+    	} catch (Exception e) {
119
+    		e.printStackTrace();
120
+    	}
121
+    	return null;
122
+    }
123
+
124
+	public static void outPrint(HttpServletResponse response, String content, String charset) {
125
+		response.setCharacterEncoding(charset);
126
+		response.setContentType(new StringBuilder().append("text/html;charset=").append(charset).toString());
127
+		PrintWriter out = null;
128
+		try {
129
+			out = response.getWriter();
130
+			out.println(content);
131
+			out.flush();
132
+		} catch (Exception e) {
133
+			e.printStackTrace();
134
+		} finally {
135
+			out.close();
136
+		}
137
+	}
138
+	
139
+	public static String readResponse(String requestUrl, Map<String, String> params, String method, String charset) {
140
+		StringBuffer sb = new StringBuffer();
141
+		String paramsStr = "";
142
+		if ((params != null) && (params.size() > 0)) {
143
+			for (Map.Entry e : params.entrySet()) {
144
+				sb.append((String) e.getKey());
145
+				sb.append("=");
146
+				sb.append((String) e.getValue());
147
+				sb.append("&");
148
+			}
149
+			paramsStr = sb.substring(0, sb.length() - 1);
150
+		}
151
+		return readResponse(requestUrl, paramsStr, method, charset);
152
+	}
153
+	
154
+	public static String readPostResponse(String requestUrl, String json, String contentType) {
155
+		HttpURLConnection conn = null;
156
+		OutputStreamWriter out = null;
157
+		BufferedReader in = null;
158
+		String line = null;
159
+		try {
160
+			URL url = new URL(requestUrl);
161
+			conn = (HttpURLConnection) url.openConnection();
162
+			conn.setRequestMethod("POST");
163
+			conn.setRequestProperty("Content-Type", contentType);
164
+			conn.setRequestProperty("Accept-Charset", "UTF-8");
165
+			conn.setRequestProperty("Content-Length", new StringBuilder().append("").append(json.length()).toString());
166
+			conn.setUseCaches(false);
167
+			conn.setDoOutput(true);
168
+			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
169
+			out.write(json);
170
+			out.flush();
171
+			out.close();
172
+
173
+			if (conn.getResponseCode() != 200) {
174
+				System.err.println("connect failed!" + conn.getResponseCode());
175
+				String str1 = "";
176
+				return str1;
177
+			}
178
+			String result = "";
179
+			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
180
+			while ((line = in.readLine()) != null) {
181
+				result = new StringBuilder().append(result).append(line).append("\n").toString();
182
+			}
183
+			String str2 = result;
184
+			return str2;
185
+		} catch (SocketException se) {
186
+			se.printStackTrace();
187
+			line = null;
188
+			return line;
189
+		} catch (Exception e) {
190
+			e.printStackTrace();
191
+			line = null;
192
+			return line;
193
+		} finally {
194
+			if (out != null) {
195
+				try {
196
+					out.close();
197
+				} catch (IOException e) {
198
+					e.printStackTrace();
199
+				}
200
+			}
201
+			if (in != null) {
202
+				try {
203
+					in.close();
204
+				} catch (IOException e) {
205
+					e.printStackTrace();
206
+				}
207
+			}
208
+			if (conn != null)
209
+				conn.disconnect();
210
+		}
211
+	}
212
+	
213
+	public static String readResponse(String requestUrl, String requestData, String method, String charset) {
214
+		HttpURLConnection conn = null;
215
+		OutputStreamWriter out = null;
216
+		BufferedReader in = null;
217
+		String line = null;
218
+		try {
219
+			URL url = new URL(requestUrl);
220
+			conn = (HttpURLConnection) url.openConnection();
221
+			conn.setRequestMethod(method);
222
+			conn.setRequestProperty("Content-Type", "text/html");
223
+			conn.setRequestProperty("Accept-Charset", charset);
224
+			conn.setUseCaches(false);
225
+			conn.setDoOutput(true);
226
+			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
227
+			conn.setRequestProperty("Content-Length", new StringBuilder().append("").append(requestData.length()).toString());
228
+			out = new OutputStreamWriter(conn.getOutputStream(), charset);
229
+			out.write(requestData);
230
+			out.flush();
231
+			out.close();
232
+
233
+			if (conn.getResponseCode() != 200) {
234
+				System.err.println("connect failed!" + conn.getResponseCode());
235
+				String str1 = "";
236
+				return str1;
237
+			}
238
+			String result = "";
239
+			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
240
+			while ((line = in.readLine()) != null) {
241
+				result = new StringBuilder().append(result).append(line).append("\n").toString();
242
+			}
243
+			String str2 = result;
244
+			return str2;
245
+		} catch (SocketException se) {
246
+			se.printStackTrace();
247
+			line = null;
248
+			return line;
249
+		} catch (Exception e) {
250
+			e.printStackTrace();
251
+			line = null;
252
+			return line;
253
+		} finally {
254
+			if (out != null) {
255
+				try {
256
+					out.close();
257
+				} catch (IOException e) {
258
+					e.printStackTrace();
259
+				}
260
+			}
261
+			if (in != null) {
262
+				try {
263
+					in.close();
264
+				} catch (IOException e) {
265
+					e.printStackTrace();
266
+				}
267
+			}
268
+			if (conn != null)
269
+				conn.disconnect();
270
+		}
271
+	}
272
+
273
+	public static String getString(byte[] b, int offset, int len, String encoding) {
274
+		try {
275
+			return new String(b, offset, len, encoding);
276
+		} catch (UnsupportedEncodingException e) {
277
+		}
278
+		return new String(b, offset, len);
279
+	}
280
+
281
+
282
+	public static String doPost(String httpUrl,Object param) {
283
+
284
+		HttpURLConnection connection = null;
285
+		InputStream is = null;
286
+		OutputStream out = null;
287
+		BufferedReader br = null;
288
+		String result = null;
289
+		try {
290
+			URL url = new URL(httpUrl);
291
+			// 通过远程url连接对象打开连接
292
+			connection = (HttpURLConnection) url.openConnection();
293
+			// 设置连接请求方式
294
+			connection.setRequestMethod("POST");
295
+			// 设置连接主机服务器超时时间:15000毫秒
296
+			connection.setConnectTimeout(15000);
297
+			// 设置读取主机服务器返回数据超时时间:60000毫秒
298
+			connection.setReadTimeout(60000);
299
+
300
+			// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
301
+			connection.setDoOutput(true);
302
+			// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
303
+			connection.setDoInput(true);
304
+			// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
305
+			connection.setRequestProperty("Content-Type", "application/json");
306
+			// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
307
+			//connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
308
+			// 通过连接对象获取一个输出流
309
+			out = connection.getOutputStream();
310
+			// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
311
+			//os.write(param.getBytes());
312
+			//JSONObject obj = new JSONObject();
313
+			// java.net.URLEncoder.encode 编码之后会有%多余%的问题,在传输的过程中无法被解析
314
+			// String json = java.net.URLEncoder.encode(obj.toString(), "utf-8");
315
+			Object o = JSONObject.toJSON(param);
316
+			Object jsonObject = JSONObject.parse(o.toString());
317
+			out.write(jsonObject.toString().getBytes());
318
+
319
+
320
+			// 通过连接对象获取一个输入流,向远程读取
321
+			if (connection.getResponseCode() == 200) {
322
+
323
+				is = connection.getInputStream();
324
+				// 对输入流对象进行包装:charset根据工作项目组的要求来设置
325
+				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
326
+
327
+				StringBuffer sbf = new StringBuffer();
328
+				String temp = null;
329
+				// 循环遍历一行一行读取数据
330
+				while ((temp = br.readLine()) != null) {
331
+					sbf.append(temp);
332
+					sbf.append("\r\n");
333
+				}
334
+				result = sbf.toString();
335
+			}
336
+		} catch (MalformedURLException e) {
337
+			e.printStackTrace();
338
+		} catch (IOException e) {
339
+			e.printStackTrace();
340
+		} finally {
341
+			// 关闭资源
342
+			if (null != br) {
343
+				try {
344
+					br.close();
345
+				} catch (IOException e) {
346
+					e.printStackTrace();
347
+				}
348
+			}
349
+			if (null != out) {
350
+				try {
351
+					out.close();
352
+				} catch (IOException e) {
353
+					e.printStackTrace();
354
+				}
355
+			}
356
+			if (null != is) {
357
+				try {
358
+					is.close();
359
+				} catch (IOException e) {
360
+					e.printStackTrace();
361
+				}
362
+			}
363
+			// 断开与远程地址url的连接
364
+			connection.disconnect();
365
+		}
366
+		return result;
367
+	}
368
+	public static void main(String[] args) {
369
+		String re=readResponse("www.baidu.com","","get","UTF-8");
370
+		System.out.println(re);
371
+	}
372
+}

+ 20 - 0
src/main/java/com/dashitech/utils/I18n.java

@@ -0,0 +1,20 @@
1
+package com.dashitech.utils;
2
+
3
+import java.lang.annotation.Documented;
4
+import java.lang.annotation.Retention;
5
+import java.lang.annotation.Target;
6
+
7
+import static java.lang.annotation.ElementType.FIELD;
8
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
9
+/**
10
+ * Created by chi on 2019/9/10.
11
+ * 实体说明注解
12
+ */
13
+
14
+
15
+@Target(FIELD)
16
+@Retention(RUNTIME)
17
+@Documented
18
+public @interface I18n {
19
+    String value();
20
+}

+ 81 - 0
src/main/java/com/dashitech/utils/JDBCLearn.java

@@ -0,0 +1,81 @@
1
+package com.dashitech.utils;
2
+
3
+import java.sql.*;
4
+import java.util.ArrayList;
5
+import java.util.HashMap;
6
+import java.util.List;
7
+import java.util.Map;
8
+
9
+/**
10
+ * Created by xuweihua on 2021/6/9.
11
+ */
12
+public class JDBCLearn {
13
+    private static String jdbc = PropertiesUtil.getProperty("sqlserver.conn.jdbc");
14
+    private static String user = PropertiesUtil.getProperty("sqlserver.user");
15
+    private static String pwd = PropertiesUtil.getProperty("sqlserver.password");
16
+
17
+    private static String jdbc1 = PropertiesUtil.getProperty("sqlserver.conn.jdbc1");
18
+    private static String user1 = PropertiesUtil.getProperty("sqlserver.user1");
19
+    private static String pwd1 = PropertiesUtil.getProperty("sqlserver.password1");
20
+
21
+    /**
22
+    public static void main(String[] args) throws ClassNotFoundException, SQLException { //加载驱动
23
+        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
24
+        String url = "jdbc:sqlserver://172.18.100.200:1433;DataBaseName=CR_JMPZZX_V4";
25
+        String username = "dszzzxroot";
26
+        String passWord = "IuMrNP01Gk7NFeFz";
27
+        //建立连接
28
+        Connection comm = DriverManager.getConnection(url,username,passWord);
29
+        String SQL = "SELECT * FROM dbo.JMPZ_ZZFW_JJD_V ";//注意:表名一定要带[]
30
+        Statement stmt = comm.createStatement();
31
+        //结果集
32
+        ResultSet rs = stmt.executeQuery(SQL);
33
+        List list = new ArrayList();
34
+        ResultSetMetaData rsmd = rs.getMetaData();
35
+        //每循环一次遍历出来1条记录,记录对应的所有列值存放在map中(columnName:columnValue)
36
+        while(rs.next()){
37
+            Map map = new HashMap();
38
+            int columnCount = rsmd.getColumnCount();
39
+            for(int i=0;i<columnCount;i++){
40
+                String columnName = rsmd.getColumnName(i+1);
41
+                map.put(columnName, rs.getObject(i+1));
42
+            }
43
+            list.add(map);
44
+        }
45
+        rs.close();
46
+        comm.close();
47
+    }
48
+    */
49
+    public List getDataList(String sql,Integer type){
50
+        try{
51
+            //建立连接
52
+            Connection comm = null;
53
+            if (type == null) {
54
+                comm = DriverManager.getConnection(jdbc, user, pwd);
55
+            } else if (type != null && type == 1) {
56
+                comm = DriverManager.getConnection(jdbc1, user1, pwd1);
57
+            }
58
+            Statement stmt = comm.createStatement();
59
+            //结果集
60
+            ResultSet rs = stmt.executeQuery(sql);
61
+            List list = new ArrayList();
62
+            ResultSetMetaData rsmd = rs.getMetaData();
63
+            //每循环一次遍历出来1条记录,记录对应的所有列值存放在map中(columnName:columnValue)
64
+            while(rs.next()){
65
+                Map map = new HashMap();
66
+                int columnCount = rsmd.getColumnCount();
67
+                for(int i=0;i<columnCount;i++){
68
+                    String columnName = rsmd.getColumnName(i+1);
69
+                    map.put(columnName, rs.getObject(i+1));
70
+                }
71
+                list.add(map);
72
+            }
73
+            rs.close();
74
+            comm.close();
75
+            return list;
76
+        }catch (Exception e){
77
+            e.printStackTrace();
78
+        }
79
+        return  null;
80
+    }
81
+}

+ 120 - 0
src/main/java/com/dashitech/utils/JsonParam.java

@@ -0,0 +1,120 @@
1
+package com.dashitech.utils;
2
+
3
+import net.sf.json.JSONArray;
4
+import net.sf.json.JSONObject;
5
+
6
+import java.io.Serializable;
7
+import java.util.ArrayList;
8
+import java.util.List;
9
+import java.util.Map;
10
+
11
+
12
+public class JsonParam implements Serializable {
13
+
14
+	private static final long serialVersionUID = -4882852696761401880L;
15
+
16
+	private Integer total;
17
+
18
+	private Integer pageIndex = 1;
19
+
20
+	private Integer pageSize = 20;
21
+
22
+	private Integer totalPage = 0;
23
+
24
+	/**
25
+	 * 实体bean
26
+	 */
27
+	private Map<String, Object> model;
28
+	/**
29
+	 * 实体bean列表
30
+	 */
31
+	private List<Map<String,Object>> list;
32
+	/**
33
+	 * 其他参数
34
+	 */
35
+	private Map<String, Object> param;
36
+	
37
+	
38
+	
39
+	public Integer getTotal() {
40
+		return total;
41
+	}
42
+
43
+	public void setTotal(Integer total) {
44
+		this.total = total;
45
+	}
46
+
47
+	public Integer getPageIndex() {
48
+		return pageIndex;
49
+	}
50
+
51
+	public void setPageIndex(Integer pageIndex) {
52
+		this.pageIndex = pageIndex;
53
+	}
54
+
55
+	public Integer getPageSize() {
56
+		return pageSize;
57
+	}
58
+
59
+	public void setPageSize(Integer pageSize) {
60
+		this.pageSize = pageSize;
61
+	}
62
+
63
+	public Integer getTotalPage() {
64
+		return totalPage;
65
+	}
66
+
67
+	public void setTotalPage(Integer totalPage) {
68
+		this.totalPage = totalPage;
69
+	}
70
+
71
+	public Map<String, Object> getModel() {
72
+		return model;
73
+	}
74
+
75
+	public void setModel(Map<String, Object> model) {
76
+		this.model = model;
77
+	}
78
+
79
+	public Map<String, Object> getParam() {
80
+		return param;
81
+	}
82
+
83
+	public void setParam(Map<String, Object> param) {
84
+		this.param = param;
85
+	}
86
+	
87
+	public List<Map<String, Object>> getList() {
88
+		return list;
89
+	}
90
+
91
+	public void setList(List<Map<String, Object>> list) {
92
+		this.list = list;
93
+	}
94
+
95
+	@SuppressWarnings({ "rawtypes", "unchecked" })
96
+	public <T> T getModelBean(Class clazz) {
97
+		JSONObject jsonObj = JsonUtil.toJSONObject(getModel());
98
+		Object temp = JsonUtil.toObject(jsonObj.toString(), clazz);
99
+		if(temp != null) {
100
+			return (T)temp;
101
+		}
102
+		return null;
103
+	}
104
+	
105
+	@SuppressWarnings({ "rawtypes", "unchecked" })
106
+	public <T> List<T> getModelListBean(Class clazz) {
107
+		JSONArray jsonArr = JsonUtil.toJSONArray(getList());
108
+		List<T> temp = JsonUtil.toList2(jsonArr.toString(), clazz);
109
+		if(temp != null) {
110
+			return temp;
111
+		}
112
+		return new ArrayList<T>();
113
+	}
114
+
115
+	@Override
116
+	public String toString() {
117
+		return "JsonParamBean [total=" + total + ", pageIndex=" + pageIndex + ", pageSize=" + pageSize + ", totalPage=" + totalPage + ", model=" + model + ", list=" + list + ", param=" + param + "]";
118
+	}
119
+
120
+}

+ 100 - 0
src/main/java/com/dashitech/utils/JsonResponse.java

@@ -0,0 +1,100 @@
1
+package com.dashitech.utils;
2
+
3
+import java.io.Serializable;
4
+
5
+
6
+import net.sf.json.JSONObject;
7
+
8
+public class JsonResponse implements Serializable{
9
+	private static final long serialVersionUID = 2275655193720587417L;
10
+	
11
+	/**
12
+	 * 消息
13
+	 */
14
+	private String msg;
15
+	/**
16
+	 * 状态
17
+	 */
18
+	private Integer status;
19
+	/**
20
+	 * 数据
21
+	 */
22
+	private Object data;
23
+	
24
+	public String getMsg() {
25
+		return msg;
26
+	}
27
+
28
+	public void setMsg(String msg) {
29
+		this.msg = msg;
30
+	}
31
+
32
+	public Integer getStatus() {
33
+		return status;
34
+	}
35
+
36
+	public void setStatus(Integer status) {
37
+		this.status = status;
38
+	}
39
+
40
+	public Object getData() {
41
+		return data;
42
+	}
43
+
44
+	public void setData(Object data) {
45
+		this.data = data;
46
+	}
47
+
48
+	public JsonResponse() {
49
+		
50
+	}
51
+	
52
+	public JsonResponse(String msg, Integer status, Object data) {
53
+		super();
54
+		this.msg = msg;
55
+		this.status = status;
56
+		this.data = data;
57
+	}
58
+	
59
+	public static JsonResponse success(Object data) {
60
+		JsonResponse bean = new JsonResponse();
61
+		bean.setData(data);
62
+		bean.setMsg("成功!");
63
+		bean.setStatus(200);
64
+		return bean;
65
+	}
66
+	
67
+	public static JsonResponse error(String msg) {
68
+		JsonResponse bean = new JsonResponse();
69
+		bean.setMsg("服务出错!");
70
+		bean.setStatus(500);
71
+		return bean;
72
+	}
73
+	
74
+	public static JsonResponse forbidden() {
75
+		JsonResponse bean = new JsonResponse();
76
+		bean.setMsg("没有权限!");
77
+		bean.setStatus(403);
78
+		return bean;
79
+	}
80
+	
81
+	public static JsonResponse forbidden(String msg) {
82
+		JsonResponse bean = new JsonResponse();
83
+		bean.setMsg(msg);
84
+		bean.setStatus(403);
85
+		return bean;
86
+	}
87
+
88
+	@Override
89
+	public String toString() {
90
+		try {
91
+			JSONObject json = JsonUtil.toJSONObject(this);
92
+			return json.toString();
93
+		} catch (Exception e) {
94
+			e.printStackTrace();
95
+		}
96
+		return error("json转换错误!").toString();
97
+	}
98
+	
99
+	
100
+}

+ 163 - 0
src/main/java/com/dashitech/utils/JsonUtil.java

@@ -0,0 +1,163 @@
1
+package com.dashitech.utils;
2
+
3
+import com.fasterxml.jackson.databind.DeserializationFeature;
4
+import com.fasterxml.jackson.databind.JavaType;
5
+import com.fasterxml.jackson.databind.SerializationFeature;
6
+import net.sf.json.JSONArray;
7
+import net.sf.json.JSONObject;
8
+import net.sf.json.JsonConfig;
9
+import net.sf.json.processors.JsonValueProcessor;
10
+import net.sf.json.util.CycleDetectionStrategy;
11
+
12
+import java.util.ArrayList;
13
+import java.util.Date;
14
+import java.util.List;
15
+import java.util.Map;
16
+
17
+
18
+public class JsonUtil {
19
+
20
+    public static JSONObject toJSONObject(Object obj) {
21
+        return JSONObject.fromObject(obj, getJsonConfig());
22
+    }
23
+
24
+    public static String toJsonString(Object obj) {
25
+        com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
26
+        mapper.setDateFormat(DateUtil.SDF_DATETIME);
27
+        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
28
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
29
+        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
30
+        try {
31
+            return mapper.writeValueAsString(obj);
32
+        } catch (Exception e) {
33
+            e.printStackTrace();
34
+        }
35
+        return "";
36
+    }
37
+
38
+    public static JSONArray toJSONArray(Object obj) {
39
+        return JSONArray.fromObject(obj, getJsonConfig());
40
+    }
41
+
42
+    public static <T> List<T> toList(Object obj, Class<T> clazz) {
43
+        JSONArray arr = toJSONArray(obj);
44
+        @SuppressWarnings({"unchecked", "deprecation"}) List<T> list = JSONArray.toList(arr, clazz);
45
+        return list;
46
+    }
47
+
48
+    public static <T> List<T> toList(Object obj, Class<T> clazz, Map classMap) {
49
+        JSONArray arr = toJSONArray(obj);
50
+        @SuppressWarnings({"unchecked", "deprecation"}) List<T> list = JSONArray.toList(arr, clazz, classMap);
51
+        return list;
52
+    }
53
+
54
+    /**
55
+     * 会格式化日期为yyyy-MM-dd HH:mm:ss
56
+     */
57
+    @SuppressWarnings({"deprecation"})
58
+    public static <T> List<T> toList2(String json, Class<T> clazz) {
59
+        try {
60
+            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
61
+            mapper.setDateFormat(DateUtil.SDF_DATETIME);
62
+            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
63
+            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
64
+
65
+            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
66
+            List<T> result = mapper.readValue(json, javaType);
67
+            return result;
68
+        } catch (Exception e) {
69
+            e.printStackTrace();
70
+        }
71
+        return null;
72
+    }
73
+
74
+    /**
75
+     * 2016-03-01 00:00:00 替换为 2016-03-01 <br/>
76
+     * 如果报错返回原始数据
77
+     */
78
+    public static JSONObject replaceDateTime(JSONObject source) {
79
+        JSONObject result = source;
80
+        try {
81
+            String ss = source.toString();
82
+            String formatJson = ss.replaceAll(" \\d{2}:\\d{2}:\\d{2}", "");
83
+            result = JSONObject.fromObject(formatJson);
84
+        } catch (Exception e) {
85
+        }
86
+        return result;
87
+    }
88
+
89
+
90
+    public static <T> T toObject(String json, Class<T> valueType) {
91
+        com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
92
+        mapper.setDateFormat(DateUtil.SDF_DATETIME);
93
+        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
94
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
95
+        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
96
+
97
+        try {
98
+            return mapper.readValue(json, valueType);
99
+        } catch (Exception e) {
100
+            e.printStackTrace();
101
+        }
102
+        return null;
103
+    }
104
+
105
+    public static <T> List<T> toListObject(String json, Class<T> valueType) {
106
+        com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
107
+        mapper.setDateFormat(DateUtil.SDF_DATETIME);
108
+        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
109
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
110
+        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
111
+
112
+        try {
113
+            List<T> result = new ArrayList<>();
114
+            List<Map> list = mapper.readValue(json, ArrayList.class);
115
+            for (Map map : list) {
116
+                T t = toObject(toJSONObject(map).toString(), valueType);
117
+                result.add(t);
118
+            }
119
+            return result;
120
+        } catch (Exception e) {
121
+            e.printStackTrace();
122
+        }
123
+        return null;
124
+    }
125
+
126
+    public static JsonConfig getJsonConfig() {
127
+        JsonConfig config = new JsonConfig();
128
+        //去掉class
129
+        config.setIgnoreDefaultExcludes(false);
130
+        //禁止自包含
131
+        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
132
+        //处理日期转换
133
+        config.registerJsonValueProcessor(Date.class, new Date_JsonValueProcessor());
134
+        return config;
135
+    }
136
+
137
+}
138
+
139
+class Date_JsonValueProcessor implements JsonValueProcessor {
140
+
141
+    public Object processArrayValue(Object value, JsonConfig config) {
142
+        return process(value, config);
143
+    }
144
+
145
+    public Object processObjectValue(String key, Object value, JsonConfig config) {
146
+        return process(value, config);
147
+    }
148
+
149
+    ;
150
+
151
+    private Object process(Object value, JsonConfig config) {
152
+        if (value == null) {
153
+            return "";
154
+        }
155
+        if (value instanceof Date) {
156
+            String date = DateUtil.SDF_DATETIME.format((Date) value);
157
+            return date;
158
+        } else {
159
+            return value == null ? null : value.toString();
160
+        }
161
+    }
162
+
163
+}

+ 17 - 0
src/main/java/com/dashitech/utils/MyObjectMapper.java

@@ -0,0 +1,17 @@
1
+package com.dashitech.utils;
2
+
3
+import com.fasterxml.jackson.databind.ObjectMapper;
4
+import com.fasterxml.jackson.databind.SerializationFeature;
5
+
6
+
7
+
8
+public class MyObjectMapper extends ObjectMapper{
9
+	
10
+	private static final long serialVersionUID = 1L;
11
+
12
+	public MyObjectMapper() {
13
+		this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
14
+		this.setDateFormat(new MyObjectMapperDateFormat());
15
+	}
16
+
17
+}

+ 119 - 0
src/main/java/com/dashitech/utils/MyObjectMapperDateFormat.java

@@ -0,0 +1,119 @@
1
+package com.dashitech.utils;
2
+
3
+import java.text.FieldPosition;
4
+import java.text.ParseException;
5
+import java.text.SimpleDateFormat;
6
+import java.util.Date;
7
+
8
+import org.apache.commons.lang.StringUtils;
9
+
10
+public class MyObjectMapperDateFormat extends SimpleDateFormat{
11
+	private static final long serialVersionUID = 1L;
12
+	public static final String Y_M_D = "yyyy-MM-dd";  
13
+    public static final String Y_M_D_HM = "yyyy-MM-dd HH:mm";  
14
+    public static final String Y_M_D_HMS = "yyyy-MM-dd HH:mm:ss";  
15
+    public static final String YMD = "yyyyMMdd";  
16
+    public static final String YMDHM = "yyyyMMddHHmm";  
17
+    public static final String YMDHMS = "yyyyMMddHHmmss";  
18
+    public static final String ymd = "yyyy/MM/dd";  
19
+    public static final String ymd_HM = "yyyy/MM/dd HH:mm";  
20
+    public static final String ymd_HMS = "yyyy/MM/dd HH:mm:ss";  
21
+	
22
+	@Override  
23
+    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {  
24
+        return new StringBuffer(smartFormat(date));  
25
+    }  
26
+  
27
+    @Override  
28
+    public Date parse(String text) throws ParseException {  
29
+        return smartFormat(text);  
30
+    }  
31
+    
32
+    public static String smartFormat(Date date) {  
33
+        String dateStr = null;  
34
+        if (date == null) {  
35
+            dateStr = "";  
36
+        } else {  
37
+            try {  
38
+                dateStr = formatDate(date, Y_M_D_HMS);  
39
+                //时分秒  
40
+                if (dateStr.endsWith(" 00:00:00")) {  
41
+                    dateStr = dateStr.substring(0, 10);  
42
+                }  
43
+                //时分  
44
+                else if (dateStr.endsWith("00:00")) {  
45
+                    dateStr = dateStr.substring(0, 16);  
46
+                }  
47
+                //秒  
48
+                else if (dateStr.endsWith(":00")) {  
49
+                    dateStr = dateStr.substring(0, 16);  
50
+                }  
51
+            } catch (Exception ex) {  
52
+                throw new IllegalArgumentException("转换日期失败: " + ex.getMessage(), ex);  
53
+            }  
54
+        }  
55
+        return dateStr;  
56
+    }  
57
+  
58
+    /** 
59
+     * 智能转换日期 
60
+     * 
61
+     * @param text 
62
+     * @return 
63
+     */  
64
+    public static Date smartFormat(String text) {  
65
+        Date date = null;  
66
+        try {  
67
+            if (text == null || text.length() == 0) {  
68
+                date = null;  
69
+            } else if (text.length() == 10) {  
70
+                date = formatStringToDate(text, Y_M_D);  
71
+            } else if (text.length() == 13) {  
72
+                date = new Date(Long.parseLong(text));  
73
+            } else if (text.length() == 16) {  
74
+                date = formatStringToDate(text, Y_M_D_HM);  
75
+            } else if (text.length() == 19) {  
76
+                date = formatStringToDate(text, Y_M_D_HMS);  
77
+            } else {  
78
+                throw new IllegalArgumentException("日期长度不符合要求!");  
79
+            }  
80
+        } catch (Exception e) {  
81
+            throw new IllegalArgumentException("日期转换失败!");  
82
+        }  
83
+        return date;  
84
+    }  
85
+    
86
+    public static String formatDate(Date argDate, String argFormat) throws Exception {  
87
+        if (argDate == null) {  
88
+            throw new Exception("参数[日期]不能为空!");  
89
+        }  
90
+        if (StringUtils.isEmpty(argFormat)) {  
91
+            argFormat = Y_M_D;  
92
+        }  
93
+        SimpleDateFormat sdfFrom = new SimpleDateFormat(argFormat);  
94
+        return sdfFrom.format(argDate).toString();  
95
+    }  
96
+  
97
+    public static Date formatStringToDate(String argDateStr, String argFormat) throws Exception {  
98
+        if (argDateStr == null || argDateStr.trim().length() < 1) {  
99
+            throw new Exception("参数[日期]不能为空!");  
100
+        }  
101
+        String strFormat = argFormat;  
102
+        if (StringUtils.isEmpty(strFormat)) {  
103
+            strFormat = Y_M_D;  
104
+            if (argDateStr.length() > 16) {  
105
+                strFormat = Y_M_D_HMS;  
106
+            } else if (argDateStr.length() > 10) {  
107
+                strFormat = Y_M_D_HM;  
108
+            }  
109
+        }  
110
+        SimpleDateFormat sdfFormat = new SimpleDateFormat(strFormat);  
111
+        //严格模式  
112
+        sdfFormat.setLenient(false);  
113
+        try {  
114
+            return sdfFormat.parse(argDateStr);  
115
+        } catch (ParseException e) {  
116
+            throw new Exception(e);  
117
+        }  
118
+    } 
119
+}

+ 18 - 0
src/main/java/com/dashitech/utils/MyX509TrustManager.java

@@ -0,0 +1,18 @@
1
+package com.dashitech.utils;
2
+
3
+import javax.net.ssl.X509TrustManager;
4
+import java.security.cert.CertificateException;
5
+import java.security.cert.X509Certificate;
6
+
7
+public class MyX509TrustManager implements X509TrustManager {
8
+	  
9
+    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
10
+    }  
11
+  
12
+    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
13
+    }  
14
+  
15
+    public X509Certificate[] getAcceptedIssuers() {
16
+        return null;  
17
+    }  
18
+}  

+ 272 - 0
src/main/java/com/dashitech/utils/OracleConn.java

@@ -0,0 +1,272 @@
1
+package com.dashitech.utils;
2
+
3
+import java.sql.*;
4
+import java.util.ArrayList;
5
+import java.util.HashMap;
6
+import java.util.List;
7
+import java.util.Map;
8
+
9
+/**
10
+ * Created by xuweihua on 2021/4/1.
11
+ */
12
+public class OracleConn {
13
+    private static String jdbc = PropertiesUtil.getProperty("oracle.conn.jdbc");
14
+    private static String user = PropertiesUtil.getProperty("oracle.user");
15
+    private static String pwd = PropertiesUtil.getProperty("oracle.password");
16
+
17
+    private static String user2 = PropertiesUtil.getProperty("oracle.user2");
18
+    private static String pwd2 = PropertiesUtil.getProperty("oracle.password2");
19
+
20
+    private static String jdbc2 = PropertiesUtil.getProperty("oracle.conn.jdbc2");
21
+    private static String jdbc3 = PropertiesUtil.getProperty("oracle.conn.jdbc3");
22
+
23
+    private static String user3 = PropertiesUtil.getProperty("oracle.user3");
24
+    private static String pwd3 = PropertiesUtil.getProperty("oracle.password3");
25
+
26
+    private static Connection  con = null;// 创建一个数据库连接
27
+    private static Connection  con2 = null;// 创建一个数据库连接
28
+    private static Connection  con3 = null;// 创建一个数据库连接
29
+    private static Connection  con4 = null;// 创建一个数据库连接
30
+
31
+
32
+    public List<Map<String, Object>> getOracleDataList(String sql) {
33
+        List<Map<String, Object>> list = new ArrayList<>();
34
+        PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
35
+        ResultSet result = null;// 创建一个结果集对象
36
+        try {
37
+            if(con == null) {
38
+                Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
39
+                //System.out.println("开始尝试连接数据库!");
40
+                con = DriverManager.getConnection(jdbc, user, pwd);// 获取连接
41
+                //System.out.println("连接成功!");
42
+            }
43
+            pre = con.prepareStatement(sql);
44
+            result = pre.executeQuery();
45
+            ResultSetMetaData md = result.getMetaData();// 获得结果集结构信息(元数据)
46
+            int columnCount = md.getColumnCount();// ResultSet列数
47
+            // ResultSet转List<Map>数据结构
48
+            // next用于移动到ResultSet的下一行,使下一行成为当前行
49
+            while (result.next()) {
50
+                Map<String, Object> map = new HashMap<>();
51
+                for (int i = 1; i <= columnCount; i++) {// 遍历获取对当前行的每一列的键值对,put到map中
52
+                    // rs.getObject(i) 获得当前行某一列字段的值
53
+                    map.put(md.getColumnName(i).toLowerCase(), result.getObject(i));
54
+                }
55
+                list.add(map);
56
+            }
57
+            return list;
58
+        }catch (Exception e) {
59
+            e.printStackTrace();
60
+            try {
61
+                if (con != null) { // 使用单例模式不关闭连接
62
+                    con.close();
63
+                    con = null;
64
+                    System.out.println("关闭数据库连接!");
65
+                }
66
+            }catch (Exception ex){
67
+                ex.printStackTrace();
68
+            }
69
+        } finally {
70
+            try {
71
+                // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
72
+                // 注意关闭的顺序,最后使用的最先关闭
73
+                if (result != null) {
74
+                    result.close();
75
+                }
76
+                if (pre != null) {
77
+                    pre.close();
78
+                }
79
+                if (con != null) { // 使用单例模式不关闭连接
80
+                    // con.close();
81
+                  //  System.out.println("关闭数据库连接!");
82
+                }
83
+            } catch (Exception e) {
84
+                e.printStackTrace();
85
+            }
86
+        }
87
+        return list;
88
+    }
89
+
90
+    /**
91
+     * 手术专用
92
+     * @param sql
93
+     * @return
94
+     */
95
+    public List<Map<String, Object>> getSurgeryOracleDataList(String sql) {
96
+        List<Map<String, Object>> list = new ArrayList<>();
97
+        PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
98
+        ResultSet result = null;// 创建一个结果集对象
99
+        try {
100
+            if(con2 == null) {
101
+                Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
102
+                //System.out.println("开始尝试连接数据库!");
103
+                con2 = DriverManager.getConnection(jdbc, user2, pwd2);// 获取连接
104
+                //System.out.println("连接成功!");
105
+            }
106
+            pre = con2.prepareStatement(sql);
107
+            result = pre.executeQuery();
108
+            ResultSetMetaData md = result.getMetaData();// 获得结果集结构信息(元数据)
109
+            int columnCount = md.getColumnCount();// ResultSet列数
110
+            // ResultSet转List<Map>数据结构
111
+            // next用于移动到ResultSet的下一行,使下一行成为当前行
112
+            while (result.next()) {
113
+                Map<String, Object> map = new HashMap<>();
114
+                for (int i = 1; i <= columnCount; i++) {// 遍历获取对当前行的每一列的键值对,put到map中
115
+                    // rs.getObject(i) 获得当前行某一列字段的值
116
+                    map.put(md.getColumnName(i).toLowerCase(), result.getObject(i));
117
+                }
118
+                list.add(map);
119
+            }
120
+            return list;
121
+        }catch (Exception e) {
122
+            e.printStackTrace();
123
+            try {
124
+                if (con2 != null) { // 使用单例模式不关闭连接
125
+                    con2.close();
126
+                    con2 = null;
127
+                    System.out.println("关闭数据库连接!");
128
+                }
129
+            }catch (Exception ex){
130
+                ex.printStackTrace();
131
+            }
132
+        } finally {
133
+            try {
134
+                // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
135
+                // 注意关闭的顺序,最后使用的最先关闭
136
+                if (result != null) {
137
+                    result.close();
138
+                }
139
+                if (pre != null) {
140
+                    pre.close();
141
+                }
142
+                if (con2 != null) { // 使用单例模式不关闭连接
143
+                    // con.close();
144
+                    //  System.out.println("关闭数据库连接!");
145
+                }
146
+            } catch (Exception e) {
147
+                e.printStackTrace();
148
+            }
149
+        }
150
+        return list;
151
+    }
152
+
153
+    /**
154
+     * 血制品
155
+     * @author song
156
+     * @date 2024/08/06
157
+     * @param sql
158
+     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
159
+     */
160
+    public List<Map<String, Object>> getBloodOracleDataList(String sql) {
161
+        List<Map<String, Object>> list = new ArrayList<>();
162
+        PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
163
+        ResultSet result = null;// 创建一个结果集对象
164
+        try {
165
+            if(con3 == null) {
166
+                Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
167
+                con3 = DriverManager.getConnection(jdbc2, user3, pwd3);// 获取连接
168
+            }
169
+            pre = con3.prepareStatement(sql);
170
+            result = pre.executeQuery();
171
+            ResultSetMetaData md = result.getMetaData();// 获得结果集结构信息(元数据)
172
+            int columnCount = md.getColumnCount();// ResultSet列数
173
+            // ResultSet转List<Map>数据结构
174
+            // next用于移动到ResultSet的下一行,使下一行成为当前行
175
+            while (result.next()) {
176
+                Map<String, Object> map = new HashMap<>();
177
+                for (int i = 1; i <= columnCount; i++) {// 遍历获取对当前行的每一列的键值对,put到map中
178
+                    // rs.getObject(i) 获得当前行某一列字段的值
179
+                    map.put(md.getColumnName(i).toLowerCase(), result.getObject(i));
180
+                }
181
+                list.add(map);
182
+            }
183
+            return list;
184
+        }catch (Exception e) {
185
+            e.printStackTrace();
186
+            try {
187
+                if (con3 != null) { // 使用单例模式不关闭连接
188
+                    con3.close();
189
+                    con3 = null;
190
+                    System.out.println("关闭数据库连接!");
191
+                }
192
+            }catch (Exception ex){
193
+                ex.printStackTrace();
194
+            }
195
+        } finally {
196
+            try {
197
+                // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
198
+                // 注意关闭的顺序,最后使用的最先关闭
199
+                if (result != null) {
200
+                    result.close();
201
+                }
202
+                if (pre != null) {
203
+                    pre.close();
204
+                }
205
+            } catch (Exception e) {
206
+                e.printStackTrace();
207
+            }
208
+        }
209
+        return list;
210
+    }
211
+
212
+    /**
213
+     * 标本
214
+     * @author song
215
+     * @date 2024/08/06
216
+     * @param sql
217
+     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
218
+     */
219
+    public List<Map<String, Object>> getSpecimenOracleDataList(String sql) {
220
+        List<Map<String, Object>> list = new ArrayList<>();
221
+        PreparedStatement pre = null;// 创建预编译语句对象,一般都是用这个而不用Statement
222
+        ResultSet result = null;// 创建一个结果集对象
223
+        try {
224
+            if(con4 == null) {
225
+                Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动程序
226
+                con4 = DriverManager.getConnection(jdbc3, user3, pwd3);// 获取连接
227
+            }
228
+            pre = con4.prepareStatement(sql);
229
+            result = pre.executeQuery();
230
+            ResultSetMetaData md = result.getMetaData();// 获得结果集结构信息(元数据)
231
+            int columnCount = md.getColumnCount();// ResultSet列数
232
+            // ResultSet转List<Map>数据结构
233
+            // next用于移动到ResultSet的下一行,使下一行成为当前行
234
+            while (result.next()) {
235
+                Map<String, Object> map = new HashMap<>();
236
+                for (int i = 1; i <= columnCount; i++) {// 遍历获取对当前行的每一列的键值对,put到map中
237
+                    // rs.getObject(i) 获得当前行某一列字段的值
238
+                    map.put(md.getColumnName(i).toLowerCase(), result.getObject(i));
239
+                }
240
+                list.add(map);
241
+            }
242
+            return list;
243
+        }catch (Exception e) {
244
+            e.printStackTrace();
245
+            try {
246
+                if (con4 != null) { // 使用单例模式不关闭连接
247
+                    con4.close();
248
+                    con4 = null;
249
+                    System.out.println("关闭数据库连接!");
250
+                }
251
+            }catch (Exception ex){
252
+                ex.printStackTrace();
253
+            }
254
+        } finally {
255
+            try {
256
+                // 逐一将上面的几个对象关闭,因为不关闭的话会影响性能、并且占用资源
257
+                // 注意关闭的顺序,最后使用的最先关闭
258
+                if (result != null) {
259
+                    result.close();
260
+                }
261
+                if (pre != null) {
262
+                    pre.close();
263
+                }
264
+            } catch (Exception e) {
265
+                e.printStackTrace();
266
+            }
267
+        }
268
+        return list;
269
+    }
270
+
271
+
272
+}

+ 49 - 0
src/main/java/com/dashitech/utils/Page.java

@@ -0,0 +1,49 @@
1
+package com.dashitech.utils;
2
+
3
+import java.io.Serializable;
4
+
5
+/**
6
+ * Created by xuweihua on 2021/4/2.
7
+ */
8
+public class Page implements Serializable {
9
+    private int pageNow = 1; // 当前页数
10
+    private int pageSize = 200; // 每页显示记录的条数(根据自身需求修改每页显示条数)
11
+    private int totalCount; // 总记录条数
12
+    private int totalPageCount; // 总页数
13
+    private int startPos; // 开始位置,从0开始
14
+    //构造函数,参数:总记录数和当前页
15
+    public Page(int totalCount, int pageNow) {
16
+        this.totalCount = totalCount;
17
+        this.pageNow = pageNow;
18
+    }
19
+    //计算总页数,总页数=总记录数/每页显示记录的条数
20
+    public int getTotalPageCount() {
21
+        totalPageCount = getTotalCount() / getPageSize();
22
+        return (totalCount % pageSize == 0) ? totalPageCount : totalPageCount + 1;
23
+    }
24
+    public void setTotalPageCount(int totalPageCount) {
25
+        this.totalPageCount = totalPageCount;
26
+    }
27
+    public int getPageNow() {
28
+        return pageNow;
29
+    }
30
+    public void setPageNow(int pageNow) {
31
+        this.pageNow = pageNow;
32
+    }
33
+    public int getPageSize() {
34
+        return pageSize;
35
+    }
36
+    public void setPageSize(int pageSize) {
37
+        this.pageSize = pageSize;
38
+    }
39
+    public int getTotalCount() {
40
+        return totalCount;
41
+    }
42
+    public void setTotalCount(int totalCount) {
43
+        this.totalCount = totalCount;
44
+    }
45
+    //取得选择记录的初始位置
46
+    public int getStartPos() {
47
+        return (pageNow - 1) * pageSize;
48
+    }
49
+}

+ 61 - 0
src/main/java/com/dashitech/utils/PortalVerifystUtils.java

@@ -0,0 +1,61 @@
1
+package com.dashitech.utils;
2
+
3
+import com.alibaba.fastjson.JSONObject;
4
+
5
+
6
+import java.text.SimpleDateFormat;
7
+import java.util.Date;
8
+import java.util.UUID;
9
+
10
+/**
11
+ * Created by xuweihua on 2021/3/5.
12
+ */
13
+public class PortalVerifystUtils {
14
+//    private static String SSO_VERIFYST = PropertiesUtil.getProperty("SSO_VERIFYST");
15
+//    private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
16
+//    private static Client svclient;
17
+//    private static Client getClient(){
18
+//        if (svclient!=null){
19
+//            return svclient;
20
+//        }else{
21
+//            // 创建动态客户端
22
+//            JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
23
+//            svclient = dcf.createClient(SSO_VERIFYST);
24
+//            return svclient;
25
+//        }
26
+//    }
27
+//    public static String verifyst(String st,String Url){
28
+//        Client client = getClient();
29
+//        Object[] objects;
30
+//        try {
31
+//            String params = "<Request> \n" +
32
+//                    "<MessageHeader> \n" +
33
+//                    "<Sender>DSTECH</Sender> \n" +
34
+//                    "<Receiver>UUM</Receiver> \n" +
35
+//                    "<SendTime>"+sdf2.format(new Date())+"</SendTime> \n" +
36
+//                    "<EventType>SSO_VERIFYST</EventType> \n" +
37
+//                    "<MsgId>"+UUID.randomUUID()+"</MsgId> \n" +
38
+//                    "</MessageHeader> \n" +
39
+//                    "<MessageBody> \n" +
40
+//                    "<ST>"+st+"</ST> \n" +
41
+//                    "<Url>"+Url+"</Url> \n" +
42
+//                    "</MessageBody> \n" +
43
+//                    "</Request>";
44
+//            objects = client.invoke("initCasWebService", params);
45
+//            String redate = objects[0]+"";
46
+//            System.out.println("verifyst======================:" + redate);
47
+//            JSONObject jData= XmlToJson.xml2Json(redate);
48
+//            JSONObject result = jData.getJSONObject("MessageBody").getJSONObject("Result");
49
+//            if (result.getString("Code").equals("CA")){
50
+//                Object userId = jData.getJSONObject("MessageBody").get("UserId");
51
+//                if (userId!=null){
52
+//                    System.out.println("OK======================:" + userId);
53
+//                    return  userId+"";
54
+//                }
55
+//            }
56
+//        } catch (Exception e) {
57
+//            e.printStackTrace();
58
+//        }
59
+//        return null;
60
+//    }
61
+}

+ 506 - 0
src/main/java/com/dashitech/utils/PropertiesHelper.java

@@ -0,0 +1,506 @@
1
+package com.dashitech.utils;
2
+
3
+import java.io.ByteArrayInputStream;
4
+import java.io.IOException;
5
+import java.io.InputStream;
6
+import java.io.OutputStream;
7
+import java.io.PrintStream;
8
+import java.io.PrintWriter;
9
+import java.net.MalformedURLException;
10
+import java.net.URL;
11
+import java.util.Collection;
12
+import java.util.Enumeration;
13
+import java.util.InvalidPropertiesFormatException;
14
+import java.util.Map;
15
+import java.util.Properties;
16
+import java.util.Set;
17
+import java.util.Map.Entry;
18
+
19
+/**
20
+ * Properties的操作的工具类,为Properties提供一个代理增加相关工具方法如
21
+ * getRequiredString(),getInt(),getBoolean()等方法
22
+ * 并可以通过systemPropertiesMode属性指定是否搜索System.getProperty()及System.getenv()来查找值.
23
+ * 默认不搜索系统属性
24
+ * 
25
+ * <pre>
26
+ * 使用1:
27
+ * public class ConnectionUtils {
28
+ *     static Properties properties = new Properties(); 
29
+ *     // ... do load properties 
30
+ *     
31
+ *     // delegate to properties
32
+ * 	   static PropertiesHelper props = new PropertiesHelper(properties);
33
+ *     public static Connection getConnection() {
34
+ *     		// use getRequiredProperty() 
35
+ *     		DriverManager.getConnection(props.getRequiredString("jdbc.url"));
36
+ *     }
37
+ * }
38
+ * 指定是否搜索系统属性:
39
+ * new PropertiesHelper(properties,PropertiesHelper.SYSTEM_PROPERTIES_MODE_OVERRIDE)
40
+ * </pre>
41
+ * 
42
+ * @author badqiu
43
+ */
44
+public class PropertiesHelper {
45
+	/**
46
+	 * 不使用系统属性,这个是默认值
47
+	 **/
48
+	public static final int SYSTEM_PROPERTIES_MODE_NEVER = 0;
49
+
50
+	/**
51
+	 * 如果在properties中没有找到属性值,则查找系统属性
52
+	 */
53
+	public static final int SYSTEM_PROPERTIES_MODE_FALLBACK = 1;
54
+
55
+	/**
56
+	 * 首先查找系统属性,如果没有找到值,再查找properties,这可以用于系统属性覆盖properties中的值
57
+	 */
58
+	public static final int SYSTEM_PROPERTIES_MODE_OVERRIDE = 2;
59
+
60
+	private int systemPropertiesMode = SYSTEM_PROPERTIES_MODE_NEVER;
61
+
62
+	private Properties p;
63
+
64
+	public PropertiesHelper(Properties p) {
65
+		setProperties(p);
66
+	}
67
+
68
+	public PropertiesHelper(Properties p, int systemPropertiesMode) {
69
+		setProperties(p);
70
+		if (systemPropertiesMode != SYSTEM_PROPERTIES_MODE_NEVER && systemPropertiesMode != SYSTEM_PROPERTIES_MODE_FALLBACK
71
+				&& systemPropertiesMode != SYSTEM_PROPERTIES_MODE_OVERRIDE) {
72
+			throw new IllegalArgumentException("error systemPropertiesMode mode:" + systemPropertiesMode);
73
+		}
74
+		this.systemPropertiesMode = systemPropertiesMode;
75
+	}
76
+
77
+	public Properties getProperties() {
78
+		return p;
79
+	}
80
+
81
+	public void setProperties(Properties props) {
82
+		if (props == null)
83
+			throw new IllegalArgumentException("properties must be not null");
84
+		this.p = props;
85
+	}
86
+
87
+	/**
88
+	 * 必须存在这个key的值,不然抛 IllegalStateException异常
89
+	 **/
90
+	public String getRequiredProperty(String key) throws IllegalStateException {
91
+		String value = getProperty(key);
92
+		if (isBlankString(value)) {
93
+			throw new IllegalStateException("required property is blank by key=" + key);
94
+		}
95
+		return value;
96
+	}
97
+
98
+	/**
99
+	 * 返回null,如果查值的属性值是blank
100
+	 * 
101
+	 * @param key
102
+	 * @return
103
+	 */
104
+	public String getNullIfBlank(String key) {
105
+		String value = getProperty(key);
106
+		if (isBlankString(value)) {
107
+			return null;
108
+		}
109
+		return value;
110
+	}
111
+
112
+	/**
113
+	 * 返回null,如果查值的属性值是empty
114
+	 * 
115
+	 * @param key
116
+	 * @return
117
+	 */
118
+	public String getNullIfEmpty(String key) {
119
+		String value = getProperty(key);
120
+		if (value == null || "".equals(value)) {
121
+			return null;
122
+		}
123
+		return value;
124
+	}
125
+
126
+	/**
127
+	 * 尝试从System.getProperty(key)及System.getenv(key)得到值
128
+	 * 
129
+	 * @return
130
+	 */
131
+	public String getAndTryFromSystem(String key) {
132
+		String value = getProperty(key);
133
+		if (isBlankString(value)) {
134
+			value = getSystemProperty(key);
135
+		}
136
+		return value;
137
+	}
138
+
139
+	private String getSystemProperty(String key) {
140
+		String value;
141
+		value = System.getProperty(key);
142
+		if (isBlankString(value)) {
143
+			value = System.getenv(key);
144
+		}
145
+		return value;
146
+	}
147
+
148
+	public Integer getInteger(String key) {
149
+		String value = getProperty(key);
150
+		if (isBlankString(value)) {
151
+			return null;
152
+		}
153
+		return Integer.parseInt(value);
154
+	}
155
+
156
+	public int getInt(String key, int defaultValue) {
157
+		String value = getProperty(key);
158
+		if (isBlankString(value)) {
159
+			return defaultValue;
160
+		}
161
+		return Integer.parseInt(value);
162
+	}
163
+
164
+	/**
165
+	 * 必须存在这个key的值,不然抛 IllegalStateException异常
166
+	 **/
167
+	public int getRequiredInt(String key) throws IllegalStateException {
168
+		return Integer.parseInt(getRequiredProperty(key));
169
+	}
170
+
171
+	public Long getLong(String key) {
172
+		String value = getProperty(key);
173
+		if (isBlankString(value)) {
174
+			return null;
175
+		}
176
+		return Long.parseLong(value);
177
+	}
178
+
179
+	public long getLong(String key, long defaultValue) {
180
+		String value = getProperty(key);
181
+		if (isBlankString(value)) {
182
+			return defaultValue;
183
+		}
184
+		return Long.parseLong(value);
185
+	}
186
+
187
+	/**
188
+	 * 必须存在这个key的值,不然抛 IllegalStateException异常
189
+	 **/
190
+	public long getRequiredLong(String key) throws IllegalStateException {
191
+		return Long.parseLong(getRequiredProperty(key));
192
+	}
193
+
194
+	public Boolean getBoolean(String key) {
195
+		String value = getProperty(key);
196
+		if (isBlankString(value)) {
197
+			return null;
198
+		}
199
+		return Boolean.parseBoolean(value);
200
+	}
201
+
202
+	public boolean getBoolean(String key, boolean defaultValue) {
203
+		String value = getProperty(key);
204
+		if (isBlankString(value)) {
205
+			return defaultValue;
206
+		}
207
+		return Boolean.parseBoolean(value);
208
+	}
209
+
210
+	/**
211
+	 * 必须存在这个key的值,不然抛 IllegalStateException异常
212
+	 **/
213
+	public boolean getRequiredBoolean(String key) throws IllegalStateException {
214
+		return Boolean.parseBoolean(getRequiredProperty(key));
215
+	}
216
+
217
+	public Float getFloat(String key) {
218
+		String value = getProperty(key);
219
+		if (isBlankString(value)) {
220
+			return null;
221
+		}
222
+		return Float.parseFloat(value);
223
+	}
224
+
225
+	public float getFloat(String key, float defaultValue) {
226
+		String value = getProperty(key);
227
+		if (isBlankString(value)) {
228
+			return defaultValue;
229
+		}
230
+		return Float.parseFloat(value);
231
+	}
232
+
233
+	/**
234
+	 * 必须存在这个key的值,不然抛 IllegalStateException异常
235
+	 **/
236
+	public float getRequiredFloat(String key) throws IllegalStateException {
237
+		return Float.parseFloat(getRequiredProperty(key));
238
+	}
239
+
240
+	public Double getDouble(String key) {
241
+		String value = getProperty(key);
242
+		if (isBlankString(value)) {
243
+			return null;
244
+		}
245
+		return Double.parseDouble(value);
246
+	}
247
+
248
+	public double getDouble(String key, double defaultValue) {
249
+		String value = getProperty(key);
250
+		if (isBlankString(value)) {
251
+			return defaultValue;
252
+		}
253
+		return Double.parseDouble(value);
254
+	}
255
+
256
+	/**
257
+	 * 必须存在这个key的值,不然抛 IllegalStateException异常
258
+	 **/
259
+	public double getRequiredDouble(String key) throws IllegalStateException {
260
+		return Double.parseDouble(getRequiredProperty(key));
261
+	}
262
+
263
+	public URL getURL(String key) throws IllegalArgumentException {
264
+		try {
265
+			return new URL(getProperty(key));
266
+		} catch (MalformedURLException e) {
267
+			throw new IllegalArgumentException("Property " + key + " must be a valid URL (" + getProperty(key) + ")");
268
+		}
269
+	}
270
+
271
+	public Object getClassInstance(String key) throws IllegalArgumentException {
272
+		String s = (String) getProperty(key);
273
+		if (s == null || "".equals(s.trim())) {
274
+			throw new IllegalArgumentException("Property " + key + " must be a valid classname  : " + key);
275
+		}
276
+		try {
277
+			return Class.forName(s).newInstance();
278
+		} catch (ClassNotFoundException nfe) {
279
+			throw new IllegalArgumentException(s + ": invalid class name for key " + key, nfe);
280
+		} catch (InstantiationException e) {
281
+			throw new IllegalArgumentException(s + ": class could not be reflected " + s, e);
282
+		} catch (IllegalAccessException e) {
283
+			throw new IllegalArgumentException(s + ": class could not be reflected " + s, e);
284
+		}
285
+	}
286
+
287
+	public Object getClassInstance(String key, Object defaultinstance) throws IllegalArgumentException {
288
+		return (containsKey(key) ? getClassInstance(key) : defaultinstance);
289
+	}
290
+
291
+	/**
292
+	 * 将一个property按"逗号,空格,换行符"分隔,并返回一个String[]数组
293
+	 **/
294
+	public String[] getStringArray(String key) {
295
+		String v = getProperty(key);
296
+		if (v == null) {
297
+			return new String[0];
298
+		} else {
299
+			return org.springframework.util.StringUtils.tokenizeToStringArray(v, ", \t\n\r\f");
300
+		}
301
+	}
302
+
303
+	/**
304
+	 * 将一个property按"逗号,空格,换行符"分隔,并返回一个int[]数组
305
+	 **/
306
+	public int[] getIntArray(String key) {
307
+		return toIntArray(getStringArray(key));
308
+	}
309
+
310
+	/**
311
+	 * 得到以某个前缀开始的所有属性,返回的属性值为移除前缀后的属性值.
312
+	 * 
313
+	 * @param prefix
314
+	 * @return
315
+	 */
316
+	public Properties getStartsWithProperties(String prefix) {
317
+		if (prefix == null)
318
+			throw new IllegalArgumentException("'prefix' must be not null");
319
+
320
+		Properties props = getProperties();
321
+
322
+		Properties result = new Properties();
323
+		for (Entry<Object, Object> entry : props.entrySet()) {
324
+			String key = (String) entry.getKey();
325
+			if (key != null && key.startsWith(prefix)) {
326
+				result.put(key.substring(prefix.length()), entry.getValue());
327
+			}
328
+		}
329
+		return result;
330
+	}
331
+
332
+	/** setProperty(String key,int value) ... start */
333
+
334
+	public Object setProperty(String key, int value) {
335
+		return setProperty(key, String.valueOf(value));
336
+	}
337
+
338
+	public Object setProperty(String key, long value) {
339
+		return setProperty(key, String.valueOf(value));
340
+	}
341
+
342
+	public Object setProperty(String key, float value) {
343
+		return setProperty(key, String.valueOf(value));
344
+	}
345
+
346
+	public Object setProperty(String key, double value) {
347
+		return setProperty(key, String.valueOf(value));
348
+	}
349
+
350
+	public Object setProperty(String key, boolean value) {
351
+		return setProperty(key, String.valueOf(value));
352
+	}
353
+
354
+	/** delegate method start */
355
+
356
+	public String getProperty(String key, String defaultValue) {
357
+		String value = getProperty(key);
358
+		if (isBlankString(value)) {
359
+			return defaultValue;
360
+		}
361
+		return value;
362
+	}
363
+
364
+	public String getProperty(String key) {
365
+		String propVal = null;
366
+		if (systemPropertiesMode == SYSTEM_PROPERTIES_MODE_OVERRIDE) {
367
+			propVal = getSystemProperty(key);
368
+		}
369
+		if (propVal == null) {
370
+			propVal = p.getProperty(key);
371
+		}
372
+		if (propVal == null && systemPropertiesMode == SYSTEM_PROPERTIES_MODE_FALLBACK) {
373
+			propVal = getSystemProperty(key);
374
+		}
375
+		return propVal == null ? null : propVal.trim();
376
+	}
377
+
378
+	public Object setProperty(String key, String value) {
379
+		return p.setProperty(key, value);
380
+	}
381
+
382
+	public void clear() {
383
+		p.clear();
384
+	}
385
+
386
+	public Set<Entry<Object, Object>> entrySet() {
387
+		return p.entrySet();
388
+	}
389
+
390
+	public Enumeration<?> propertyNames() {
391
+		return p.propertyNames();
392
+	}
393
+
394
+	public boolean contains(Object value) {
395
+		return p.contains(value);
396
+	}
397
+
398
+	public boolean containsKey(Object key) {
399
+		return p.containsKey(key);
400
+	}
401
+
402
+	public boolean containsValue(Object value) {
403
+		return p.containsValue(value);
404
+	}
405
+
406
+	public Enumeration<Object> elements() {
407
+		return p.elements();
408
+	}
409
+
410
+	public Object get(Object key) {
411
+		return p.get(key);
412
+	}
413
+
414
+	public boolean isEmpty() {
415
+		return p.isEmpty();
416
+	}
417
+
418
+	public Enumeration<Object> keys() {
419
+		return p.keys();
420
+	}
421
+
422
+	public Set<Object> keySet() {
423
+		return p.keySet();
424
+	}
425
+
426
+	public void list(PrintStream out) {
427
+		p.list(out);
428
+	}
429
+
430
+	public void list(PrintWriter out) {
431
+		p.list(out);
432
+	}
433
+
434
+	public void load(InputStream inStream) throws IOException {
435
+		p.load(inStream);
436
+	}
437
+
438
+	public void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException {
439
+		p.loadFromXML(in);
440
+	}
441
+
442
+	public Object put(Object key, Object value) {
443
+		return p.put(key, value);
444
+	}
445
+
446
+	public void putAll(Map<? extends Object, ? extends Object> t) {
447
+		p.putAll(t);
448
+	}
449
+
450
+	public Object remove(Object key) {
451
+		return p.remove(key);
452
+	}
453
+
454
+	/** @deprecated */
455
+	public void save(OutputStream out, String comments) {
456
+		p.save(out, comments);
457
+	}
458
+
459
+	public int size() {
460
+		return p.size();
461
+	}
462
+
463
+	public void store(OutputStream out, String comments) throws IOException {
464
+		p.store(out, comments);
465
+	}
466
+
467
+	public void storeToXML(OutputStream os, String comment, String encoding) throws IOException {
468
+		p.storeToXML(os, comment, encoding);
469
+	}
470
+
471
+	public void storeToXML(OutputStream os, String comment) throws IOException {
472
+		p.storeToXML(os, comment);
473
+	}
474
+
475
+	public Collection<Object> values() {
476
+		return p.values();
477
+	}
478
+
479
+	public String toString() {
480
+		return p.toString();
481
+	}
482
+
483
+	public static Properties restoreFromString(String str) {
484
+		if (str == null)
485
+			return new Properties();
486
+		Properties p = new Properties();
487
+		try {
488
+			p.load(new ByteArrayInputStream(str.getBytes()));
489
+		} catch (IOException e) {
490
+			throw new IllegalStateException("restore properties from String occer error. str:" + str, e);
491
+		}
492
+		return p;
493
+	}
494
+
495
+	private static boolean isBlankString(String value) {
496
+		return value == null || "".equals(value.trim());
497
+	}
498
+
499
+	private static int[] toIntArray(String[] array) {
500
+		int[] result = new int[array.length];
501
+		for (int i = 0; i < array.length; i++) {
502
+			result[i] = Integer.parseInt(array[i]);
503
+		}
504
+		return result;
505
+	}
506
+}

+ 179 - 0
src/main/java/com/dashitech/utils/PropertiesUtil.java

@@ -0,0 +1,179 @@
1
+package com.dashitech.utils;
2
+
3
+import org.apache.commons.logging.Log;
4
+import org.apache.commons.logging.LogFactory;
5
+import org.springframework.beans.factory.InitializingBean;
6
+import org.springframework.util.Assert;
7
+
8
+import java.net.URL;
9
+import java.util.HashMap;
10
+import java.util.Map;
11
+import java.util.Properties;
12
+
13
+/**
14
+ * 用于持有Properties,将Propereis变成静态方法使用.
15
+ */
16
+public class PropertiesUtil implements InitializingBean {
17
+	private static Log log = LogFactory.getLog(PropertiesUtil.class);
18
+
19
+	public static PropertiesHelper properies = null;
20
+
21
+	public void setProperties(Properties properies) {
22
+		Assert.isNull(PropertiesUtil.properies, "PropertiesUtil alreade hold properties");
23
+		PropertiesUtil.properies = new PropertiesHelper(properies);
24
+	}
25
+
26
+	// /**
27
+	// * 重新设置properties
28
+	// * @param properties
29
+	// */
30
+	// public void resetProperties(Properties properties) {
31
+	// clearHolder();
32
+	// new PropertiesUtil().setProperties(properties);
33
+	// }
34
+
35
+	/**
36
+	 * 清空 holder,只有清空Holder才可以重新设置 Properties
37
+	 */
38
+	public static void clearHolder() {
39
+		properies = null;
40
+	}
41
+
42
+	public static void setProperty(String key, String value) {
43
+		getRequiredHelper().setProperty(key, value);
44
+	}
45
+
46
+	/**
47
+	 * get readonly Properties
48
+	 **/
49
+	public static Properties getProperies() {
50
+		return (Properties) getRequiredHelper().getProperties().clone();
51
+	}
52
+
53
+	public static boolean getBoolean(String key, boolean defaultValue) {
54
+		return getRequiredHelper().getBoolean(key, defaultValue);
55
+	}
56
+
57
+	public static Boolean getBoolean(String key) {
58
+		return getRequiredHelper().getBoolean(key);
59
+	}
60
+
61
+	public static Object getClassInstance(String key, Object defaultinstance) throws IllegalArgumentException {
62
+		return getRequiredHelper().getClassInstance(key, defaultinstance);
63
+	}
64
+
65
+	public static Object getClassInstance(String key) throws IllegalArgumentException {
66
+		return getRequiredHelper().getClassInstance(key);
67
+	}
68
+
69
+	public static double getDouble(String key, double defaultValue) {
70
+		return getRequiredHelper().getDouble(key, defaultValue);
71
+	}
72
+
73
+	public static Double getDouble(String key) {
74
+		return getRequiredHelper().getDouble(key);
75
+	}
76
+
77
+	public static float getFloat(String key, float defaultValue) {
78
+		return getRequiredHelper().getFloat(key, defaultValue);
79
+	}
80
+
81
+	public static Float getFloat(String key) {
82
+		return getRequiredHelper().getFloat(key);
83
+	}
84
+
85
+	public static int getInt(String key, int defaultValue) {
86
+		return getRequiredHelper().getInt(key, defaultValue);
87
+	}
88
+
89
+	public static int[] getIntArray(String key) {
90
+		return getRequiredHelper().getIntArray(key);
91
+	}
92
+
93
+	public static Integer getInteger(String key) {
94
+		return getRequiredHelper().getInteger(key);
95
+	}
96
+
97
+	public static long getLong(String key, long defaultValue) {
98
+		return getRequiredHelper().getLong(key, defaultValue);
99
+	}
100
+
101
+	public static Long getLong(String key) {
102
+		return getRequiredHelper().getLong(key);
103
+	}
104
+
105
+	public static String getNullIfBlank(String key) {
106
+		return getRequiredHelper().getNullIfBlank(key);
107
+	}
108
+
109
+	public static String getNullIfEmpty(String key) {
110
+		return getRequiredHelper().getNullIfEmpty(key);
111
+	}
112
+
113
+	public static String getProperty(String key, String defaultValue) {
114
+		return getRequiredHelper().getProperty(key, defaultValue);
115
+	}
116
+
117
+	public static String getProperty(String key) {
118
+		return getRequiredHelper().getProperty(key);
119
+	}
120
+
121
+	public static boolean getRequiredBoolean(String key) throws IllegalStateException {
122
+		return getRequiredHelper().getRequiredBoolean(key);
123
+	}
124
+
125
+	public static double getRequiredDouble(String key) throws IllegalStateException {
126
+		return getRequiredHelper().getRequiredDouble(key);
127
+	}
128
+
129
+	public static float getRequiredFloat(String key) throws IllegalStateException {
130
+		return getRequiredHelper().getRequiredFloat(key);
131
+	}
132
+
133
+	public static int getRequiredInt(String key) throws IllegalStateException {
134
+		return getRequiredHelper().getRequiredInt(key);
135
+	}
136
+
137
+	public static long getRequiredLong(String key) throws IllegalStateException {
138
+		return getRequiredHelper().getRequiredLong(key);
139
+	}
140
+
141
+	public static String getRequiredProperty(String key) throws IllegalStateException {
142
+		return getRequiredHelper().getRequiredProperty(key);
143
+	}
144
+
145
+	public static Properties getStartsWithProperties(String prefix) {
146
+		return getRequiredHelper().getStartsWithProperties(prefix);
147
+	}
148
+
149
+	public static String[] getStringArray(String key) {
150
+		return getRequiredHelper().getStringArray(key);
151
+	}
152
+
153
+	public static URL getURL(String key) throws IllegalArgumentException {
154
+		return getRequiredHelper().getURL(key);
155
+	}
156
+
157
+	private static PropertiesHelper getRequiredHelper() {
158
+		assertHolderInited();
159
+		return properies;
160
+	}
161
+
162
+	private static void assertHolderInited() {
163
+		if (properies == null)
164
+			throw new IllegalStateException("PropertiesUtil.properties must be not null, PropertiesUtil not yet init.");
165
+	}
166
+
167
+	public void afterPropertiesSet() throws Exception {
168
+		assertHolderInited();
169
+		log.info("PropertiesUtil holded properties:" + getProperies());
170
+	}
171
+	
172
+	public static Map<String,String> getAsMap() {
173
+		Map<String,String> configs = new HashMap<String, String>();
174
+		for( Map.Entry<Object,Object> entry : properies.entrySet()) {
175
+			configs.put(entry.getKey().toString(), entry.getValue().toString());
176
+		}
177
+		return configs;
178
+	}
179
+}

+ 69 - 0
src/main/java/com/dashitech/utils/Sha1Util.java

@@ -0,0 +1,69 @@
1
+package com.dashitech.utils;
2
+
3
+
4
+import java.security.MessageDigest;
5
+import java.util.Formatter;
6
+import java.util.UUID;
7
+
8
+public class Sha1Util {
9
+
10
+    public static String getNonce() {
11
+        String uuid = UUID.randomUUID().toString();
12
+        return uuid;
13
+    }
14
+
15
+    public static String getTimestamp() {
16
+        return String.valueOf(System.currentTimeMillis() / 1000);
17
+    }
18
+
19
+
20
+    private static String byteToHex(final byte[] hash) {
21
+        Formatter formatter = new Formatter();
22
+        for (byte b : hash) {
23
+            formatter.format("%02x", b);
24
+        }
25
+        String result = formatter.toString();
26
+        formatter.close();
27
+        return result;
28
+    }
29
+
30
+    //SHA1
31
+    public static String sha1(String str) {
32
+        if (str == null || str.length() == 0) {
33
+            return null;
34
+        }
35
+        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
36
+
37
+        try {
38
+            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
39
+            mdTemp.update(str.getBytes("UTF-8"));
40
+
41
+            byte[] md = mdTemp.digest();
42
+            int j = md.length;
43
+            char buf[] = new char[j * 2];
44
+            int k = 0;
45
+            for (int i = 0; i < j; i++) {
46
+                byte byte0 = md[i];
47
+                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
48
+                buf[k++] = hexDigits[byte0 & 0xf];
49
+            }
50
+            return new String(buf);
51
+        } catch (Exception e) {
52
+            return null;
53
+        }
54
+    }
55
+
56
+    //SHA-1
57
+    public static String sha_1(String str) {
58
+        try {
59
+            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
60
+            crypt.reset();
61
+            crypt.update(str.getBytes("UTF-8"));
62
+            String signature = byteToHex(crypt.digest());
63
+            return signature;
64
+        } catch (Exception ex) {
65
+            ex.printStackTrace();
66
+        }
67
+        return null;
68
+    }
69
+}

+ 68 - 0
src/main/java/com/dashitech/utils/SpringContextHolder.java

@@ -0,0 +1,68 @@
1
+package com.dashitech.utils;
2
+
3
+import org.springframework.context.ApplicationContext;
4
+import org.springframework.context.ApplicationContextAware;
5
+
6
+import java.lang.annotation.Annotation;
7
+import java.util.ArrayList;
8
+import java.util.List;
9
+import java.util.Map;
10
+
11
+/**
12
+ * 以静态变量保存Spring ApplicationContext, 可在任何地方getBean
13
+ */
14
+public class SpringContextHolder implements ApplicationContextAware {
15
+    private static ApplicationContext applicationContext;
16
+
17
+    /**
18
+     * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
19
+     */
20
+    @Override
21
+    public void setApplicationContext(ApplicationContext applicationContext) {
22
+        SpringContextHolder.applicationContext = applicationContext; // NOSONAR
23
+    }
24
+
25
+    /**
26
+     * 取得存储在静态变量中的ApplicationContext.
27
+     */
28
+    public static ApplicationContext getApplicationContext() {
29
+        checkApplicationContext();
30
+        return applicationContext;
31
+    }
32
+
33
+    public static <T> T getBean(String name) {
34
+        return (T) getApplicationContext().getBean(name);
35
+    }
36
+
37
+    public static <T> T getBean(Class<T> clazz) {
38
+        return (T) getApplicationContext().getBeansOfType(clazz);
39
+    }
40
+
41
+    public static <T> T getBean(Class<T> beanType, Class<? extends Annotation> annotationType) {
42
+        if (annotationType == null) {
43
+            return getBean(beanType);
44
+        }
45
+        Map<String, T> results = getApplicationContext().getBeansOfType(beanType);
46
+        List<T> resultsWithAnnotation = new ArrayList<T>();
47
+        for (Map.Entry<String, T> entry : results.entrySet()) {
48
+            if (getApplicationContext().findAnnotationOnBean(entry.getKey(), annotationType) != null) {
49
+                resultsWithAnnotation.add(entry.getValue());
50
+            }
51
+        }
52
+        if (resultsWithAnnotation.isEmpty()) {
53
+            return null;
54
+        }
55
+        if (resultsWithAnnotation.size() == 1) {
56
+            return resultsWithAnnotation.get(0);
57
+        }
58
+        throw new IllegalStateException("参数错误!未获取到对应Bean");
59
+    }
60
+
61
+
62
+    private static void checkApplicationContext() {
63
+        if (applicationContext == null) {
64
+            throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
65
+        }
66
+    }
67
+
68
+}

+ 31 - 0
src/main/java/com/dashitech/utils/ThreadPoolFactory.java

@@ -0,0 +1,31 @@
1
+package com.dashitech.utils;
2
+
3
+import java.util.concurrent.*;
4
+
5
+/**
6
+ * Created by chi on 2020/8/25.
7
+ */
8
+
9
+public abstract class ThreadPoolFactory {
10
+   // private static final Logger LOG = LoggerFactory.getLogger(ThreadPoolFactory.class);
11
+    private static ThreadPoolExecutor pool;
12
+    private static ScheduledThreadPoolExecutor scheduler;
13
+
14
+    public synchronized static ExecutorService getCachedPool() {
15
+        if (pool == null) {
16
+            pool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
17
+         //   LOG.info("缓存线程池启动完成!初始化线程池大小:" + pool.getPoolSize());
18
+        }
19
+        return pool;
20
+    }
21
+
22
+    public synchronized static ScheduledExecutorService getScheduledPool() {
23
+        if (scheduler == null) {
24
+            scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(35);
25
+           // LOG.info("定时线程池启动完成!初始化线程池大小:" + scheduler.getPoolSize());
26
+        }
27
+        return scheduler;
28
+    }
29
+
30
+}
31
+

File diff suppressed because it is too large
+ 131 - 0
src/main/java/com/dashitech/utils/XmlToJson.java


+ 83 - 0
src/main/java/com/dashitech/utils/XmlToMap.java

@@ -0,0 +1,83 @@
1
+package com.dashitech.utils;
2
+
3
+import org.dom4j.Document;
4
+import org.dom4j.DocumentHelper;
5
+import org.dom4j.Element;
6
+
7
+import java.util.*;
8
+
9
+/**
10
+ * Created by xuweihua on 2021/3/29.
11
+ */
12
+public class XmlToMap {
13
+    public static Map<String, Object> Dom2Map(String xmlStr){
14
+        Map<String, Object> map = new HashMap<String, Object>();
15
+        try{
16
+            Document doc= DocumentHelper.parseText(xmlStr);
17
+            if(doc == null)
18
+                return null;
19
+            Element root = doc.getRootElement();
20
+            for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
21
+                Element e = (Element) iterator.next();
22
+                //System.out.println(e.getName());
23
+                List list = e.elements();
24
+                if(list.size() > 0){
25
+                    map.put(e.getName(), Dom2Map(e));
26
+                }else
27
+                    map.put(e.getName(), e.getText());
28
+            }
29
+            return map;
30
+        }catch (Exception e){
31
+            e.printStackTrace();
32
+        }
33
+        return null;
34
+    }
35
+
36
+
37
+    public static Map Dom2Map(Element e){
38
+        Map map = new HashMap();
39
+        List list = e.elements();
40
+        if(list.size() > 0){
41
+            for (int i = 0;i < list.size(); i++) {
42
+                Element iter = (Element) list.get(i);
43
+                List mapList = new ArrayList();
44
+
45
+                if(iter.elements().size() > 0){
46
+                    Map m = Dom2Map(iter);
47
+                    if(map.get(iter.getName()) != null){
48
+                        Object obj = map.get(iter.getName());
49
+                        if(!obj.getClass().getName().equals("java.util.ArrayList")){
50
+                            mapList = new ArrayList();
51
+                            mapList.add(obj);
52
+                            mapList.add(m);
53
+                        }
54
+                        if(obj.getClass().getName().equals("java.util.ArrayList")){
55
+                            mapList = (List) obj;
56
+                            mapList.add(m);
57
+                        }
58
+                        map.put(iter.getName(), mapList);
59
+                    }else
60
+                        map.put(iter.getName(), m);
61
+                }
62
+                else{
63
+                    if(map.get(iter.getName()) != null){
64
+                        Object obj = map.get(iter.getName());
65
+                        if(!obj.getClass().getName().equals("java.util.ArrayList")){
66
+                            mapList = new ArrayList();
67
+                            mapList.add(obj);
68
+                            mapList.add(iter.getText());
69
+                        }
70
+                        if(obj.getClass().getName().equals("java.util.ArrayList")){
71
+                            mapList = (List) obj;
72
+                            mapList.add(iter.getText());
73
+                        }
74
+                        map.put(iter.getName(), mapList);
75
+                    }else
76
+                        map.put(iter.getName(), iter.getText());
77
+                }
78
+            }
79
+        }else
80
+            map.put(e.getName(), e.getText());
81
+        return map;
82
+    }
83
+}

+ 32 - 0
src/main/resources/application-context.xml

@@ -0,0 +1,32 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<beans xmlns="http://www.springframework.org/schema/beans"
3
+	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
4
+	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
5
+	xsi:schemaLocation="http://www.springframework.org/schema/beans
6
+						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7
+						http://www.springframework.org/schema/mvc
8
+						http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
9
+						http://www.springframework.org/schema/aop 
10
+						http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
11
+						http://www.springframework.org/schema/context
12
+						http://www.springframework.org/schema/context/spring-context-3.0.xsd">
13
+
14
+
15
+	<!-- 初始化静态资源类 -->
16
+	<bean id="applicationProperties"
17
+		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
18
+		<property name="ignoreResourceNotFound" value="true" />
19
+		<property name="locations">
20
+			<list>
21
+				<value>classpath:application.properties</value>
22
+				<value>classpath:application-custom.properties</value>
23
+			</list>
24
+		</property>
25
+	</bean>
26
+
27
+	<bean class="com.dashitech.utils.PropertiesUtil" lazy-init="false">
28
+		<property name="properties" ref="applicationProperties" />
29
+	</bean>
30
+
31
+	<bean class="com.dashitech.utils.SpringContextHolder" lazy-init="false" />
32
+</beans>

+ 1 - 0
src/main/resources/application-custom.properties

@@ -0,0 +1 @@
1
+custom.redis.expire=60

+ 55 - 0
src/main/resources/application.properties

@@ -0,0 +1,55 @@
1
+
2
+mysql2.spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
3
+mysql2.spring.datasource.driver-class-name=com.mysql.jdbc.Driver
4
+#mysql2.spring.datasource.url=jdbc:mysql://172.16.100.186:3306/hsms2?autoReconnect=true&useUnicode=true&characterEncoding=utf8
5
+#mysql2.spring.datasource.url=jdbc:mysql://192.168.3.108:3306/hsms2_0622?autoReconnect=true&useUnicode=true&characterEncoding=utf8
6
+mysql2.spring.datasource.url=jdbc:mysql://192.168.3.108:3306/hsms_nanjing?autoReconnect=true&useUnicode=true&characterEncoding=utf8
7
+mysql2.spring.datasource.username=root
8
+mysql2.spring.datasource.password=100100
9
+mysql2.spring.datasource.initialSize=5
10
+mysql2.spring.datasource.minIdle=1
11
+mysql2.spring.datasource.maxActive=150
12
+mysql2.spring.datasource.maxWait=60000
13
+mysql2.spring.datasource.timeBetweenEvictionRunsMillis=60000
14
+mysql2.spring.datasource.minEvictableIdleTimeMillis=300000
15
+mysql2.spring.datasource.validationQuery=SELECT 'x'
16
+mysql2.spring.datasource.testWhileIdle=true
17
+mysql2.spring.datasource.testOnBorrow=true
18
+mysql2.spring.datasource.testOnReturn=true
19
+
20
+mysql3.spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
21
+mysql3.spring.datasource.driver-class-name=com.mysql.jdbc.Driver
22
+#mysql3.spring.datasource.url=jdbc:mysql://172.16.100.186:3306/hsms2?autoReconnect=true&useUnicode=true&characterEncoding=utf8
23
+#mysql3.spring.datasource.url=jdbc:mysql://192.168.3.108:3306/hsms2_0622?autoReconnect=true&useUnicode=true&characterEncoding=utf8
24
+mysql3.spring.datasource.url=jdbc:mysql://192.168.3.108:3306/md2_nanjing?autoReconnect=true&useUnicode=true&characterEncoding=utf8
25
+mysql3.spring.datasource.username=root
26
+mysql3.spring.datasource.password=100100
27
+mysql3.spring.datasource.initialSize=5
28
+mysql3.spring.datasource.minIdle=1
29
+mysql3.spring.datasource.maxActive=150
30
+mysql3.spring.datasource.maxWait=60000
31
+mysql3.spring.datasource.timeBetweenEvictionRunsMillis=60000
32
+mysql3.spring.datasource.minEvictableIdleTimeMillis=300000
33
+mysql3.spring.datasource.validationQuery=SELECT 'x'
34
+mysql3.spring.datasource.testWhileIdle=true
35
+mysql3.spring.datasource.testOnBorrow=true
36
+mysql3.spring.datasource.testOnReturn=true
37
+
38
+
39
+
40
+spring.redis.host=localhost
41
+#spring.redis.host=172.16.100.176
42
+spring.redis.port=6379
43
+spring.redis.password=Redis@#6379pwD
44
+spring.redis.pool.max-total=100
45
+spring.redis.pool.max-idle=20
46
+spring.redis.pool.max-wait-millis=10000
47
+spring.profiles.active=custom
48
+spring.redis.topic=hsms-data-service
49
+
50
+server.port=29999
51
+spring.jps.showsql=true
52
+server.tomcat.compression=on
53
+
54
+spring.jackson.parser.allow-numeric-leading-zeros=true
55
+

+ 22 - 0
src/main/resources/banner.txt

@@ -0,0 +1,22 @@
1
+////////////////////////////////////////////////////////////////////
2
+//                          _ooOoo_                               //
3
+//                         o8888888o                              //
4
+//                         88" . "88                              //
5
+//                         (| ^_^ |)                              //
6
+//                         O\  =  /O                              //
7
+//                      ____/`---'\____                           //
8
+//                    .'  \\|     |//  `.                         //
9
+//                   /  \\|||  :  |||//  \                        //
10
+//                  /  _||||| -卍-|||||-  \                       //
11
+//                  |   | \\\  -  /// |   |                       //
12
+//                  | \_|  ''\---/''  |   |                       //
13
+//                  \  .-\__  `-`  ___/-. /                       //
14
+//                ___`. .'  /--.--\  `. . ___                     //
15
+//              ."" '<  `.___\_<|>_/___.'  >'"".                  //
16
+//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //
17
+//            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //
18
+//      ========`-.____`-.___\_____/___.-`____.-'========         //
19
+//                           `=---='                              //
20
+//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
21
+//          佛祖保佑   永不宕机   永无BUG  大势雄起               //
22
+////////////////////////////////////////////////////////////////////

+ 5 - 0
src/main/resources/log4j.properties

@@ -0,0 +1,5 @@
1
+log4j.rootLogger=WARN,ERROR
2
+
3
+log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
4
+log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
5
+log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c - %m%n

+ 5 - 0
src/main/resources/start.bat

@@ -0,0 +1,5 @@
1
+echo "start ing"
2
+
3
+java -Xmx512m -XX:MaxPermSize=256m -jar C:/Users/Administrator/Desktop/hsmsV1-DataService-1.0.0.jar --server.port=29999 &
4
+
5
+echo "start end"

+ 15 - 0
src/main/resources/start.sh

@@ -0,0 +1,15 @@
1
+#!/bin/bash
2
+
3
+HOME=`pwd`
4
+NAME=hsmsV1-DataService
5
+LOG=$HOME/logs/itsm.log
6
+
7
+echo "service $NAME start"
8
+echo ""
9
+
10
+
11
+
12
+nohup java -server -Xms256m -Djava.security.egd=file:/dev/./urandom -jar /home/itsm/itsm_v2/hsmsV1-DataService/HSMSV1-DataService-1.0.0.jar --server.port=9999 > $LOG 2>&1 &
13
+
14
+echo ""
15
+echo "service $NAME completed"

+ 20 - 0
src/main/resources/startCollect.sh

@@ -0,0 +1,20 @@
1
+#!/bin/bash
2
+
3
+NAME=hsmsV1-DataService
4
+
5
+echo "service $NAME start"
6
+echo ""
7
+
8
+HOME=`pwd`
9
+LOG=$HOME/logs/itsm.log
10
+CONFS=$HOME/conf
11
+CLASSES=$HOME/classes
12
+LIBS=$HOME/lib
13
+JARS=`ls $LIBS|grep .jar|awk '{print "'$LIBS'/"$0}'|tr "\n" ":"`
14
+JAVA_OPTS=" -server -Xms10g -Xmx20g -XX:PermSize=2g -XX:SurvivorRatio=2 -XX:+UseParallelGC "
15
+CLASS_PATH=$CONFS:$CLASSES:$JARS:$NAME
16
+
17
+nohup java $JAVA_OPTS -classpath $CLASS_PATH com.dashitech.Application > $LOG 2>&1 &
18
+
19
+echo ""
20
+echo "service $NAME completed"

+ 26 - 0
src/main/webapp/WEB-INF/web.xml

@@ -0,0 +1,26 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
3
+        "http://java.sun.com/dtd/web-app_2_3.dtd">
4
+<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
5
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6
+         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
7
+  <display-name></display-name>
8
+
9
+    <servlet>
10
+        <servlet-name>AtmosphereServlet</servlet-name>
11
+        <servlet-class>org.atmosphere.cpr.AtmosphereServlet</servlet-class>
12
+        <init-param>
13
+            <param-name>org.atmosphere.cpr.packages</param-name>
14
+            <param-value>com.dashitech.callcenter.webSocket.service</param-value>
15
+        </init-param>
16
+        <load-on-startup>0</load-on-startup>
17
+    </servlet>
18
+
19
+
20
+    <servlet-mapping>
21
+        <servlet-name>AtmosphereServlet</servlet-name>
22
+        <url-pattern>/webSocket/*</url-pattern>
23
+    </servlet-mapping>
24
+
25
+
26
+</web-app>

+ 38 - 0
src/test/java/com/dashitech/mc/AppTest.java

@@ -0,0 +1,38 @@
1
+package com.dashitech.mc;
2
+
3
+import junit.framework.Test;
4
+import junit.framework.TestCase;
5
+import junit.framework.TestSuite;
6
+
7
+/**
8
+ * Unit test for simple App.
9
+ */
10
+public class AppTest 
11
+    extends TestCase
12
+{
13
+    /**
14
+     * Create the test case
15
+     *
16
+     * @param testName name of the test case
17
+     */
18
+    public AppTest( String testName )
19
+    {
20
+        super( testName );
21
+    }
22
+
23
+    /**
24
+     * @return the suite of tests being tested
25
+     */
26
+    public static Test suite()
27
+    {
28
+        return new TestSuite( AppTest.class );
29
+    }
30
+
31
+    /**
32
+     * Rigourous Test :-)
33
+     */
34
+    public void testApp()
35
+    {
36
+        assertTrue( true );
37
+    }
38
+}