Browse Source

Merge branch 'master' of http://git.ycjcjy.com/fuxingfan/SpringProject

weiximei 6 years ago
parent
commit
1ca4228eb2
23 changed files with 2513 additions and 10 deletions
  1. 104
    0
      SmartCommunity/SmartCommunityV1/community-common/pom.xml
  2. 49
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/FastJsonSerializer.java
  3. 35
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisConfiguration.java
  4. 47
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisJsonSerializer.java
  5. 47
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisObjectSerializer.java
  6. 30
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisSerializer.java
  7. 317
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisTemplate.java
  8. 17
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/SerializationFailedException.java
  9. 585
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/SingleRedisTemplate.java
  10. 115
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/BeanTools.java
  11. 88
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/CommonUtils.java
  12. 142
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/CookieUtil.java
  13. 139
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/DESUtils.java
  14. 277
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/DateUtils.java
  15. 120
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/EnumUtils.java
  16. 148
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/HttpClientUtils.java
  17. 51
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/MD5Utils.java
  18. 113
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/QRCodeGeneratorUtils.java
  19. 72
    0
      SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/StringConverter.java
  20. 6
    5
      SmartCommunity/SmartCommunityV1/eureka-client1/pom.xml
  21. 5
    0
      SmartCommunity/SmartCommunityV1/eureka-client1/src/main/java/com/example/demo/controller/TestController.java
  22. 2
    1
      SmartCommunity/SmartCommunityV1/pom.xml
  23. 4
    4
      SmartCommunity/SmartCommunityV1/user-server/pom.xml

+ 104
- 0
SmartCommunity/SmartCommunityV1/community-common/pom.xml View File

@@ -0,0 +1,104 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<project xmlns="http://maven.apache.org/POM/4.0.0"
3
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5
+    <parent>
6
+        <artifactId>spring-cloud</artifactId>
7
+        <groupId>com.example</groupId>
8
+        <version>0.0.1</version>
9
+    </parent>
10
+    <modelVersion>4.0.0</modelVersion>
11
+
12
+    <artifactId>community-common</artifactId>
13
+    <packaging>jar</packaging>
14
+    <name>community-common</name>
15
+
16
+    <properties>
17
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
18
+        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
19
+        <java.version>1.8</java.version>
20
+        <spring-cloud.version>Finchley.SR1</spring-cloud.version>
21
+    </properties>
22
+
23
+    <dependencies>
24
+        <dependency>
25
+            <groupId>com.alibaba</groupId>
26
+            <artifactId>fastjson</artifactId>
27
+            <version>1.2.4</version>
28
+        </dependency>
29
+        <dependency>
30
+            <groupId>redis.clients</groupId>
31
+            <artifactId>jedis</artifactId>
32
+            <version>2.9.0</version>
33
+        </dependency>
34
+        <dependency>
35
+            <groupId>org.slf4j</groupId>
36
+            <artifactId>slf4j-api</artifactId>
37
+            <version>${slf4j.version}</version>
38
+        </dependency>
39
+        <dependency>
40
+            <groupId>com.fasterxml.jackson.core</groupId>
41
+            <artifactId>jackson-core</artifactId>
42
+            <version>${jackson.version}</version>
43
+        </dependency>
44
+        <dependency>
45
+            <groupId>com.fasterxml.jackson.core</groupId>
46
+            <artifactId>jackson-databind</artifactId>
47
+            <version>${jackson.version}</version>
48
+        </dependency>
49
+        <dependency>
50
+            <groupId>org.jodd</groupId>
51
+            <artifactId>jodd-bean</artifactId>
52
+            <version>3.7.1</version>
53
+        </dependency>
54
+        <dependency>
55
+            <groupId>commons-collections</groupId>
56
+            <artifactId>commons-collections</artifactId>
57
+            <version>3.2.1</version>
58
+        </dependency>
59
+        <dependency>
60
+            <groupId>commons-httpclient</groupId>
61
+            <artifactId>commons-httpclient</artifactId>
62
+            <version>3.1</version>
63
+        </dependency>
64
+        <dependency>
65
+            <groupId>com.google.zxing</groupId>
66
+            <artifactId>core</artifactId>
67
+            <version>3.2.1</version>
68
+        </dependency>
69
+        <dependency>
70
+            <groupId>com.google.zxing</groupId>
71
+            <artifactId>javase</artifactId>
72
+            <version>3.2.1</version>
73
+        </dependency>
74
+        <dependency>
75
+            <groupId>org.springframework</groupId>
76
+            <artifactId>spring-web</artifactId>
77
+            <version>${spring.version}</version>
78
+        </dependency>
79
+        <dependency>
80
+            <groupId>com.alibaba</groupId>
81
+            <artifactId>fastjson</artifactId>
82
+            <version>RELEASE</version>
83
+        </dependency>
84
+        <dependency>
85
+            <groupId>org.apache.tomcat.embed</groupId>
86
+            <artifactId>tomcat-embed-core</artifactId>
87
+            <version>8.5.16</version>
88
+        </dependency>
89
+        <dependency>
90
+            <groupId>org.springframework</groupId>
91
+            <artifactId>spring-context</artifactId>
92
+            <version>4.3.16.RELEASE</version>
93
+            <scope>compile</scope>
94
+        </dependency>
95
+    </dependencies>
96
+    <build>
97
+        <plugins>
98
+            <plugin>
99
+                <groupId>org.springframework.boot</groupId>
100
+                <artifactId>spring-boot-maven-plugin</artifactId>
101
+            </plugin>
102
+        </plugins>
103
+    </build>
104
+</project>

+ 49
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/FastJsonSerializer.java View File

@@ -0,0 +1,49 @@
1
+package com.community.commom.redis;
2
+
3
+import com.alibaba.fastjson.JSON;
4
+import org.springframework.stereotype.Component;
5
+
6
+import java.io.Serializable;
7
+import java.nio.charset.Charset;
8
+
9
+/**
10
+ * redis fastjson 序列化工具
11
+ * @author gengxiang
12
+ * @create 2017-09-06 18:04
13
+ *
14
+ **/
15
+@Component
16
+public class FastJsonSerializer implements RedisSerializer {
17
+
18
+
19
+    @Override
20
+    public <T> T deserialize(byte[] source, Class<T> tClass) throws SerializationFailedException {
21
+        try {
22
+            if (source == null){
23
+                return null;
24
+            }
25
+            if (tClass == String.class){
26
+                return tClass.cast(new String(source, Charset.forName("UTF-8")));
27
+            }
28
+
29
+            return JSON.parseObject(source,tClass);
30
+        } catch (Exception e) {
31
+            throw new SerializationFailedException("Deserialize failed:" + e, e);
32
+        }
33
+    }
34
+
35
+    @Override
36
+    public byte[] serialize(Object object) throws SerializationFailedException {
37
+        if (!(object instanceof Serializable)) {
38
+            throw new IllegalArgumentException("Serializer requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]");
39
+        }
40
+        try {
41
+            if (object instanceof String){
42
+                return object.toString().getBytes("UTF-8");
43
+            }
44
+            return JSON.toJSONString(object).getBytes("UTF-8");
45
+        } catch (Exception e) {
46
+            throw new SerializationFailedException("Serialize failed:" + object.getClass(), e);
47
+        }
48
+    }
49
+}

+ 35
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisConfiguration.java View File

@@ -0,0 +1,35 @@
1
+package com.community.commom.redis;
2
+
3
+import org.springframework.beans.factory.annotation.Autowired;
4
+import org.springframework.beans.factory.annotation.Qualifier;
5
+import org.springframework.beans.factory.annotation.Value;
6
+import org.springframework.context.annotation.Bean;
7
+import org.springframework.context.annotation.Configuration;
8
+import redis.clients.jedis.JedisPool;
9
+import redis.clients.jedis.JedisPoolConfig;
10
+
11
+/**
12
+ * redis configuration
13
+ * @author gengxiang
14
+ * @create 2017-09-25 10:25
15
+ **/
16
+@Configuration
17
+public class RedisConfiguration {
18
+
19
+    @Bean(name= "jedis.pool")
20
+    @Autowired
21
+    public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,
22
+                               @Value("${jedis.pool.host}")String host,
23
+                               @Value("${jedis.pool.port}")int port) {
24
+        return new JedisPool(config, host, port);
25
+    }
26
+
27
+    @Bean(name= "jedis.pool.config")
28
+    public JedisPoolConfig jedisPoolConfig (@Value("${jedis.pool.config.maxTotal}")int maxTotal,
29
+                                            @Value("${jedis.pool.config.maxIdle}")int maxIdle) {
30
+        JedisPoolConfig config = new JedisPoolConfig();
31
+        config.setMaxTotal(maxTotal);
32
+        config.setMaxIdle(maxIdle);
33
+        return config;
34
+    }
35
+}

+ 47
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisJsonSerializer.java View File

@@ -0,0 +1,47 @@
1
+package com.community.commom.redis;
2
+
3
+import com.fasterxml.jackson.annotation.JsonInclude;
4
+import com.fasterxml.jackson.databind.ObjectMapper;
5
+
6
+import java.io.Serializable;
7
+
8
+/**
9
+ * redis json 序列化工具
10
+ * @author gengxiang
11
+ * @create 2017-09-06 18:04
12
+ *
13
+ **/
14
+public class RedisJsonSerializer implements RedisSerializer {
15
+    private static final ObjectMapper mapper = new ObjectMapper();
16
+
17
+    static {
18
+        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
19
+    }
20
+
21
+    @Override
22
+    public <T> T deserialize(byte[] source, Class<T> tClass) throws SerializationFailedException {
23
+        try {
24
+            if (source == null)
25
+                return null;
26
+            if (tClass == String.class)
27
+                return tClass.cast(new String(source));
28
+            return mapper.readValue(source, tClass);
29
+        } catch (Exception e) {
30
+            throw new SerializationFailedException("Deserialize failed:" + e, e);
31
+        }
32
+    }
33
+
34
+    @Override
35
+    public byte[] serialize(Object object) throws SerializationFailedException {
36
+        if (!(object instanceof Serializable)) {
37
+            throw new IllegalArgumentException("Serializer requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]");
38
+        }
39
+        try {
40
+            if (object instanceof String)
41
+                return object.toString().getBytes();
42
+            return mapper.writeValueAsString(object).getBytes("UTF-8");
43
+        } catch (Exception e) {
44
+            throw new SerializationFailedException("Serialize failed:" + object.getClass(), e);
45
+        }
46
+    }
47
+}

+ 47
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisObjectSerializer.java View File

