xiaoyong931011
2020-11-30 78d39c4e43c80ea16cc96dc73d60c8880ac5020d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package com.xcong.excoin.utils;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
 
/**
 * 工具类
 * @add 20190828 添加时间转换方法
 * @author 敢超
 *
 */
public class ToolUtil {
 
    private static Logger log = LoggerFactory.getLogger(ToolUtil.class);
 
    /*
     * 字符串正则匹配方法(用于匹配字符串是否包含指定字符串)
     */
    public static boolean stringFilter(String string, String regex) {
        Pattern p = Pattern.compile(regex);
        return p.matcher(string).matches();
    }
 
    /**
     * 将http传过来的数据转化成实体
     *
     * @param request
     * @param clazz
     * @return
     */
    public static <T> T getHttpRequestParams(HttpServletRequest request, Class<T> clazz) {
        T bean = null;
        try {
            bean = clazz.newInstance();
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                String methodName = method.getName();
                if (methodName.startsWith("set")) {
                    String key = methodName.substring(3);
                    key = key.substring(0, 1).toLowerCase() + key.substring(1);
                    String value = request.getParameter(key);
                    if (value != null) {
                        method.invoke(bean, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }
 
    /**
     * 实体转json字符串
     * @param obj
     * @return
     */
    public static String objToJson(Object obj) {
        return JSONObject.toJSONString(obj);
    }
 
    /**
     * json字符串转对象
     * @param json  json格式的字符串
     * @param clazz
     * @return
     */
    public static <T> T jsonToObject(String json, Class<T> clazz) {
        //    return new Gson().fromJson(json, clazz);
        return JSONObject.parseObject(json,clazz);
    }
 
    /**
     * json转list对象
     * @param json
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> jsonToList(String json,Class<?> clazz){
        return (List<T>) JSONObject.parseArray(json, clazz);
    }
 
    /**
     * map 对象转bean对象 用于统一处理接口输入参数
     * @param map
     * @param clazz
     * @param isUpper Map的key值是否为大写类型 ture: USER_ID,false:userId
     * @return
     */
    public static <T> T mapToBean(Map map, Class<T> clazz, boolean isUpper) {
        T t = null;
        try {
            t = clazz.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (map.containsKey(key)) {
                    Object value = map.get(key);
                    Method setter = property.getWriteMethod();
                    if(setter != null && value != null){
                        if(value.getClass().equals(setter.getParameterTypes()[0])){
                            setter.invoke(t, value);
                        }else if(Date.class.equals(setter.getParameterTypes()[0]) && Number.class.isAssignableFrom(value.getClass())){
                            setter.invoke(t,new Date(((Number)value).longValue()));
                        }else {
                            log.warn("【mapToBean】"+key+" 类型不匹配,没有转化");
                        }
                    }else {
                        log.warn("【mapToBean】"+key+" 不存在写入方法,或值不存在,没有转化");
                    }
 
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
 
    /**
     *    实体bean 转换成map
     * @param object
     * @param <T>
     * @return
     */
    public static <T> Map beanToMap(T object){
        Map map = new HashMap();
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if("class".equals(key)){
                    continue;
                }
                Object temp = property.getReadMethod().invoke(object);
                if(temp != null){
                    map.put(key,temp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            map = null;
        }
        return map;
    }
 
    /**
     * 大写字母转小写
     * @param str USER_ID 转小写 userId
     * @return
     */
    public static String strToLowerCase(String str) {
        String s1 = str.toLowerCase();
        if (s1.indexOf("_") != -1) {
            StringBuffer sb = new StringBuffer();
            String[] strs = s1.split("_");
            for (String temp : strs) {
                if (sb.length() == 0) {
                    sb.append(temp);
                } else {
                    char[] cs = temp.toCharArray();
                    cs[0] -= 32;
                    sb.append(String.valueOf(cs));
                }
            }
            s1 = sb.toString();
        }
        return s1;
    }
 
    /**
     * list对象转换成Map<String,T>
     * @param list 对象
     * @param name 作为map的key的 属性
     * @return
     */
    public static <T> Map<String, T> listToMap(List<T> list, String name) {
        HashMap<String, T> map = new HashMap<>();
        if(CollectionUtils.isNotEmpty(list)){
            try {
                if(Map.class.isAssignableFrom(list.get(0).getClass())){
                    for(T object : list){
                        Map temp = (Map) object;
                        String key = (String) temp.get(name);
                        map.put(key,object);
                    }
                }else {
                    char[] cs = name.toCharArray();
                    cs[0] -= 32;
                    String getMethod = "get" + String.valueOf(cs);
                    Method method = list.get(0).getClass().getMethod(getMethod);
                    for (T object : list) {
                        String str = (String) method.invoke(object);
                        map.put(str, object);
                    }
                }
            } catch (Exception e) {
                log.error("listToMap 数据转换出错!");
                e.printStackTrace();
            }
        }
        return map;
    }
 
 
    /**
     * 打印异常堆栈
     * @param e
     * @return
     */
    public static String printExceptionDetail(Exception e){
        String result = "";
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw =  new PrintWriter(sw);
            //将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            result = sw.toString();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return result;
    }
 
 
 
    /**
     * 复制bean属性
     * @param source
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T copyBeanProperties(Object source,Class<T> type){
        T t = null;
        try {
            t = type.newInstance();
            PropertyUtils.copyProperties(t,source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
 
    /**
     * 模拟oracle数据库的decode
     * @param source
     * @param match 比配参数,参数个数必须是2的倍数,没有匹配到直接返回原字符串
     * @return
     */
    public static String decodeStr(String source,String... match){
        if(source == null){
            return null;
        }
        if(match == null || match.length%2 != 0){
            throw new RuntimeException("ToolUtil.decodeStr的match参数错误");
        }
        for(int i = 0;i < match.length;i++){
            if(source.equals(match[i])){
                return match[i+1];
            }
            i++;
        }
        return source;
    }
 
    /**
     * 根据属性,获取get方法
     * @param ob 对象
     * @param name 属性名
     * @return
     * @throws Exception
     */
    public static Object getGetMethod(Object ob , String name)throws Exception{
        Method[] m = ob.getClass().getMethods();
        for(int i = 0;i < m.length;i++){
            if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
                return m[i].invoke(ob);
            }
        }
        return null;
    }
 
    /**
     * 获取格式化后的时间
     * @param date
     * @param pattern
     * @return
     */
    public static String getStringDate(Date date,String pattern){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }
 
    /**
     * 去除字符串的前后空格
     * @author zhangheng
     * @date 2020-04-23
     * @param param
     * @return java.lang.String
     */
    public static String trimString(String param){
        if(StringUtils.isBlank(param)){
            return null;
        }
        return param.trim();
    }
 
    public static String listToString(List<String> list,String sep){
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        int size = list.size();
        StringBuilder builder = new StringBuilder();
        for(int i=0;i<size;i++){
            if(i==0){
                builder.append(list.get(i));
            }else{
                builder.append(sep+list.get(i));
            }
        }
        return builder.toString();
    }
 
}