package com.highdatas.mdm.util; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.annotations.TableName; import com.google.common.collect.Maps; import com.highdatas.mdm.entity.Character; import com.highdatas.mdm.entity.*; import com.highdatas.mdm.mapper.MaintainDetailMapper; import com.highdatas.mdm.mapper.TableInfoMapper; import com.highdatas.mdm.pojo.MasterAuthorType; import com.highdatas.mdm.pojo.Segment; import com.highdatas.mdm.service.*; import com.highdatas.mdm.util.pool.MqClient; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.mapping.ParameterMode; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.property.PropertyTokenizer; import org.apache.ibatis.scripting.xmltags.ForEachSqlNode; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cglib.beans.BeanMap; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.MessageDigest; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @author kimi * @description * @date 2019-12-16 15:13 */ @Slf4j @Component public class DbUtils { private static UserRoleClient userRoleClient; public static MaintainDetailMapper maintainDetailMapper; public static IMaintainService maintainService; public static IMaintainDetailService maintainDetailService; public static ISysFieldService fieldService; public static IMaintainFieldService maintainFieldService; public static TableInfoMapper tableInfoMapper; public static ISysViewService viewService; public static MasterDataService masterDataService; public static IMasterAuthorService masterAuthorService; public static ISysMenuService menuService; public static MqClient mqClient; public static ISysDispenseLogsService dispenseLogsService; public static DispenseService dispenseService; public static AntianaphylaxisClient antianaphylaxisClient; @Autowired public void setAntianaphylaxisClient(AntianaphylaxisClient antianaphylaxisClient){ DbUtils.antianaphylaxisClient = antianaphylaxisClient; } @Autowired public void setDispenseService(DispenseService dispenseService){ DbUtils.dispenseService = dispenseService; } @Autowired public void setISysDispenseLogsService(ISysDispenseLogsService dispenseLogsService){ DbUtils.dispenseLogsService = dispenseLogsService; } @Autowired public void setMqClient(MqClient mqClient){ DbUtils.mqClient = mqClient; } @Autowired public void setISysMenuService(ISysMenuService menuService){ DbUtils.menuService = menuService; } @Autowired public void setIMasterAuthorService(IMasterAuthorService masterAuthorService){ DbUtils.masterAuthorService = masterAuthorService; } @Autowired public void setMasterDataService(MasterDataService masterDataService){ DbUtils.masterDataService = masterDataService; } @Autowired public void setISysViewService(ISysViewService viewService){ DbUtils.viewService = viewService; } @Autowired public void setTableInfoMapper(TableInfoMapper tableInfoMapper){ DbUtils.tableInfoMapper = tableInfoMapper; } @Autowired public void setIMaintainFieldService(IMaintainFieldService maintainFieldService){ DbUtils.maintainFieldService = maintainFieldService; } @Autowired public void setISysFieldService(ISysFieldService fieldService){ DbUtils.fieldService = fieldService; } @Autowired public void setIMaintainDetailService(IMaintainDetailService maintainDetailService){ DbUtils.maintainDetailService = maintainDetailService; } @Autowired public void setIMaintainService(IMaintainService maintainService){ DbUtils.maintainService = maintainService; } @Autowired public void setMaintainDetailMapper(MaintainDetailMapper maintainDetailMapper){ DbUtils.maintainDetailMapper = maintainDetailMapper; } @Autowired public void setUserRoleClient(UserRoleClient userRoleClient){ DbUtils.userRoleClient = userRoleClient; } private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; public static String versionAddSub (String baseVersion) { if (StringUtils.isEmpty(baseVersion)) { return null; } String[] split = baseVersion.split(Constant.Dot); if (split.length == 1) { return null; } int smallVersion = Integer.valueOf(split[1]); smallVersion++; return MessageFormat.format("{0}.{1}",split[0], smallVersion); } public static Integer compareVersion(Maintain baseVersion, Maintain compareVersion) { if ((baseVersion == null) || (compareVersion == null)) { return null; } return baseVersion.getOrderNo().compareTo(compareVersion.getOrderNo()); } public static Integer compareVersion(MaintainField baseVersion, MaintainField compareVersion) { if ((baseVersion == null) || (compareVersion == null)) { return null; } return baseVersion.getOrderNo().compareTo(compareVersion.getOrderNo()); } public static String versionAddBig(String baseVersion) { if (StringUtils.isEmpty(baseVersion)) { return null; } String[] split = baseVersion.split(Constant.Dot); if (split.length == 1) { return null; } String bigVersionStr = split[0].substring(1); int bigVersion = Integer.valueOf(bigVersionStr); bigVersion++; return MessageFormat.format("V{0}.{1}",bigVersion, 0); } public static Map beanToMap(T bean) { Map map = Maps.newHashMap(); if (bean != null) { BeanMap beanMap = BeanMap.create(bean); for (Object key : beanMap.keySet()) { map.put(key+"", beanMap.get(key)); } } return map; } public static HashMap JsonObjectToHashMap(JSONObject jsonObj){ HashMap data = new HashMap(); Set keySet = jsonObj.keySet(); for (String key : keySet) { data.put(key, jsonObj.get(key)); } return data; } public static Integer getSubVersion(String baseVersion) { if (StringUtils.isEmpty(baseVersion)) { return null; } String[] split = baseVersion.split(Constant.Dot); if (split.length == 1) { return null; } return Integer.valueOf(split[1]); } public static Integer getBigVersion(String baseVersion) { if (StringUtils.isEmpty(baseVersion)) { return null; } String[] split = baseVersion.split(Constant.Dot); if (split.length == 0 || split[0].length() < 2) { return null; } return Integer.valueOf(split[0].substring(1)); } public static String getUUID() { String id = UUID.randomUUID().toString().replaceAll("-", ""); return id; } public static String getUUID(int i) { String id = UUID.randomUUID().toString().replaceAll("-", "").substring(0, i); return id; } public static String combieOneSegment(String name, String value) { Segment segment = new Segment(name, value); return segment.toString(); } public static String getTableNameFromEntity(Object object) { Field[] fields = object.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); // 获取表名 TableName table = object.getClass().getAnnotation(TableName.class); if (table != null) { String tableName = table.value(); return tableName; } } return null; } public static Object toSqlToJava(String value, TableSchemaResult tableSchema) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException { String dbType = tableSchema.getDbType(); String javaType = toSqlToJava(dbType); Class baseWapperClaz = Class.forName("java.lang." + javaType); Object baseWapper = baseWapperClaz.newInstance(); Method valueOfMethod = baseWapperClaz.getDeclaredMethod("valueOf"); return null; // valueOfMethod.invoke(baseWapper, ) } public static String toSqlToJava(String sqlType) { if( sqlType == null || sqlType.trim().length() == 0 ) return sqlType; sqlType = sqlType.toLowerCase(); switch(sqlType){ case "nvarchar":return "String"; case "char":return "String"; case "varchar":return "String"; case "text":return "String"; case "nchar":return "String"; case "blob":return "byte[]"; case "integer":return "Long"; case "tinyint":return "Integer"; case "smallint":return "Integer"; case "mediumint":return "Integer"; case "bit":return "Boolean"; case "bigint":return "java.math.BigInteger"; case "float":return "Fload"; case "double":return "Double"; case "decimal":return "java.math.BigDecimal"; case "boolean":return "Boolean"; case "id":return "Long"; case "date":return "java.util.Date"; case "datetime":return "java.util.Date"; case "year":return "java.util.Date"; case "time":return "java.sql.Time"; case "timestamp":return "java.sql.Timestamp"; case "numeric":return "java.math.BigDecimal"; case "real":return "java.math.BigDecimal"; case "money":return "Double"; case "smallmoney":return "Double"; case "image":return "byte[]"; default: log.error("-----------------》转化失败:未发现的类型:{0}",sqlType); break; } return sqlType; } public static void sqlValueToJava(Object value, String dbType) throws Exception { String javaType = toSqlToJava(dbType); Class baseWapperClaz = Class.forName("java.lang." + javaType); Object baseWapper = baseWapperClaz.newInstance(); Method valueOfMethod = baseWapperClaz.getDeclaredMethod("valueOf"); } public static String quotedStr(Object o) { return quotedStr(String.valueOf(o)); } public static String quotedStr(String str) { if (str != null) return "'" + str + "'"; else return "''"; } public static String bracketStr(String str) { if (str != null) return "(" + str + ")"; else return "()"; } public static String StrJoin(String... objects){ ContentBuilder builder = new ContentBuilder(Constant.EMPTY); for (String object : objects) { builder.append(object); } return builder.toString(); } public static String StrJoinLink(String link,String... objects){ ContentBuilder builder = new ContentBuilder(link); for (String object : objects) { builder.append(object); } return builder.toString(); } public static String assemblParam(String objects){ if (StringUtils.isEmpty(objects)) { return null; }else { return "@{" + objects + "}"; } } public static String getRandomString(int length) { Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(3); long result = 0; switch (number) { case 0: result = Math.round(Math.random() * 25 + 65); sb.append(String.valueOf((char) result)); break; case 1: result = Math.round(Math.random() * 25 + 97); sb.append(String.valueOf((char) result)); break; case 2: sb.append(String.valueOf(new Random().nextInt(10))); break; } } return sb.toString(); } public static int getOrderNoAdd(int orderNo) { return orderNo + 1; } public static Date getDateByStart() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date zero = calendar.getTime(); return zero; } public static Date getDateByEnd() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); Date zero = calendar.getTime(); return zero; } public static long getDistanceTime2Long(Date startTime, Date endTime) { long time1 = startTime.getTime(); long time2 = endTime.getTime(); long diff; if (time1 < time2) { diff = time2 - time1; } else { diff = time1 - time2; } return diff; } public static final String getChineseOrEnglishOrNumber(String str) { StringBuffer sbf = new StringBuffer(); char[] charArray = str.toCharArray(); for (int i = 0; i < charArray.length; i++) { if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) { sbf.append(charArray[i]); } if ((charArray[i] >= 65) && (charArray[i] <= 122)) { sbf.append(charArray[i]); } if (str.charAt(i) >= 48 && str.charAt(i) <= 57) { sbf.append(charArray[i]); } } return sbf.toString(); } public static Set matcher(String testStr) { return matcher(Constant.Default_Patter, testStr); } public static String replaceEscape(String testStr) { String new_str = Pattern.compile("\t|\r|\n| ").matcher(testStr).replaceAll(Constant.EMPTY); return new_str; } public static Set matcher(String patter, String testStr) { // String test = "@{databaseIp}:{databasePort}{instanceName};database"; // String initCompile = "(?<=@\\{)(.+?)(?=\\})"; Set ls=new HashSet<>(); Pattern pattern = Pattern.compile(patter); Matcher matcher = pattern.matcher(testStr); while(matcher.find()){ ls.add(matcher.group()); } return ls; } private static String toHexString(byte[] b) { StringBuilder sb = new StringBuilder(b.length * 2); for (int i = 0; i < b.length; i++) { sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]); sb.append(HEX_DIGITS[b[i] & 0x0f]); } return sb.toString(); } public static String Bit32(String SourceString) throws Exception { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(SourceString.getBytes()); byte messageDigest[] = digest.digest(); return toHexString(messageDigest); } public static String Bit16(String SourceString) throws Exception { return Bit32(SourceString).substring(8, 24); } public static List map2Segment(Map masterModifiedMap) { ArrayList result = new ArrayList<>(); Set keys = masterModifiedMap.keySet(); for (String key : keys) { String value = masterModifiedMap.get(key); Segment segment = new Segment(key, value); result.add(segment); } return result; } public static String getFieldRedisKey(String tableName, String field) { if (StringUtils.isEmpty(tableName) && StringUtils.isEmpty(field)) { return null; }else if (StringUtils.isEmpty(field)){ return tableName; }else if (StringUtils.isEmpty(tableName)){ return field; }else { return tableName + Constant.UnderLine + field; } } public static List split(String redisVal) { if (StringUtils.isEmpty(redisVal)) { return new ArrayList<>(); } String[] split = redisVal.split(Constant.SEMICOLON); List strings = Arrays.asList(split); return new ArrayList(strings); } public static List split(String redisVal, String spilt) { if (StringUtils.isEmpty(redisVal)) { return new ArrayList<>(); } String[] split = redisVal.split(spilt); List strings = Arrays.asList(split); return strings; } public static TUser getUser(HttpServletRequest request) { String userId = request.getParameter("userId"); if (StringUtils.isEmpty(userId)) { return (TUser) request.getSession().getAttribute(Constant.USER); } else { return getUserById(userId); } } public static Character getCharacter(HttpServletRequest request) { String characterType = request.getParameter("characterType"); if (StringUtils.isEmpty(characterType)) { return (TUser) request.getSession().getAttribute(Constant.USER); }else { String characterId = request.getParameter("characterId"); MasterAuthorType type = MasterAuthorType.valueOf(characterType); switch (type){ case role: return DbUtils.getRoleById(characterId); case user: return DbUtils.getUserById(characterId); case groupInfo: return DbUtils.getGroupById(characterId); } } return null; } private static Character getGroupById(String characterId) { return new TUserGroup().setGroupId(characterId); } private static Character getRoleById(String roleId) { return userRoleClient.getRoleByRoleId(roleId); } public static boolean addOneRole(TUser user, List roleIds) { if (user == null) { return false; } return userRoleClient.addRoleByUser(user.getUserId(), roleIds, user.getUserName()); } public static boolean groupAddOneRole(String userId, String groupId, List roleIds) { return userRoleClient.addRoleByGroupId(userId, roleIds, groupId); } public static boolean delOneRole(String userId, List roleIds) { return userRoleClient.deleteRoleByUser(userId, roleIds); } public static boolean groupDelOneRole(String groupId, List roleIds) { return userRoleClient.deleteRoleByGroupId(roleIds, groupId); } public static TUser getUserById(String userId) { TUser tUserById = userRoleClient.getTUserById(userId); return tUserById; } public static Set getRoleByGroup(String groupId) { List tRoleListByUserId = userRoleClient.getRoleListByGroupId(groupId); if (tRoleListByUserId == null || tRoleListByUserId.isEmpty()){ return new HashSet<>(); } Set collect = tRoleListByUserId.stream().map(tRole -> tRole.getRoleId()).collect(Collectors.toSet()); return collect; } public static Set getRoleByUser(String userId) { List tRoleListByUserId = userRoleClient.getTRoleListByUserId(userId); if (tRoleListByUserId == null || tRoleListByUserId.isEmpty()){ return new HashSet<>(); } Set collect = tRoleListByUserId.stream().map(tRole -> tRole.getRoleId()).collect(Collectors.toSet()); return collect; } public static Set getAllUser() { List tRoleListByUserId = userRoleClient.listUserRoleGroup(); if (tRoleListByUserId == null) { return new HashSet<>(); } return new HashSet(tRoleListByUserId); } public static Set getUserByRole(String roleId) { List userListByRole = userRoleClient.getUserListByRole(roleId); if (userListByRole == null) { return new HashSet<>(); } HashSet result = new HashSet<>(userListByRole); return result; } public static Set getGroupByUser(String userId) { List tRoleListByUserId = userRoleClient.getUserGroupByUserId(userId); if (tRoleListByUserId == null || tRoleListByUserId.isEmpty()){ return new HashSet<>(); } Set collect = tRoleListByUserId.stream().map(tRole -> tRole.getGroupId()).collect(Collectors.toSet()); return collect; } public static MyBatisSql getMyBatisSql(String id, Map parameterMap, SqlSessionFactory sqlSessionFactory) { MyBatisSql ibatisSql = new MyBatisSql(); MappedStatement ms = sqlSessionFactory.getConfiguration().getMappedStatement(id); BoundSql boundSql = ms.getBoundSql(parameterMap); ibatisSql.setSql(boundSql.getSql()); List parameterMappings = boundSql.getParameterMappings(); Configuration configuration = sqlSessionFactory.getConfiguration(); if (parameterMappings != null) { Object[] parameterArray = new Object[parameterMappings.size()]; ParameterMapping parameterMapping = null; Object value = null; Object parameterObject = null; MetaObject metaObject = null; PropertyTokenizer prop = null; String propertyName = null; String[] names = null; for (int i = 0; i < parameterMappings.size(); i++) { parameterMapping = parameterMappings.get(i); if (parameterMapping.getMode() != ParameterMode.OUT) { propertyName = parameterMapping.getProperty(); names = propertyName.split("\\."); if (propertyName.indexOf(".") != -1 && names.length == 2) { parameterObject = parameterMap.get(names[0]); propertyName = names[1]; } else if (propertyName.indexOf(".") != -1 && names.length == 3) { parameterObject = parameterMap.get(names[0]); // map if (parameterObject instanceof Map) { parameterObject = ((Map) parameterObject).get(names[1]); } propertyName = names[2]; } else { parameterObject = parameterMap.get(propertyName); } metaObject = parameterMap == null ? null : MetaObject.forObject(parameterObject,configuration.getObjectFactory(),configuration.getObjectWrapperFactory(), configuration.getReflectorFactory()); prop = new PropertyTokenizer(propertyName); if (parameterObject == null) { value = null; } else if (ms.getConfiguration().getTypeHandlerRegistry().hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else if (boundSql.hasAdditionalParameter(propertyName)) { value = boundSql.getAdditionalParameter(propertyName); } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) { value = boundSql.getAdditionalParameter(prop.getName()); if (value != null) { value = MetaObject.forObject(value,configuration.getObjectFactory(),configuration.getObjectWrapperFactory(), configuration.getReflectorFactory()).getValue(propertyName.substring(prop.getName().length())); } } else { value = metaObject == null ? null : metaObject.getValue(propertyName); } parameterArray[i] = value; } } ibatisSql.setParameters(parameterArray); } return ibatisSql; } public static String getNowDateStr() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = format.format(new Date()); return time; } public static Set getRoleByUser(String userId, String uuid) { Date start = new Date(); List tRoleListByUserId = userRoleClient.getTRoleListByUserId(userId); Date end = new Date(); log.info(MessageFormat.format("master tag:{0} form userId select role :{1} ms",uuid, (end.getTime() - start.getTime()))); if (tRoleListByUserId == null || tRoleListByUserId.isEmpty()){ return new HashSet<>(); } Set collect = tRoleListByUserId.stream() .filter(tRole -> tRole != null).map(tRole -> tRole.getRoleId()).collect(Collectors.toSet()); return collect; } public static Set getGroupByUser(String userId, String uuid) { Date start = new Date(); List tRoleListByUserId = userRoleClient.getUserGroupByUserId(userId); Date end = new Date(); log.info(MessageFormat.format("master tag:{0} form userId select group :{1} ms",uuid, (end.getTime() - start.getTime()))); if (tRoleListByUserId == null || tRoleListByUserId.isEmpty()){ return new HashSet<>(); } Set collect = tRoleListByUserId.stream().map(tRole -> tRole.getGroupId()).collect(Collectors.toSet()); return collect; } public static Set getRoleByGroup(String groupId, String uuid) { Date start = new Date(); List tRoleListByUserId = userRoleClient.getRoleListByGroupId(groupId); Date end = new Date(); log.info(MessageFormat.format("master tag:{0} form groupId select role :{1} ms",uuid, (end.getTime() - start.getTime()))); if (tRoleListByUserId == null || tRoleListByUserId.isEmpty()){ return new HashSet<>(); } Set collect = tRoleListByUserId.stream().map(tRole -> tRole.getRoleId()).collect(Collectors.toSet()); return collect; } }