@@ -0,0 +1,47 @@
1
+package com.community.commom.redis;
2
+
3
+import java.io.ByteArrayInputStream;
4
+import java.io.ByteArrayOutputStream;
5
+import java.io.ObjectInputStream;
6
+import java.io.ObjectOutputStream;
7
+import java.io.Serializable;
8
+
9
+/**
10
+ * redis json 序列化工具
11
+ * @author gengxiang
12
+ * @create 2017-09-06 18:04
13
+ *
14
+ **/
15
+public class RedisObjectSerializer implements RedisSerializer {
16
+
17
+    @Override
18
+    public <T> T deserialize(byte[] source, Class<T> tClass) throws SerializationFailedException {
19
+        if (source == null)
20
+            return null;
21
+        if (tClass == String.class)
22
+            return tClass.cast(new String(source));
23
+        try (ByteArrayInputStream byteStream = new ByteArrayInputStream(source);
24
+             ObjectInputStream objectInputStream = new ObjectInputStream(byteStream)) {
25
+            return tClass.cast(objectInputStream.readObject());
26
+        } catch (Exception e) {
27
+            throw new SerializationFailedException("Deserialize failed:" + e, e);
28
+        }
29
+    }
30
+
31
+    @Override
32
+    public byte[] serialize(Object object) throws SerializationFailedException {
33
+        if (!(object instanceof Serializable)) {
34
+            throw new IllegalArgumentException("Serializer requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]");
35
+        }
36
+        if (object instanceof String)
37
+            return object.toString().getBytes();
38
+        try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
39
+             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream)) {
40
+            objectOutputStream.writeObject(object);
41
+            objectOutputStream.flush();
42
+            return byteStream.toByteArray();
43
+        } catch (Exception e) {
44
+            throw new SerializationFailedException("Serialize failed:" + object.getClass(), e);
45
+        }
46
+    }
47
+}

+ 30
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisSerializer.java View File

@@ -0,0 +1,30 @@
1
+package com.community.commom.redis;
2
+
3
+/**
4
+ * redis 序列化工具接口
5
+ * @author gengxiang
6
+ * @create 2017-09-06 18:04
7
+ *
8
+ **/
9
+public interface RedisSerializer {
10
+    /**
11
+     * Deserialize
12
+     *
13
+     * @param source serialized data
14
+     * @param tClass generic class type
15
+     * @param <T>    generic class
16
+     * @return object
17
+     * @throws SerializationFailedException
18
+     */
19
+    <T> T deserialize(byte[] source, Class<T> tClass) throws SerializationFailedException;
20
+
21
+    /**
22
+     * Serialize
23
+     *
24
+     * @param object object
25
+     * @return serialized data
26
+     * @throws SerializationFailedException
27
+     */
28
+    byte[] serialize(Object object) throws SerializationFailedException;
29
+
30
+}

+ 317
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/RedisTemplate.java View File

@@ -0,0 +1,317 @@
1
+package com.community.commom.redis;
2
+
3
+
4
+
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import redis.clients.jedis.JedisPool;
7
+
8
+import java.nio.charset.Charset;
9
+import java.util.List;
10
+import java.util.Map;
11
+import java.util.Set;
12
+
13
+/**
14
+ * redis 工具虚类
15
+ * @author gengxiang
16
+ * @create 2017-09-06 18:04
17
+ *
18
+ **/
19
+public abstract class RedisTemplate {
20
+
21
+    final Charset defaultCharset = Charset.forName("UTF8");
22
+
23
+    long maxLockTime = 5000L;
24
+
25
+    long lockRetryTime = 100L;
26
+
27
+    @Autowired
28
+    RedisSerializer serializer;
29
+
30
+    @Autowired
31
+    JedisPool redisPool;
32
+
33
+
34
+    public Charset getDefaultCharset() {
35
+        return defaultCharset;
36
+    }
37
+
38
+    public long getMaxLockTime() {
39
+        return maxLockTime;
40
+    }
41
+
42
+    public void setMaxLockTime(long maxLockTime) {
43
+        this.maxLockTime = maxLockTime;
44
+    }
45
+
46
+    public long getLockRetryTime() {
47
+        return lockRetryTime;
48
+    }
49
+
50
+    public void setLockRetryTime(long lockRetryTime) {
51
+        this.lockRetryTime = lockRetryTime;
52
+    }
53
+
54
+    public RedisSerializer getSerializer() {
55
+        return serializer;
56
+    }
57
+
58
+    public void setSerializer(RedisSerializer serializer) {
59
+        this.serializer = serializer;
60
+    }
61
+
62
+    public JedisPool getRedisPool() {
63
+        return redisPool;
64
+    }
65
+
66
+    public void setRedisPool(JedisPool redisPool) {
67
+        this.redisPool = redisPool;
68
+    }
69
+
70
+    /**
71
+     * Set the value of a key
72
+     *
73
+     * @param key   key
74
+     * @param value value
75
+     * @return result
76
+     */
77
+    public abstract String set(String key, Object value);
78
+
79
+    /**
80
+     * setnx the value of a key
81
+     *
82
+     * @param key   key
83
+     * @param value value
84
+     * @return result
85
+     */
86
+    public abstract Long setnx(String key, Object value);
87
+
88
+    /**
89
+     * set an expire time for a key
90
+     *
91
+     * @param key     key
92
+     * @param seconds expire time
93
+     * @return result
94
+     */
95
+    public abstract Long expire(String key, int seconds);
96
+
97
+    public abstract Long ttl(String key);
98
+
99
+    /**
100
+     * get a String value of a key
101
+     *
102
+     * @param key key
103
+     * @return object
104
+     */
105
+    public abstract String get(String key);
106
+
107
+    /**
108
+     * get an object of a key
109
+     *
110
+     * @param key    key
111
+     * @param tClass the class of object
112
+     * @param <T>    generic type
113
+     * @return object
114
+     */
115
+    public abstract <T> T get(String key, Class<T> tClass);
116
+
117
+    /**
118
+     * delete a value of a key
119
+     *
120
+     * @param key key
121
+     * @return result
122
+     */
123
+    public abstract Long del(String key);
124
+
125
+    /**
126
+     * delete values of keys
127
+     *
128
+     * @param keys keys
129
+     * @return result
130
+     */
131
+    public abstract Long del(String... keys);
132
+
133
+    /**
134
+     * Set the value of a hash field
135
+     *
136
+     * @param key   key
137
+     * @param field hash field
138
+     * @param value value
139
+     * @return result
140
+     */
141
+    public abstract Long hset(String key, String field, Object value);
142
+
143
+    /**
144
+     * Set the values of fields
145
+     *
146
+     * @param key key
147
+     * @param map key:field,value:object
148
+     * @return result
149
+     */
150
+    public abstract <T> String hmset(String key, Map<String, T> map);
151
+
152
+    public abstract <T> Map<String, T> hmget(String key, List<String> fields, Class<T> tClass);
153
+
154
+    /**
155
+     * del the value of a hash field
156
+     *
157
+     * @param key   key
158
+     * @param field hash field
159
+     * @return result
160
+     */
161
+    public abstract Long hdel(String key, String field);
162
+
163
+    /**
164
+     * Set the string value of a hash field
165
+     *
166
+     * @param key    key
167
+     * @param field  hash field
168
+     * @param tClass generics class type
169
+     * @param <T>    generics class
170
+     * @return value
171
+     */
172
+    public abstract <T> T hget(String key, String field, Class<T> tClass);
173
+
174
+
175
+    /**
176
+     * Set the string value of a hash field
177
+     *
178
+     * @param key    key
179
+     * @param tClass generics class type
180
+     * @param <T>    generics class
181
+     * @return value
182
+     */
183
+    public abstract <T> Map<String,T> hgetAll(String key, Class<T> tClass);
184
+
185
+    /**
186
+     * Get all the fields in a hash
187
+     *
188
+     * @param key key
189
+     * @return all the fields set
190
+     */
191
+    public abstract Set<String> hkeys(String key);
192
+
193
+
194
+    /**
195
+     * Get a range of elements from a list
196
+     *
197
+     * @param key    key
198
+     * @param tClass generic class type
199
+     * @param start  start number, the first is 0
200
+     * @param stop   stop number, the last is -1
201
+     * @param <T>    generic class
202
+     * @return list of results
203
+     */
204
+    public abstract <T> List<T> lrange(String key, Class<T> tClass, long start, long stop);
205
+
206
+    /**
207
+     * Get all of elements from a list
208
+     *
209
+     * @param key    key
210
+     * @param tClass generic class type
211
+     * @param <T>    generic class
212
+     * @return list of results
213
+     */
214
+    public abstract <T> List<T> lrange(String key, Class<T> tClass);
215
+
216
+    /**
217
+     * Prepend one or multiple values to a list
218
+     *
219
+     * @param key    key
220
+     * @param values values
221
+     * @return result
222
+     */
223
+    public abstract Long lpush(String key, Object... values);
224
+
225
+    /**
226
+     * Prepend one or multiple values to a list
227
+     *
228
+     * @param key    key
229
+     * @param values values
230
+     * @return result
231
+     */
232
+    public abstract Long lpush(String key, List values);
233
+
234
+    /**
235
+     * Append one or multiple values to a list
236
+     *
237
+     * @param key    key
238
+     * @param values values
239
+     * @return result
240
+     */
241
+    public abstract Long rpush(String key, Object... values);
242
+
243
+    /**
244
+     * Append one or multiple values to a list
245
+     *
246
+     * @param key    key
247
+     * @param values values
248
+     * @return result
249
+     */
250
+    public abstract Long rpush(String key, List values);
251
+
252
+    /**
253
+     * get a lock for key
254
+     *
255
+     * @param key key
256
+     * @return result
257
+     */
258
+    public abstract Boolean getLock(String key);
259
+
260
+    /**
261
+     * release lock
262
+     *
263
+     * @param key key
264
+     */
265
+    public abstract void releaseLock(String key);
266
+
267
+    /**
268
+     * 缓存是否存在
269
+     *
270
+     * @param key 键
271
+     * @return
272
+     */
273
+    public abstract boolean exists(String key);
274
+
275
+    /**
276
+     * 缓存是否存在
277
+     *
278
+     * @param key   键
279
+     * @param field
280
+     * @return
281
+     */
282
+    public abstract boolean hexists(String key, String field);
283
+
284
+    /**
285
+     * 获取hash缓存的个数
286
+     *
287
+     * @param key   键
288
+     * @return
289
+     */
290
+    public abstract Long hlen(String key);
291
+
292
+    /**
293
+     * 计数器递减
294
+     *
295
+     * @param key
296
+     * @return
297
+     */
298
+    public abstract Long decr(String key);
299
+
300
+    /**
301
+     * 计数器递增
302
+     *
303
+     * @param key
304
+     * @return
305
+     */
306
+    public abstract Long incr(String key);
307
+
308
+	/**
309
+	 * map值加
310
+	 * @param key
311
+	 * @param field
312
+	 * @param value
313
+	 * @return
314
+	 */
315
+	public abstract  Long hincrBy(final String key, final String field, final long value);
316
+
317
+}

+ 17
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/SerializationFailedException.java View File

@@ -0,0 +1,17 @@
1
+package com.community.commom.redis;
2
+
3
+/**
4
+ * redis 序列化异常类
5
+ * @author gengxiang
6
+ * @create 2017-09-06 18:04
7
+ *
8
+ **/
9
+public class SerializationFailedException extends RuntimeException {
10
+    public SerializationFailedException(Throwable cause) {
11
+        super(cause);
12
+    }
13
+
14
+    public SerializationFailedException(String message, Throwable cause) {
15
+        super(message, cause);
16
+    }
17
+}

