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 getHttpRequestParams(HttpServletRequest request, Class 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 jsonToObject(String json, Class clazz) { // return new Gson().fromJson(json, clazz); return JSONObject.parseObject(json,clazz); } /** * json转list对象 * @param json * @param clazz * @return */ @SuppressWarnings("unchecked") public static List jsonToList(String json,Class clazz){ return (List) JSONObject.parseArray(json, clazz); } /** * map 对象转bean对象 用于统一处理接口输入参数 * @param map * @param clazz * @param isUpper Map的key值是否为大写类型 ture: USER_ID,false:userId * @return */ public static T mapToBean(Map map, Class 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 * @return */ public static 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 * @param list 对象 * @param name 作为map的key的 属性 * @return */ public static Map listToMap(List list, String name) { HashMap 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 * @return */ public static T copyBeanProperties(Object source,Class 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 list,String sep){ if(CollectionUtils.isEmpty(list)){ return null; } int size = list.size(); StringBuilder builder = new StringBuilder(); for(int i=0;i