+ 585
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/redis/SingleRedisTemplate.java View File

@@ -0,0 +1,585 @@
1
+package com.community.commom.redis;
2
+
3
+import org.slf4j.Logger;
4
+import org.slf4j.LoggerFactory;
5
+import org.springframework.stereotype.Component;
6
+import redis.clients.jedis.Jedis;
7
+
8
+import java.util.ArrayList;
9
+import java.util.Arrays;
10
+import java.util.HashMap;
11
+import java.util.List;
12
+import java.util.Map;
13
+import java.util.Set;
14
+
15
+/**
16
+ * 单机redis 操作工具
17
+ *
18
+ * @author gengxiang
19
+ * @create 2017-09-06 18:04
20
+ **/
21
+@Component
22
+public class SingleRedisTemplate extends RedisTemplate {
23
+    private Logger log = LoggerFactory.getLogger(RedisTemplate.class);
24
+
25
+    /**
26
+     * 从jedis连接池中获取获取jedis对象
27
+     */
28
+    public Jedis getJedis() {
29
+        return redisPool.getResource();
30
+    }
31
+
32
+    /**
33
+     * 回收jedis
34
+     */
35
+    public void returnJedis(Jedis jedis) {
36
+        if (jedis != null)
37
+            jedis.close();
38
+    }
39
+
40
+    @Override
41
+    public String set(String key, Object value) {
42
+        String result = null;
43
+        Jedis jedis = null;
44
+        try {
45
+            jedis = getJedis();
46
+            result = jedis.set(key.getBytes(defaultCharset), serializer.serialize(value));
47
+        } catch (Exception e) {
48
+            log.error("redis set error, key:" + key, e);
49
+        } finally {
50
+            returnJedis(jedis);
51
+        }
52
+        return result;
53
+    }
54
+
55
+    @Override
56
+    public Long setnx(String key, Object value) {
57
+        Long result = null;
58
+        Jedis jedis = null;
59
+        try {
60
+            jedis = getJedis();
61
+            result = jedis.setnx(key.getBytes(defaultCharset), serializer.serialize(value));
62
+        } catch (Exception e) {
63
+            log.error("redis setnx error, key:" + key, e);
64
+        } finally {
65
+            returnJedis(jedis);
66
+        }
67
+        return result;
68
+    }
69
+
70
+    @Override
71
+    public Long expire(String key, int seconds) {
72
+        Long result = null;
73
+        Jedis jedis = null;
74
+        try {
75
+            jedis = getJedis();
76
+            result = jedis.expire(key.getBytes(defaultCharset), seconds);
77
+        } catch (Exception e) {
78
+            log.error("redis expire error, key:" + key, e);
79
+        } finally {
80
+            returnJedis(jedis);
81
+        }
82
+        return result;
83
+    }
84
+
85
+    @Override
86
+    public Long ttl(String key) {
87
+        Long result = null;
88
+        Jedis jedis = null;
89
+        try {
90
+            jedis = getJedis();
91
+            result = jedis.ttl(key.getBytes(defaultCharset));
92
+        } catch (Exception e) {
93
+            log.error("redis ttl error, key:" + key, e);
94
+        } finally {
95
+            returnJedis(jedis);
96
+        }
97
+        return result;
98
+    }
99
+
100
+    @Override
101
+    public String get(String key) {
102
+        return get(key, String.class);
103
+    }
104
+
105
+    @Override
106
+    public <T> T get(String key, Class<T> tClass) {
107
+        byte[] result = null;
108
+        Jedis jedis = null;
109
+        try {
110
+            jedis = getJedis();
111
+            result = jedis.get(key.getBytes(defaultCharset));
112
+        } catch (Exception e) {
113
+            log.error("redis set error, key:" + key, e);
114
+        } finally {
115
+            returnJedis(jedis);
116
+        }
117
+        return serializer.deserialize(result, tClass);
118
+    }
119
+
120
+    @Override
121
+    public Long del(String key) {
122
+        Long result = null;
123
+        Jedis jedis = null;
124
+        try {
125
+            jedis = getJedis();
126
+            result = jedis.del(key.getBytes(defaultCharset));
127
+        } catch (Exception e) {
128
+            log.error("redis del error, key:" + key);
129
+        } finally {
130
+            returnJedis(jedis);
131
+        }
132
+        return result;
133
+    }
134
+
135
+    @Override
136
+    public Long del(String... keys) {
137
+        Long result = 0L;
138
+        Jedis jedis = null;
139
+        try {
140
+            jedis = getJedis();
141
+            for (String key : keys)
142
+                result += jedis.del(key.getBytes(defaultCharset));
143
+        } catch (Exception e) {
144
+            log.error("redis del error, key:" + Arrays.toString(keys));
145
+        } finally {
146
+            returnJedis(jedis);
147
+        }
148
+        return result;
149
+    }
150
+
151
+    /**
152
+     * Get the value of a hash field
153
+     *
154
+     * @param key   key
155
+     * @param field hash field
156
+     * @param value value
157
+     * @return result
158
+     */
159
+    @Override
160
+    public Long hset(String key, String field, Object value) {
161
+        Long result = null;
162
+        Jedis jedis = null;
163
+        try {
164
+            jedis = getJedis();
165
+            result = jedis.hset(key.getBytes(defaultCharset), field.getBytes(defaultCharset), serializer.serialize(value));
166
+        } catch (Exception e) {
167
+            log.error("redis hset error, key:" + key + ", field:" + field, e);
168
+        } finally {
169
+            returnJedis(jedis);
170
+        }
171
+        return result;
172
+    }
173
+
174
+    @Override
175
+    public <T> String hmset(String key, Map<String, T> map) {
176
+        String result = null;
177
+        Jedis jedis = null;
178
+        try {
179
+            jedis = getJedis();
180
+            Map<byte[], byte[]> data = new HashMap<byte[], byte[]>();
181
+            for (Map.Entry<String, T> entry : map.entrySet())
182
+                data.put(entry.getKey().getBytes(defaultCharset), serializer.serialize(entry.getValue()));
183
+            result = jedis.hmset(key.getBytes(defaultCharset), data);
184
+        } catch (Exception e) {
185
+            log.error("redis hmset error, key:" + key, e);
186
+        } finally {
187
+            returnJedis(jedis);
188
+        }
189
+        return result;
190
+    }
191
+
192
+    @Override
193
+    public <T> Map<String, T> hmget(String key, List<String> fields, Class<T> tClass) {
194
+        Map<String, T> result = new HashMap<>();
195
+        Jedis jedis = null;
196
+        try {
197
+            jedis = getJedis();
198
+            List<byte[]> byteList = new ArrayList<>(fields.size());
199
+            for (String field : fields) {
200
+                byte[] s = field.getBytes(defaultCharset);
201
+                byteList.add(s);
202
+            }
203
+            List<byte[]> strings = jedis.hmget(key.getBytes(defaultCharset), byteList.toArray(new byte[fields.size()][]));
204
+            for (int i = 0; i < fields.size(); i++) {
205
+                result.put(fields.get(i), serializer.deserialize(strings.get(i), tClass));
206
+            }
207
+        } catch (Exception e) {
208
+            log.error("redis hmset error, key:" + key, e);
209
+        } finally {
210
+            returnJedis(jedis);
211
+        }
212
+        return result;
213
+    }
214
+
215
+    /**
216
+     * del the value of a hash field
217
+     *
218
+     * @param key   key
219
+     * @param field hash field
220
+     * @return result
221
+     */
222
+    @Override
223
+    public Long hdel(String key, String field) {
224
+        Long result = null;
225
+        Jedis jedis = null;
226
+        try {
227
+            jedis = getJedis();
228
+            result = jedis.hdel(key.getBytes(defaultCharset), field.getBytes(defaultCharset));
229
+        } catch (Exception e) {
230
+            log.error("redis hset error, key:" + key + ", field:" + field, e);
231
+        } finally {
232
+            returnJedis(jedis);
233
+        }
234
+        return result;
235
+    }
236
+
237
+    /**
238
+     * Set the string value of a hash field
239
+     *
240
+     * @param key    key
241
+     * @param field  hash field
242
+     * @param tClass generics class type
243
+     * @param <T>    generics class
244
+     * @return value
245
+     */
246
+    @Override
247
+    public <T> T hget(String key, String field, Class<T> tClass) {
248
+        byte[] result = null;
249
+        Jedis jedis = null;
250
+        try {
251
+            jedis = getJedis();
252
+            result = jedis.hget(key.getBytes(defaultCharset), field.getBytes(defaultCharset));
253
+        } catch (Exception e) {
254
+            log.error("redis hget error, key:" + key + ", field:" + field, e);
255
+        } finally {
256
+            returnJedis(jedis);
257
+        }
258
+        return serializer.deserialize(result, tClass);
259
+    }
260
+
261
+    @Override
262
+    public <T> Map<String, T> hgetAll(String key, Class<T> tClass) {
263
+        Map<String, T> result = new HashMap<String, T>();
264
+        Jedis jedis = null;
265
+        try {
266
+            jedis = getJedis();
267
+            Map<byte[], byte[]> map = jedis.hgetAll(key.getBytes(defaultCharset));
268
+            for (Map.Entry<byte[], byte[]> entry : map.entrySet()) {
269
+                result.put(new String(entry.getKey(), defaultCharset), serializer.deserialize(entry.getValue(), tClass));
270
+            }
271
+        } catch (Exception e) {
272
+            log.error("redis hGetAll error, key:" + key, e);
273
+        } finally {
274
+            returnJedis(jedis);
275
+        }
276
+        return result;
277
+    }
278
+
279
+    /**
280
+     * Get all the fields in a hash
281
+     *
282
+     * @param key key
283
+     * @return all the fields set
284
+     */
285
+    @Override
286
+    public Set<String> hkeys(String key) {
287
+        Set<String> result = null;
288
+        Jedis jedis = null;
289
+        try {
290
+            jedis = getJedis();
291
+            result = jedis.hkeys(key);
292
+        } catch (Exception e) {
293
+            log.error("redis hkeys error, key:" + key, e);
294
+        } finally {
295
+            returnJedis(jedis);
296
+        }
297
+        return result;
298
+    }
299
+
300
+    /**
301
+     * Get a range of elements from a list
302
+     *
303
+     * @param key    key
304
+     * @param tClass generic class type
305
+     * @param start  start number, the first is 0
306
+     * @param stop   stop number, the last is -1
307
+     * @param <T>    generic class
308
+     * @return list of results
309
+     */
310
+    @Override
311
+    public <T> List<T> lrange(String key, Class<T> tClass, long start, long stop) {
312
+        List<T> result = new ArrayList<>();
313
+        Jedis jedis = null;
314
+        try {
315
+            jedis = getJedis();
316
+            List<byte[]> list = jedis.lrange(key.getBytes(defaultCharset), start, stop);
317
+            for (byte[] bytes : list) {
318
+                result.add(serializer.deserialize(bytes, tClass));
319
+            }
320
+        } catch (Exception e) {
321
+            log.error("redis lrange error key:" + key, e);
322
+        } finally {
323
+            returnJedis(jedis);
324
+        }
325
+        return result;
326
+    }
327
+
328
+    /**
329
+     * Get all of elements from a list
330
+     *
331
+     * @param key    key
332
+     * @param tClass generic class type
333
+     * @param <T>    generic class
334
+     * @return list of results
335
+     */
336
+    @Override
337
+    public <T> List<T> lrange(String key, Class<T> tClass) {
338
+        return lrange(key, tClass, 0L, -1L);
339
+    }
340
+
341
+    /**
342
+     * Prepend one or multiple values to a list
343
+     *
344
+     * @param key    key
345
+     * @param values values
346
+     * @return result
347
+     */
348
+    @Override
349
+    public Long lpush(String key, Object... values) {
350
+        Long result = null;
351
+        Jedis jedis = null;
352
+        try {
353
+            jedis = getJedis();
354
+            List<byte[]> list = new ArrayList<>();
355
+            for (Object o : values) {
356
+                list.add(serializer.serialize(o));
357
+            }
358
+            result = jedis.lpush(key.getBytes(defaultCharset), list.toArray(new byte[list.size()][]));
359
+        } catch (Exception e) {
360
+            log.error("redis lpush error key:" + key, e);
361
+        } finally {
362
+            returnJedis(jedis);
363
+        }
364
+        return result;
365
+    }
366
+
367
+    /**
368
+     * Prepend one or multiple values to a list
369
+     *
370
+     * @param key    key
371
+     * @param values values
372
+     * @return result
373
+     */
374
+    @Override
375
+    public Long lpush(String key, List values) {
376
+        return lpush(key, values.toArray());
377
+    }
378
+
379
+    /**
380
+     * Append one or multiple values to a list
381
+     *
382
+     * @param key    key
383
+     * @param values values
384
+     * @return result
385
+     */
386
+    @Override
387
+    public Long rpush(String key, Object... values) {
388
+        Long result = null;
389
+        Jedis jedis = null;
390
+        try {
391
+            jedis = getJedis();
392
+            List<byte[]> list = new ArrayList<>();
393
+            for (Object o : values) {
394
+                list.add(serializer.serialize(o));
395
+            }
396
+            result = jedis.rpush(key.getBytes(defaultCharset), list.toArray(new byte[list.size()][]));
397
+        } catch (Exception e) {
398
+            log.error("redis rpush error key:" + key, e);
399
+        } finally {
400
+            returnJedis(jedis);
401
+        }
402
+        return result;
403
+    }
404
+
405
+    /**
406
+     * Append one or multiple values to a list
407
+     *
408
+     * @param key    key
409
+     * @param values values
410
+     * @return result
411
+     */
412
+    @Override
413
+    public Long rpush(String key, List values) {
414
+        return rpush(key, values.toArray());
415
+    }
416
+
417
+    /**
418
+     * redis setnx实现分布式锁
419
+     *
420
+     * @param key key
421
+     * @return true:获取到锁, false: 未获取到锁
422
+     */
423
+    @Override
424
+    public Boolean getLock(String key) {
425
+        Long result;
426
+        Jedis jedis = null;
427
+        try {
428
+            jedis = getJedis();
429
+            for (int i = 0; i < maxLockTime / lockRetryTime + 1; i++) {
430
+                Long now = System.currentTimeMillis();
431
+                result = jedis.setnx(key, String.valueOf(now + maxLockTime));
432
+                if (result == 1L
433
+                        || now > Long.parseLong(jedis.get(key))
434
+                        && now > Long.parseLong(jedis.getSet(key, String.valueOf(now + maxLockTime)))) {
435
+                    jedis.expire(key, (int) (maxLockTime / 1000));
436
+                    return true;
437
+                } else Thread.sleep(lockRetryTime);
438
+            }
439
+        } catch (Exception e) {
440
+            log.error(e.getMessage(), e);
441
+        } finally {
442
+            returnJedis(jedis);
443
+        }
444
+        return false;
445
+    }
446
+
447
+    /**
448
+     * redis  释放分布式锁
449
+     *
450
+     * @param key key
451
+     */
452
+    @Override
453
+    public void releaseLock(String key) {
454
+        Jedis jedis = null;
455
+        try {
456
+            jedis = getJedis();
457
+            jedis.del(key);
458
+        } catch (Exception e) {
459
+            log.error(e.getMessage(), e);
460
+        } finally {
461
+            returnJedis(jedis);
462
+        }
463
+    }
464
+
465
+    /**
466
+     * 缓存是否存在
467
+     *
468
+     * @param key 键
469
+     * @return
470
+     */
471
+    @Override
472
+    public boolean exists(String key) {
473
+        boolean result = false;
474
+        Jedis jedis = null;
475
+        try {
476
+            jedis = getJedis();
477
+            result = jedis.exists(key);
478
+        } catch (Exception e) {
479
+            log.error(e.getMessage(), e);
480
+        } finally {
481
+            returnJedis(jedis);
482
+        }
483
+        return result;
484
+    }
485
+
486
+
487
+    /**
488
+     * 缓存是否存在
489
+     *
490
+     * @param key 键
491
+     * @return
492
+     */
493
+    @Override
494
+    public boolean hexists(String key, String field) {
495
+        boolean result = false;
496
+        Jedis jedis = null;
497
+        try {
498
+            jedis = getJedis();
499
+            result = jedis.hexists(key, field);
500
+        } catch (Exception e) {
501
+            log.error(e.getMessage(), e);
502
+        } finally {
503
+            returnJedis(jedis);
504
+        }
505
+        return result;
506
+    }
507
+
508
+    /**
509
+     * 获取hash缓存的个数
510
+     *
511
+     * @param key 键
512
+     * @return
513
+     */
514
+    @Override
515
+    public Long hlen(String key) {
516
+        Long result = 0L;
517
+        Jedis jedis = null;
518
+        try {
519
+            jedis = getJedis();
520
+            result = jedis.hlen(key);
521
+        } catch (Exception e) {
522
+            log.error(e.getMessage(), e);
523
+        } finally {
524
+            returnJedis(jedis);
525
+        }
526
+        return result;
527
+    }
528
+
529
+    /**
530
+     * 计数器递减
531
+     *
532
+     * @param key
533
+     * @return
534
+     */
535
+    @Override
536
+    public Long decr(String key) {
537
+        Long result = 0L;
538
+        Jedis jedis = null;
539
+        try {
540
+            jedis = getJedis();
541
+            result = jedis.decr(key);
542
+        } catch (Exception e) {
543
+            log.error(e.getMessage(), e);
544
+        } finally {
545
+            returnJedis(jedis);
546
+        }
547
+        return result;
548
+    }
549
+
550
+    /**
551
+     * 计数器递增
552
+     *
553
+     * @param key
554
+     * @return
555
+     */
556
+    @Override
557
+    public Long incr(String key) {
558
+        Long result = 0L;
559
+        Jedis jedis = null;
560
+        try {
561
+            jedis = getJedis();
562
+            result = jedis.incr(key);
563
+        } catch (Exception e) {
564
+            log.error(e.getMessage(), e);
565
+        } finally {
566
+            returnJedis(jedis);
567
+        }
568
+        return result;
569
+    }
570
+
571
+    @Override
572
+    public Long hincrBy(String key, String field, long value) {
573
+        Long result = 0L;
574
+        Jedis jedis = null;
575
+        try {
576
+            jedis = getJedis();
577
+            result = jedis.hincrBy(key, field, value);
578
+        } catch (Exception e) {
579
+            log.error(e.getMessage(), e);
580
+        } finally {
581
+            returnJedis(jedis);
582
+        }
583
+        return result;
584
+    }
585
+}

+ 115
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/BeanTools.java View File

@@ -0,0 +1,115 @@
1
+package com.community.commom.utils;
2
+
3
+import jodd.bean.BeanCopy;
4
+import jodd.typeconverter.TypeConverterManager;
5
+import org.apache.commons.collections.BeanMap;
6
+
7
+import java.lang.reflect.Method;
8
+import java.util.HashMap;
9
+import java.util.Iterator;
10
+import java.util.Map;
11
+
12
+@SuppressWarnings("deprecation")
13
+public final class BeanTools {
14
+
15
+    private static Map<String, Object> toBeanMethodMap = new HashMap<String, Object>();
16
+
17
+    /**
18
+     * <pre>
19
+     * 功能:实现BEAN的属性对拷
20
+     * 创建人:JokenWang
21
+     * </pre>
22
+     *
23
+     * @param fromBean        待转换的源bean
24
+     * @param toBeanClassName 转换成目标bean的名称 形如:ItemSeries.class.getName()
25
+     * @return 目标BEAN类
26
+     */
27
+    public static <T> T convertBean(Object fromBean, Class<T> toBeanClassName) {
28
+        T toBean = null;
29
+        try {
30
+            toBean = getBeanInstance(toBeanClassName.getName());
31
+            return convertBean(fromBean, toBean);
32
+        } catch (Exception e) {
33
+            e.printStackTrace();
34
+        }
35
+        return toBean;
36
+    }
37
+
38
+    private static <T> T convertBean(Object fromBean, T toBean) {
39
+        TypeConverterManager.register(String.class, new StringConverter());
40
+        BeanCopy.beans(fromBean, toBean).copy();
41
+        return toBean;
42
+    }
43
+
44
+    public static Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
45
+        Method method;
46
+        for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
47
+            try {
48
+                method = clazz.getDeclaredMethod(methodName, parameterTypes);
49
+                return method;
50
+            } catch (Exception ignored) {
51
+
52
+            }
53
+        }
54
+        return null;
55
+    }
56
+
57
+    @SuppressWarnings("unchecked")
58
+    public static <T> T getBeanInstance(String clazzName)
59
+            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
60
+
61
+        return (T) Class.forName(clazzName).newInstance();
62
+    }
63
+
64
+    public static Map<String, Object> toBeanMethodMap(String toBean)
65
+            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
66
+
67
+        Class<?> toBeanClazz = getBeanInstance(toBean).getClass();
68
+        Method[] toBeanMethods = toBeanClazz.getDeclaredMethods();
69
+        if (!toBeanClazz.isInstance(Object.class))// 非超类Object
70
+        {
71
+            for (Method method : toBeanMethods) {
72
+                String methodName = method.getName();
73
+                toBeanMethodMap.put(methodName, method);
74
+            }
75
+
76
+            Class<?> toBeanSuperclazz = toBeanClazz.getSuperclass();// 获取父类
77
+            toBeanMethodMap(toBeanSuperclazz.getName());
78
+        }
79
+
80
+        return toBeanMethodMap;
81
+    }
82
+
83
+    public static Map<String, Object> toMap(Object object) {
84
+        Map<String, Object> map = new HashMap<String, Object>();
85
+
86
+        if (object == null) {
87
+            return map;
88
+        }
89
+
90
+        BeanMap beanMap;
91
+        beanMap = new BeanMap(object);
92
+        @SuppressWarnings("unchecked")
93
+        Iterator<String> it = beanMap.keyIterator();
94
+        while (it.hasNext()) {
95
+            String name = it.next();
96
+            Object value = beanMap.get(name);
97
+            // 转换时会将类名也转换成属性,此处去掉
98
+            if (value != null && !name.equals("class")) {
99
+                map.put(name, value);
100
+            }
101
+        }
102
+
103
+        return map;
104
+    }
105
+
106
+    public static Map<String, Object> toMap(Object... objs) {
107
+        Map<String, Object> map = new HashMap<>();
108
+        for (Object object : objs) {
109
+            if (object != null) {
110
+                map.putAll(toMap(object));
111
+            }
112
+        }
113
+        return map;
114
+    }
115
+}

+ 88
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/CommonUtils.java View File

@@ -0,0 +1,88 @@
1
+package com.community.commom.utils;
2
+
3
+import org.springframework.util.StringUtils;
4
+
5
+import java.util.ArrayList;
6
+import java.util.List;
7
+import java.util.regex.Matcher;
8
+import java.util.regex.Pattern;
9
+
10
+/**
11
+ * 类名称:com.yincheng.jcjy.huiju.common.utils
12
+ * 类描述:日常工具类
13
+ * 创建人:Geng Xiang
14
+ * 创建时间:2017/11/8 14:29
15
+ *
16
+ * @version 1.0.0
17
+ */
18
+public class CommonUtils {
19
+
20
+    public static Integer str2Int(String target) {
21
+        if (target != null && target.trim().length() > 0) {
22
+            return Integer.parseInt(target);
23
+        }
24
+        return null;
25
+    }
26
+
27
+    public static boolean patterMatch(String target, String patternStr) {
28
+        Pattern pattern = Pattern.compile(patternStr);          // ""
29
+        Matcher matcher = pattern.matcher(target);
30
+        return matcher.matches();
31
+    }
32
+
33
+
34
+    /**
35
+     * 正则匹配获取参数
36
+     * 目前只取一个
37
+     *
38
+     * @param target 目标String
39
+     * @param parn   匹配表达式
40
+     * @return List<String>
41
+     */
42
+    public static List<String> formatParam(String target, String prefix, String parn) {
43
+        List<String> result = new ArrayList<>();
44
+        Pattern p = Pattern.compile(parn);
45
+        Matcher m = p.matcher(target);
46
+        while (m.find()) {
47
+            if (StringUtils.hasText(prefix)){
48
+                result.add(m.group().substring(prefix.length()));
49
+            } else{
50
+                result.add(m.group());
51
+            }
52
+        }
53
+
54
+        if (result == null || result.size() == 0){
55
+            result.add("");
56
+        }
57
+        return result;
58
+    }
59
+
60
+    /**
61
+     * 正则匹配获取参数 删除已匹配数据
62
+     * 目前只取一个
63
+     *
64
+     * @param target 目标String
65
+     * @param parn   匹配表达式
66
+     * @return List<String>
67
+     */
68
+    public static List<String> formatParam(StringBuffer target, String prefix, String parn) {
69
+        List<String> result = new ArrayList<>();
70
+        String targetStr = target.toString();
71
+        Pattern p = Pattern.compile(parn);
72
+        Matcher m = p.matcher(targetStr);
73
+        while (m.find()) {
74
+            if (StringUtils.hasText(prefix)){
75
+                result.add(m.group().substring(prefix.length()));
76
+            } else{
77
+                result.add(m.group());
78
+            }
79
+            //删除已匹配的参数
80
+            target.delete(target.indexOf(m.group()), target.indexOf(m.group())+m.group().length());
81
+        }
82
+
83
+        if (result == null || result.size() == 0){
84
+            result.add("");
85
+        }
86
+        return result;
87
+    }
88
+}

+ 142
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/CookieUtil.java View File

@@ -0,0 +1,142 @@
1
+package com.community.commom.utils;
2
+
3
+
4
+import org.springframework.util.StringUtils;
5
+
6
+import javax.servlet.http.Cookie;
7
+import java.util.ArrayList;
8
+import java.util.HashMap;
9
+import java.util.List;
10
+import java.util.Map;
11
+import java.util.regex.Matcher;
12
+import java.util.regex.Pattern;
13
+
14
+/**
15
+ * describe: cookie 历史记录
16
+ * creat_user: gengxiang
17
+ * creat_time: 2017/12/25 9:05
18
+ * version V1.0
19
+ **/
20
+public class CookieUtil {
21
+
22
+    /**
23
+     * 获取所有的历史记录
24
+     *
25
+     * @param cookies 所有的cookie
26
+     * @param type    获取的cookie类型
27
+     * @return java.util.List<java.lang.String>
28
+     * @author gengxiang
29
+     * @date 2017/12/25 9:19
30
+     */
31
+    public static List<String> getAll(Cookie[] cookies, String type) {
32
+        List<String> result = new ArrayList<>();
33
+        Map<String, Cookie> cookieMap = toCookieMap(cookies);
34
+        Cookie cookie = cookieMap.get(type);
35
+        if (cookie != null) {
36
+            String value = cookie.getValue();
37
+            if (StringUtils.hasText(value)){
38
+                String[] values = value.split("#");
39
+                for (int i = 0; i < values.length; i++) {
40
+                    result.add(values[i]);
41
+                }
42
+            }
43
+        }
44
+        return result;
45
+    }
46
+
47
+    /**
48
+     * 设置cookie
49
+     * @author gengxiang
50
+     * @date 2017/12/25 10:08
51
+     * @param cookies cookie array
52
+     * @param type  cookie name
53
+     * @param value cookie value
54
+     * @return javax.servlet.http.Cookie
55
+     */
56
+    public static Cookie setCookie(Cookie[] cookies, String type, String value) {
57
+
58
+        Map<String, Cookie> cookieMap = toCookieMap(cookies);
59
+        Cookie cookie = cookieMap.get(type);
60
+        if (cookie != null && StringUtils.hasText(cookie.getValue())
61
+                && !(cookie.getValue().startsWith(value) || cookie.getValue().contains("#"+value))){
62
+            //cookie值中“#”出现的次数
63
+            int times = appearTimes(cookie.getValue(), "#");
64
+            //10个值有9个“#”,小于9直接保存到cookie
65
+            if(times < 9){
66
+                cookie.setValue(value+"#"+cookie.getValue());
67
+                cookie.setMaxAge(60*60*24*30);
68
+                cookie.setPath("/");
69
+            }else {
70
+                String oldValue = cookie.getValue();
71
+                //截取最新的9个值
72
+                String newValue = oldValue.substring(0, oldValue.lastIndexOf("#"));
73
+                cookie.setValue(value + "#" + newValue);
74
+                cookie.setMaxAge(60*60*24*30);
75
+                cookie.setPath("/");
76
+            }
77
+        }else if (cookie == null || !StringUtils.hasText(cookie.getValue())){
78
+            cookie = new Cookie(type, value);
79
+            cookie.setMaxAge(60*60*24*30);
80
+            cookie.setPath("/");
81
+            cookie.setHttpOnly(true);
82
+        }
83
+        return cookie;
84
+    }
85
+
86
+    /**
87
+     * 删除 cookie
88
+     * @author gengxiang
89
+     * @date 2017/12/25 10:17
90
+     * @param cookies cookie array
91
+     * @param type  cookie name
92
+     * @return javax.servlet.http.Cookie
93
+     */
94
+    public static Cookie delCookie(Cookie[] cookies, String type){
95
+        Map<String, Cookie> cookieMap = toCookieMap(cookies);
96
+        Cookie cookie = cookieMap.get(type);
97
+        if (cookie != null){
98
+            cookie.setValue(null);
99
+            cookie.setMaxAge(0);
100
+            cookie.setPath("/");
101
+        }
102
+        return cookie;
103
+    }
104
+
105
+
106
+    /**
107
+     * cookie array to map
108
+     * @author gengxiang
109
+     * @date 2017/12/25 10:10
110
+     * @param cookies
111
+     * @return java.util.Map<java.lang.String,javax.servlet.http.Cookie>
112
+     */
113
+    public static Map<String, Cookie> toCookieMap(Cookie[] cookies) {
114
+        Map<String, Cookie> result = new HashMap<>();
115
+        if (cookies != null && cookies.length > 0) {
116
+            for (Cookie cookie : cookies) {
117
+                result.put(cookie.getName(), cookie);
118
+            }
119
+        }
120
+        return result;
121
+    }
122
+
123
+
124
+    /**
125
+     * 获取指定字符串出现的次数
126
+     *   
127
+     * @author xrq  
128
+     * @date 2017/12/25 15:16
129
+     * @param srcText 源字符串
130
+     * @param findText 要查找的字符串
131
+     * @return int  
132
+     */ 
133
+    public static int appearTimes(String srcText, String findText) {
134
+        int count = 0;
135
+        Pattern p = Pattern.compile(findText);
136
+        Matcher m = p.matcher(srcText);
137
+        while (m.find()) {
138
+            count++;
139
+        }
140
+        return count;
141
+    }
142
+}

+ 139
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/DESUtils.java View File

@@ -0,0 +1,139 @@
1
+package com.community.commom.utils;
2
+
3
+import sun.misc.BASE64Decoder;
4
+import sun.misc.BASE64Encoder;
5
+
6
+import javax.crypto.Cipher;
7
+import javax.crypto.SecretKeyFactory;
8
+import javax.crypto.spec.DESKeySpec;
9
+import javax.crypto.spec.IvParameterSpec;
10
+import java.security.Key;
11
+import java.security.SecureRandom;
12
+
13
+/**
14
+ * des 加解密共通方法
15
+ * Created by wuxuewen on 2016/10/20.
16
+ */
17
+public class DESUtils {
18
+
19
+    Key key;
20
+
21
+    String ivParameterSpec = null;
22
+
23
+    public DESUtils(String str, String ivParameterSpec) {
24
+        setKey(str);// 生成密匙
25
+        this.ivParameterSpec = ivParameterSpec;
26
+    }
27
+
28
+    public DESUtils() {
29
+        setKey("Lnydzxkf");
30
+    }
31
+
32
+    /**
33
+     * 根据参数生成KEY
34
+     */
35
+    public void setKey(String strKey) {
36
+        try {
37
+            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
38
+            this.key = keyFactory.generateSecret(new DESKeySpec(strKey.getBytes("UTF8")));
39
+        } catch (Exception e) {
40
+            throw new RuntimeException(
41
+                    "Error initializing SqlMap class. Cause: " + e);
42
+        }
43
+    }
44
+
45
+
46
+    /**
47
+     * 加密String明文输入,String密文输出
48
+     *
49
+     * @param strMing strMing
50
+     * @return result
51
+     */
52
+    public String encrypt(String strMing) {
53
+        byte[] byteMi;
54
+        byte[] byteMing;
55
+        String strMi = "";
56
+        BASE64Encoder base64en = new BASE64Encoder();
57
+        try {
58
+            byteMing = strMing.getBytes("UTF8");
59
+            byteMi = this.getEncCode(byteMing);
60
+            strMi = base64en.encode(byteMi);
61
+        } catch (Exception e) {
62
+            throw new RuntimeException(
63
+                    "Error initializing SqlMap class. Cause: " + e);
64
+        }
65
+        return strMi;
66
+    }
67
+
68
+    /**
69
+     * 解密 以String密文输入,String明文输出
70
+     *
71
+     * @param strMi strMi
72
+     * @return result
73
+     */
74
+    public String decrypt(String strMi) {
75
+        BASE64Decoder base64De = new BASE64Decoder();
76
+        byte[] byteMing;
77
+        byte[] byteMi;
78
+        String strMing;
79
+        try {
80
+            byteMi = base64De.decodeBuffer(strMi);
81
+            byteMing = this.getDesCode(byteMi);
82
+            strMing = new String(byteMing, "UTF8");
83
+        } catch (Exception e) {
84
+            throw new RuntimeException(
85
+                    "Error initializing SqlMap class. Cause: " + e);
86
+        }
87
+        return strMing;
88
+    }
89
+
90
+    /**
91
+     * 加密以byte[]明文输入,byte[]密文输出
92
+     *
93
+     * @param byteS byteS
94
+     * @return result
95
+     */
96
+    private byte[] getEncCode(byte[] byteS) {
97
+        byte[] byteFina;
98
+        Cipher cipher;
99
+        try {
100
+            cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
101
+            if (ivParameterSpec != null) {
102
+                IvParameterSpec iv = new IvParameterSpec(ivParameterSpec.getBytes("UTF8"));
103
+                cipher.init(Cipher.ENCRYPT_MODE, key, iv);
104
+            } else {
105
+                cipher.init(Cipher.DECRYPT_MODE, key, SecureRandom.getInstance("SHA1PRNG"));
106
+            }
107
+            byteFina = cipher.doFinal(byteS);
108
+        } catch (Exception e) {
109
+            throw new RuntimeException(
110
+                    "Error initializing SqlMap class. Cause: " + e);
111
+        }
112
+        return byteFina;
113
+    }
114
+
115
+    /**
116
+     * 解密以byte[]密文输入,以byte[]明文输出
117
+     *
118
+     * @param byteD byteD
119
+     * @return result
120
+     */
121
+    private byte[] getDesCode(byte[] byteD) {
122
+        Cipher cipher;
123
+        byte[] byteFina;
124
+        try {
125
+            cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
126
+            if (ivParameterSpec != null) {
127
+                IvParameterSpec iv = new IvParameterSpec(ivParameterSpec.getBytes("UTF8"));
128
+                cipher.init(Cipher.DECRYPT_MODE, key, iv);
129
+            } else {
130
+                cipher.init(Cipher.DECRYPT_MODE, key, SecureRandom.getInstance("SHA1PRNG"));
131
+            }
132
+            byteFina = cipher.doFinal(byteD);
133
+        } catch (Exception e) {
134
+            throw new RuntimeException(
135
+                    "Error initializing SqlMap class. Cause: " + e);
136
+        }
137
+        return byteFina;
138
+    }
139
+}

+ 277
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/DateUtils.java View File

@@ -0,0 +1,277 @@
1
+package com.community.commom.utils;
2
+
3
+
4
+import java.text.DateFormat;
5
+import java.text.ParseException;
6
+import java.text.SimpleDateFormat;
7
+import java.util.Calendar;
8
+import java.util.Date;
9
+
10
+/**
11
+ * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
12
+ */
13
+public class DateUtils {
14
+
15
+    /**
16
+     * 得到当前日期字符串 格式(yyyy-MM-dd)
17
+     */
18
+    public static String getDate() {
19
+        return getDate("yyyy-MM-dd");
20
+    }
21
+
22
+    /**
23
+     * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
24
+     */
25
+    public static String getDate(String pattern) {
26
+        DateFormat sdf = new SimpleDateFormat(pattern);
27
+        return sdf.format(new Date());
28
+    }
29
+
30
+    /**
31
+     * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
32
+     */
33
+    public static String formatDate(Date date, Object... pattern) {
34
+        DateFormat sdf;
35
+        if (pattern != null && pattern.length > 0) {
36
+            sdf = new SimpleDateFormat(pattern[0].toString());
37
+        } else {
38
+            sdf = new SimpleDateFormat("yyyy-MM-dd");
39
+        }
40
+        return sdf.format(date);
41
+    }
42
+
43
+    /**
44
+     * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
45
+     */
46
+    public static String formatDateTime(Date date) {
47
+        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
48
+    }
49
+
50
+    /**
51
+     * 得到当前时间字符串 格式(HH:mm:ss)
52
+     */
53
+    public static String getTime() {
54
+        return formatDate(new Date(), "HH:mm:ss");
55
+    }
56
+
57
+    /**
58
+     * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
59
+     */
60
+    public static String getDateTime() {
61
+        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
62
+    }
63
+
64
+    /**
65
+     * 得到当前年份字符串 格式(yyyy)
66
+     */
67
+    public static String getYear() {
68
+        return formatDate(new Date(), "yyyy");
69
+    }
70
+
71
+    /**
72
+     * 得到当前月份字符串 格式(MM)
73
+     */
74
+    public static String getMonth() {
75
+        return formatDate(new Date(), "MM");
76
+    }
77
+
78
+    /**
79
+     * 得到当天字符串 格式(dd)
80
+     */
81
+    public static String getDay() {
82
+        return formatDate(new Date(), "dd");
83
+    }
84
+
85
+    /**
86
+     * 得到当前星期字符串 格式(E)星期几
87
+     */
88
+    public static String getWeek() {
89
+        return formatDate(new Date(), "E");
90
+    }
91
+
92
+    /**
93
+     * 日期型字符串转化为日期 格式
94
+     * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
95
+     * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
96
+     * "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
97
+     */
98
+    public static Date parseDate(String str, String pattern) {
99
+        if (str == null) {
100
+            return null;
101
+        }
102
+        try {
103
+            DateFormat sdf = new SimpleDateFormat(pattern);
104
+            return sdf.parse(str);
105
+        } catch (ParseException e) {
106
+            return null;
107
+        }
108
+    }
109
+
110
+    /**
111
+     * 获取过去的天数
112
+     *
113
+     * @param date
114
+     * @return
115
+     */
116
+    public static long pastDays(Date date) {
117
+        long t = new Date().getTime() - date.getTime();
118
+        return t / (24 * 60 * 60 * 1000);
119
+    }
120
+
121
+    /**
122
+     * 获取过去的小时
123
+     *
124
+     * @param date
125
+     * @return
126
+     */
127
+    public static long pastHour(Date date) {
128
+        long t = new Date().getTime() - date.getTime();
129
+        return t / (60 * 60 * 1000);
130
+    }
131
+
132
+    /**
133
+     * 获取过去的分钟
134
+     *
135
+     * @param date
136
+     * @return
137
+     */
138
+    public static long pastMinutes(Date date) {
139
+        long t = new Date().getTime() - date.getTime();
140
+        return t / (60 * 1000);
141
+    }
142
+
143
+    /**
144
+     * 转换为时间(天,时:分:秒.毫秒)
145
+     *
146
+     * @param timeMillis
147
+     * @return
148
+     */
149
+    public static String formatDateTime(long timeMillis) {
150
+        long day = timeMillis / (24 * 60 * 60 * 1000);
151
+        long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
152
+        long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
153
+        long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
154
+        long sss = (timeMillis - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
155
+        return (day > 0 ? day + "," : "") + hour + ":" + min + ":" + s + "." + sss;
156
+    }
157
+
158
+    /**
159
+     * 获取两个日期之间的天数
160
+     *
161
+     * @param before
162
+     * @param after
163
+     * @return
164
+     */
165
+    public static double getDistanceOfTwoDate(Date before, Date after) {
166
+        long beforeTime = before.getTime();
167
+        long afterTime = after.getTime();
168
+        return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
169
+    }
170
+
171
+
172
+    /**
173
+     * 获取当前月份的第一天
174
+     *
175
+     * @return result
176
+     */
177
+    public static Date getMonthFirstDay() {
178
+        Calendar cal = Calendar.getInstance();
179
+        cal.add(Calendar.MONTH, 0);
180
+        cal.set(Calendar.DAY_OF_MONTH, 1);
181
+        return cal.getTime();
182
+    }
183
+
184
+    /**
185
+     * 获取当前月份的最后一天
186
+     *
187
+     * @return result
188
+     */
189
+    public static Date getMonthLastDay() {
190
+        Calendar cal = Calendar.getInstance();
191
+        cal.add(Calendar.MONTH, 1);
192
+        cal.set(Calendar.DAY_OF_MONTH, 0);
193
+        return cal.getTime();
194
+    }
195
+
196
+    /**
197
+     * 取出两个日期的差
198
+     *
199
+     * @param startDate 开始时间
200
+     * @param endDate   结束时间
201
+     * @return 天数差
202
+     */
203
+    public static int dayDif(Date startDate, Date endDate) {
204
+        double between = (endDate.getTime() - startDate.getTime()) / 1000;//除以1000是为了转换成秒
205
+        double day = between / (24 * 3600);
206
+        return (int) day;
207
+    }
208
+
209
+    /**
210
+     * 获取当前时间N个小时
211
+     *
212
+     * @param n 天数
213
+     * @return Date
214
+     */
215
+    public static Date getCurrentDatePreH(int n) {
216
+        Calendar now = Calendar.getInstance();
217
+        now.set(Calendar.HOUR_OF_DAY, now.get(Calendar.HOUR_OF_DAY) - n);
218
+        now.set(Calendar.MINUTE, 0);
219
+        now.set(Calendar.SECOND, 0);
220
+        return now.getTime();
221
+    }
222
+
223
+    /**
224
+     * 获取当前时间N个小时
225
+     *
226
+     * @param n 天数
227
+     * @return Date
228
+     */
229
+    public static Date getCurrentDatePreEndH(int n) {
230
+        Calendar now = Calendar.getInstance();
231
+        now.set(Calendar.HOUR_OF_DAY, now.get(Calendar.HOUR_OF_DAY) - n);
232
+        now.set(Calendar.MINUTE, 59);
233
+        now.set(Calendar.SECOND, 59);
234
+        return now.getTime();
235
+    }
236
+
237
+    /**
238
+     * 获取时间的N的前后时间
239
+     * @param date
240
+     * @param n 为正数获取后N天, n为负数获取时间的前N天
241
+     * @return
242
+     */
243
+    public static Date getDateLasyDay(Date date,Integer n){
244
+        Calendar calendar = Calendar.getInstance();
245
+        calendar.setTime(date);
246
+        calendar.add(Calendar.DAY_OF_MONTH, n);
247
+        return new Date(calendar.getTimeInMillis());
248
+    }
249
+
250
+    /**
251
+     * 计算每天分配数量
252
+     * @param startDate   startDate
253
+     * @param endDate    endDate
254
+     * @param totalNum   totalNum
255
+     * @param receiveNum receiveNum
256
+     * @param nextScroll nextScroll
257
+     * @return presentNum
258
+     */
259
+    public static int getDayAssignedNum(Date startDate, Date endDate, int totalNum, int receiveNum, boolean nextScroll) {
260
+        int presentNum;
261
+        int dayDif = DateUtils.dayDif(new Date(), endDate);
262
+        //是否为最后一天
263
+        if (dayDif == 0) {
264
+            presentNum = totalNum - receiveNum;
265
+        } else {
266
+            dayDif = DateUtils.dayDif(startDate, endDate) + 1;
267
+            presentNum = totalNum / dayDif;
268
+            if (nextScroll) {
269
+                dayDif = DateUtils.dayDif(startDate, new Date());
270
+                if (dayDif > 0) {
271
+                    presentNum += dayDif * presentNum - receiveNum;
272
+                }
273
+            }
274
+        }
275
+        return presentNum;
276
+    }
277
+}

+ 120
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/EnumUtils.java View File

@@ -0,0 +1,120 @@
1
+package com.community.commom.utils;
2
+
3
+import java.lang.reflect.InvocationTargetException;
4
+import java.lang.reflect.Method;
5
+import java.util.Arrays;
6
+import java.util.HashMap;
7
+import java.util.List;
8
+import java.util.Map;
9
+
10
+/**
11
+ * 权举类型转换utils
12
+ * Created by wuxuewen on 2017/3/14.
13
+ */
14
+public class EnumUtils {
15
+
16
+    /**
17
+     * 把enum封成list,便于前端调用
18
+     *
19
+     * @return 例如:
20
+     * model.addAttribute("cateList", Enums.toList(Enums.BrandCate.class));
21
+     * <select cname="type" >
22
+     * <c:forEach var="type" items="${cateList}">
23
+     * <option value="${type.key}">${type.cname}</option>
24
+     * </c:forEach>
25
+     * </select>
26
+     */
27
+    public static <T extends Enum> List<T> toList(Class<T> clazz) {
28
+        return Arrays.asList(clazz.getEnumConstants());
29
+    }
30
+
31
+    /**
32
+     * 转为MAP
33
+     *
34
+     * @param clazz         Enums.class
35
+     * @param keyMethodName MethodName
36
+     * @param <T>           Enums
37
+     * @return Map<Object,Object>
38
+     */
39
+    public static <T extends Enum> Map<Object, T> toMap(Class<T> clazz, String keyMethodName) {
40
+        T[] universe = getEnumConstantsShared(clazz);
41
+        if (universe == null) {
42
+            return null;
43
+        }
44
+        Map<Object, T> directory = new HashMap<>();
45
+        for (T constant : universe)
46
+            try {
47
+                Object key;
48
+                if (keyMethodName != null && keyMethodName.trim().length() > 0) {
49
+                    Method method = constant.getClass().getMethod(keyMethodName);
50
+                    key = method.invoke(constant);
51
+                } else {
52
+                    key = constant.name();
53
+                }
54
+                directory.put(key, constant);
55
+            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
56
+                e.printStackTrace();
57
+            }
58
+        return directory;
59
+    }
60
+
61
+    /**
62
+     * 转为MAP
63
+     *
64
+     * @param clazz         Enums.class
65
+     * @param keyMethodName MethodName
66
+     * @param valMethodName MethodName
67
+     * @param <T>           Enums
68
+     * @return Map<String,Object>
69
+     */
70
+    public static <T extends Enum> Map<String, Object> toMap(Class<T> clazz, String keyMethodName, String valMethodName) {
71
+        T[] universe = getEnumConstantsShared(clazz);
72
+        if (universe == null) {
73
+            return null;
74
+        }
75
+        Map<String, Object> directory = new HashMap<>(2 * universe.length);
76
+        for (T constant : universe)
77
+            try {
78
+                Object key, value;
79
+                if (keyMethodName != null && keyMethodName.trim().length() > 0) {
80
+                    Method method = constant.getClass().getMethod(keyMethodName);
81
+                    key = method.invoke(constant);
82
+                } else {
83
+                    key = constant.name();
84
+                }
85
+                if (valMethodName != null && valMethodName.trim().length() > 0) {
86
+                    Method method = constant.getClass().getMethod(valMethodName);
87
+                    value = method.invoke(constant);
88
+                } else {
89
+                    value = constant;
90
+                }
91
+                directory.put(key.toString(), value);
92
+            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
93
+                e.printStackTrace();
94
+            }
95
+        return directory;
96
+    }
97
+
98
+
99
+    /**
100
+     * 获取权举对象列表
101
+     *
102
+     * @param clazz Enum.class
103
+     * @param <T>   Enum
104
+     * @return Enums
105
+     */
106
+    private static <T extends Enum> T[] getEnumConstantsShared(Class<T> clazz) {
107
+        T[] enumConstants;
108
+        if (!clazz.isEnum()) return null;
109
+        try {
110
+            final Method values = clazz.getMethod("values");
111
+            @SuppressWarnings("unchecked")
112
+            T[] temporaryConstants = (T[]) values.invoke(null);
113
+            enumConstants = temporaryConstants;
114
+        } catch (InvocationTargetException | NoSuchMethodException |
115
+                IllegalAccessException ex) {
116
+            return null;
117
+        }
118
+        return enumConstants;
119
+    }
120
+}

+ 148
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/HttpClientUtils.java View File

@@ -0,0 +1,148 @@
1
+package com.community.commom.utils;
2
+
3
+import org.apache.commons.httpclient.methods.GetMethod;
4
+import org.apache.commons.httpclient.methods.PostMethod;
5
+import org.apache.commons.httpclient.methods.RequestEntity;
6
+import org.apache.commons.httpclient.methods.StringRequestEntity;
7
+import org.apache.commons.httpclient.params.HttpMethodParams;
8
+import org.slf4j.Logger;
9
+import org.slf4j.LoggerFactory;
10
+import org.springframework.util.StringUtils;
11
+
12
+import java.io.BufferedReader;
13
+import java.io.InputStream;
14
+import java.io.InputStreamReader;
15
+import java.io.UnsupportedEncodingException;
16
+import java.util.HashMap;
17
+import java.util.Map;
18
+
19
+/**
20
+ * 外部接口调用处理(HTTP方式)
21
+ * Created by wuxuewen on 2016/11/8.
22
+ */
23
+public class HttpClientUtils {
24
+
25
+    public static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
26
+
27
+    public static final String HTTP_STATUS = "200";
28
+
29
+    /**
30
+     * 外部HTTP接口调用处理
31
+     *
32
+     * @param url               接口地址
33
+     * @param message           发送消息信息
34
+     * @param readTimeout       发送超时时间
35
+     * @param connectionTimeout 连接超时时间
36
+     * @return 接口返回
37
+     */
38
+    public static String sendMessage(final String url, final String message, final int readTimeout, final int connectionTimeout) {
39
+        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
40
+        client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
41
+        client.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);
42
+        PostMethod httpPost = new PostMethod(url);
43
+        httpPost.setRequestHeader("Response-Type", "xml");
44
+        httpPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
45
+        RequestEntity requestXml = null;
46
+        try {
47
+            requestXml = new StringRequestEntity(message, "text/xml", "UTF-8");
48
+        } catch (UnsupportedEncodingException e1) {
49
+            e1.printStackTrace();
50
+        }
51
+        try {
52
+            httpPost.setRequestEntity(requestXml);
53
+            int statusCode = client.executeMethod(httpPost);
54
+            if (statusCode == 200) {
55
+                return httpPost.getResponseBodyAsString();
56
+            }
57
+        } catch (Exception e) {
58
+            e.printStackTrace();
59
+        } finally {
60
+            httpPost.releaseConnection();
61
+            client.getHttpConnectionManager().closeIdleConnections(0);
62
+        }
63
+        return null;
64
+    }
65
+
66
+    /**
67
+     * HTTP GET请求调用
68
+     *
69
+     * @param url               请求地址
70
+     * @param readTimeout       请求超时
71
+     * @param connectionTimeout 连接超时
72
+     * @return 请求返回
73
+     */
74
+    public static String httpGet(final String url, final int readTimeout, final int connectionTimeout) {
75
+        String responseBody = null;
76
+        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
77
+        client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
78
+        client.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);
79
+        GetMethod httpPost = new GetMethod(url);
80
+        try {
81
+            httpPost.setRequestHeader("Connection", "close");
82
+            client.executeMethod(httpPost);
83
+            InputStream in = httpPost.getResponseBodyAsStream();
84
+            if (in != null) {
85
+                BufferedReader buffer = new BufferedReader(new InputStreamReader(in, "UTF-8"));
86
+                StringBuffer sbf;
87
+                sbf = new StringBuffer();
88
+                String line;
89
+                while ((line = buffer.readLine()) != null) {
90
+                    sbf.append(line);
91
+                }
92
+                buffer.close();
93
+                responseBody = sbf.toString();
94
+            }
95
+        } catch (Exception e) {
96
+            e.printStackTrace();
97
+        } finally {
98
+            httpPost.releaseConnection();
99
+            client.getHttpConnectionManager().closeIdleConnections(0);
100
+        }
101
+        return responseBody;
102
+    }
103
+
104
+
105
+    /**
106
+     * 共用HTTPPOST请求处理
107
+     *
108
+     * @param url    请求地址
109
+     * @param params 请求的参数信息
110
+     * @return 返回
111
+     * @throws Exception
112
+     */
113
+    public static Map<String, String> httpPost(String url, Map<String, Object> params) throws Exception {
114
+        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
115
+        client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
116
+        client.getHttpConnectionManager().getParams().setSoTimeout(3000);
117
+        PostMethod httpPost = new PostMethod(url);
118
+        Map<String, String> returnMap = new HashMap<String, String>();
119
+        try {
120
+            httpPost.setRequestHeader("Connection", "close");
121
+            if (params != null) {
122
+                for (Object o : params.entrySet()) {
123
+                    Map.Entry entry = (Map.Entry) o;
124
+                    Object key = entry.getKey();
125
+                    String value = (String) entry.getValue();
126
+                    if (StringUtils.hasText(value))
127
+                        httpPost.addParameter(key.toString(), value);
128
+                }
129
+            }
130
+            httpPost.getParams().setContentCharset("UTF-8");
131
+            httpPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
132
+            int statusCode = client.executeMethod(httpPost);
133
+            log.info("Request for method " + Thread.currentThread().getStackTrace()[3].getMethodName() +
134
+                    " statusCode=" + statusCode);
135
+            returnMap.put("statusCode", String.valueOf(statusCode));
136
+            String responseString = httpPost.getResponseBodyAsString();
137
+            log.info("Response responseString " + responseString);
138
+            returnMap.put("responseString", responseString);
139
+        } catch (Exception e) {
140
+            log.error("request url " + url + " Error:{}", e);
141
+            returnMap.put("statusCode", "-1");
142
+        } finally {
143
+            httpPost.releaseConnection();
144
+            client.getHttpConnectionManager().closeIdleConnections(0);
145
+        }
146
+        return returnMap;
147
+    }
148
+}

+ 51
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/MD5Utils.java View File

@@ -0,0 +1,51 @@
1
+package com.community.commom.utils;
2
+
3
+import java.io.UnsupportedEncodingException;
4
+import java.security.MessageDigest;
5
+
6
+/**
7
+ * 用户密码加密
8
+ * Created by Administrator on 2015/8/9.
9
+ */
10
+public class MD5Utils {
11
+    /**
12
+     * MD5加密
13
+     *
14
+     * @param s 字符串
15
+     * @return MD5加密 字符串
16
+     */
17
+    public static String encode(String s) {
18
+        try {
19
+            return encode(s.getBytes("utf-8"));
20
+        } catch (UnsupportedEncodingException e) {
21
+            e.printStackTrace();
22
+        }
23
+        return null;
24
+    }
25
+
26
+    private static String encode(byte[] b) {
27
+        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
28
+                'a', 'b', 'c', 'd', 'e', 'f'};
29
+        try {
30
+            byte[] strTemp;
31
+            strTemp = b;
32
+            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
33
+            mdTemp.update(strTemp);
34
+            byte[] md = mdTemp.digest();
35
+            int j = md.length;
36
+            char str[] = new char[j * 2];
37
+            int k = 0;
38
+            for (byte byte0 : md) {
39
+                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
40
+                str[k++] = hexDigits[byte0 & 0xf];
41
+            }
42
+            return new String(str);
43
+        } catch (Exception e) {
44
+            return null;
45
+        }
46
+    }
47
+
48
+    public static void main(String[] arge) throws Exception {
49
+       System.out.println(MD5Utils.encode("123456"));
50
+    }
51
+}

+ 113
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/QRCodeGeneratorUtils.java View File

@@ -0,0 +1,113 @@
1
+package com.community.commom.utils;
2
+
3
+import com.google.zxing.BarcodeFormat;
4
+import com.google.zxing.EncodeHintType;
5
+import com.google.zxing.MultiFormatWriter;
6
+import com.google.zxing.WriterException;
7
+import com.google.zxing.client.j2se.MatrixToImageWriter;
8
+import com.google.zxing.common.BitMatrix;
9
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
10
+
11
+import javax.imageio.ImageIO;
12
+import java.awt.*;
13
+import java.awt.image.BufferedImage;
14
+import java.io.ByteArrayInputStream;
15
+import java.io.ByteArrayOutputStream;
16
+import java.io.IOException;
17
+import java.util.HashMap;
18
+import java.util.Map;
19
+
20
+/**
21
+ * 二维码生成工具类
22
+ * Created by wuxuewen on 2017/4/17.
23
+ */
24
+public class QRCodeGeneratorUtils {
25
+    public static final int width = 300;
26
+
27
+    public static final int height = 300;
28
+
29
+    /**
30
+     * qr code generate
31
+     *
32
+     * @param url     url
33
+     * @param logoImg byte array of logo image
34
+     * @return byte array of qr code image
35
+     */
36
+    public static byte[] qrCode(String url, byte[] logoImg) {
37
+        try {
38
+            BufferedImage image = generate(url, logoImg);
39
+
40
+            ByteArrayOutputStream out = new ByteArrayOutputStream();
41
+            ImageIO.write(image, "png", out);
42
+
43
+            return out.toByteArray();
44
+        } catch (Exception e) {
45
+            throw new RuntimeException("Error: generate qr code.", e);
46
+        }
47
+    }
48
+
49
+    /**
50
+     * @param url       链接地址
51
+     * @param logImg  二维码图标img
52
+     * @return result
53
+     * @throws WriterException
54
+     * @throws IOException
55
+     */
56
+    public static BufferedImage generate(String url, byte[] logImg) throws WriterException, IOException {
57
+        if (logImg != null && logImg.length > 0) {
58
+            ByteArrayInputStream in = new ByteArrayInputStream(logImg);
59
+            BufferedImage logo = ImageIO.read(in);
60
+            return generateImg(url, logo);
61
+        } else {
62
+            return generateImg(url, null);
63
+        }
64
+    }
65
+
66
+    /**
67
+     * @param url    链接地址
68
+     * @param logImg 二维码图标img
69
+     * @return result
70
+     * @throws WriterException
71
+     */
72
+    public static BufferedImage generateImg(String url, BufferedImage logImg) throws WriterException {
73
+        BitMatrix bitMatrix;
74
+        Map<EncodeHintType, Object> hints = new HashMap<>();
75
+
76
+        if (logImg != null) {
77
+            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
78
+            bitMatrix = new MultiFormatWriter().encode(url,
79
+                    BarcodeFormat.QR_CODE, width, height, hints);
80
+            int logoSize = (int) (width / (4.0 + 20 / (url.length() + 10))); // into 4~6
81
+            int start = (width - logoSize) / 2;
82
+            bitMatrix.setRegion(start, start, logoSize, logoSize);// logo region
83
+            BufferedImage qrCode = MatrixToImageWriter.toBufferedImage(bitMatrix);
84
+
85
+            //combine qr code and logo
86
+            BufferedImage combine = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
87
+            Graphics g = combine.getGraphics();
88
+            g.drawImage(qrCode, 0, 0, null);
89
+            g.drawImage(resizeImg(logImg, logoSize, logoSize), start, start, null);
90
+            return combine;
91
+        } else {
92
+            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
93
+            bitMatrix = new MultiFormatWriter().encode(url,
94
+                    BarcodeFormat.QR_CODE, width, height, hints);
95
+            return MatrixToImageWriter.toBufferedImage(bitMatrix);
96
+        }
97
+    }
98
+
99
+    /**
100
+     * resize image
101
+     *
102
+     * @param logoImg image BufferedImage
103
+     * @param width   resize width
104
+     * @param height  resize height
105
+     * @return resized image
106
+     */
107
+    public static BufferedImage resizeImg(BufferedImage logoImg, int width, int height) {
108
+        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
109
+        tag.getGraphics().drawImage(logoImg.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING),
110
+                0, 0, null);
111
+        return tag;
112
+    }
113
+}

+ 72
- 0
SmartCommunity/SmartCommunityV1/community-common/src/main/java/com/community/commom/utils/StringConverter.java View File

@@ -0,0 +1,72 @@
1
+package com.community.commom.utils;
2
+
3
+import jodd.typeconverter.TypeConversionException;
4
+import jodd.typeconverter.TypeConverter;
5
+import jodd.util.ArraysUtil;
6
+
7
+import java.sql.Clob;
8
+import java.sql.SQLException;
9
+import java.util.Date;
10
+
11
+public class StringConverter implements TypeConverter<String> {
12
+
13
+    public String convert(Object value) {
14
+        if (value == null) {
15
+            return null;
16
+        }
17
+
18
+        if (value instanceof CharSequence) { // for speed
19
+            return value.toString();
20
+        }
21
+        Class<?> type = value.getClass();
22
+        if (type == Class.class) {
23
+            return ((Class<?>) value).getName();
24
+        }
25
+        if (type.isArray()) {
26
+            if (type == char[].class) {
27
+                char[] charArray = (char[]) value;
28
+                return new String(charArray);
29
+            }
30
+            if (type == int[].class) {
31
+                return ArraysUtil.toString((int[]) value);
32
+            }
33
+            if (type == long[].class) {
34
+                return ArraysUtil.toString((long[]) value);
35
+            }
36
+            if (type == byte[].class) {
37
+                return ArraysUtil.toString((byte[]) value);
38
+            }
39
+            if (type == float[].class) {
40
+                return ArraysUtil.toString((float[]) value);
41
+            }
42
+            if (type == double[].class) {
43
+                return ArraysUtil.toString((double[]) value);
44
+            }
45
+            if (type == short[].class) {
46
+                return ArraysUtil.toString((short[]) value);
47
+            }
48
+            if (type == boolean[].class) {
49
+                return ArraysUtil.toString((boolean[]) value);
50
+            }
51
+            return ArraysUtil.toString((Object[]) value);
52
+        }
53
+        if (value instanceof Clob) {
54
+            Clob clob = (Clob) value;
55
+            try {
56
+                long length = clob.length();
57
+                if (length > Integer.MAX_VALUE) {
58
+                    throw new TypeConversionException("Clob is too big.");
59
+                }
60
+                return clob.getSubString(1, (int) length);
61
+            } catch (SQLException sex) {
62
+                throw new TypeConversionException(value, sex);
63
+            }
64
+        }
65
+        if (value instanceof Date) {
66
+            java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
67
+            return format1.format(value);
68
+        }
69
+
70
+        return value.toString();
71
+    }
72
+}

+ 6
- 5
SmartCommunity/SmartCommunityV1/eureka-client1/pom.xml View File

@@ -45,6 +45,12 @@
45 45
 			<artifactId>spring-cloud-starter-openfeign</artifactId>
46 46
 		</dependency>
47 47
 
48
+		<dependency>
49
+			<groupId>com.example</groupId>
50
+			<artifactId>community-common</artifactId>
51
+			<version>0.0.1</version>
52
+			<scope>compile</scope>
53
+		</dependency>
48 54
 
49 55
 		<dependency>
50 56
 			<groupId>io.springfox</groupId>
@@ -64,11 +70,6 @@
64 70
 			<version>1.3.2</version>
65 71
 		</dependency>
66 72
 
67
-		<!--<dependency>-->
68
-			<!--<groupId>mysql</groupId>-->
69
-			<!--<artifactId>mysql-connector-java</artifactId>-->
70
-			<!--<scope>runtime</scope>-->
71
-		<!--</dependency>-->
72 73
 
73 74
 		<dependency>
74 75
 			<groupId>mysql</groupId>

+ 5
- 0
SmartCommunity/SmartCommunityV1/eureka-client1/src/main/java/com/example/demo/controller/TestController.java View File

@@ -1,5 +1,6 @@
1 1
 package com.example.demo.controller;
2 2
 
3
+import com.community.commom.redis.RedisTemplate;
3 4
 import com.example.demo.microController.MicroTestController;
4 5
 import com.example.demo.model.ScUser;
5 6
 import com.example.demo.service.ScUserServiceI;
@@ -36,10 +37,14 @@ public class TestController {
36 37
     @Autowired
37 38
     private MicroTestController microTestController;
38 39
     
40
+    @Autowired
41
+    private RedisTemplate redisTemplate;
42
+    
39 43
     @ApiOperation(value = "测试无参", notes = "无参")
40 44
     @RequestMapping(value = "/hello",method = RequestMethod.GET)
41 45
     @ResponseBody
42 46
     public String index(){
47
+        redisTemplate.set("1","1");
43 48
         return abc;
44 49
     }
45 50
     

+ 2
- 1
SmartCommunity/SmartCommunityV1/pom.xml View File

@@ -15,7 +15,8 @@
15 15
 		<module>eureka-sever</module>
16 16
 		<module>zuul</module>
17 17
 		<module>user-server</module>
18
-	</modules>
18
+        <module>community-common</module>
19
+    </modules>
19 20
 
20 21
 	<name>spring-cloud</name>
21 22
 	<description>spring-cloud project for Spring Boot</description>

+ 4
- 4
SmartCommunity/SmartCommunityV1/user-server/pom.xml View File

@@ -12,10 +12,10 @@
12 12
     <description>用户工程</description>
13 13
 
14 14
     <parent>
15
-        <groupId>com.example</groupId>
16
-        <artifactId>spring-cloud</artifactId>
17
-        <version>0.0.1</version>
18
-    </parent>
15
+    <groupId>com.example</groupId>
16
+    <artifactId>spring-cloud</artifactId>
17
+    <version>0.0.1</version>
18
+</parent>
19 19
 
20 20
     <properties>
21 21
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>