package com.engine.salary.elog.service.impl; import cn.hutool.core.date.DateUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.engine.salary.elog.dto.ElogBean; import com.engine.salary.elog.dto.FilterConditionDto; import com.engine.salary.elog.dto.LoggerContext; import com.engine.salary.elog.dto.ShowColumsDto; import com.engine.salary.elog.service.ILoggerTableService; import com.engine.salary.elog.util.ElogServiceUtils; import com.engine.salary.elog.util.ElogSeviceUtils; import com.engine.salary.mapper.elog.LocalElogDaoMapper; import com.weaver.common.batch.consts.FileType; import com.weaver.common.batch.consts.HandlerFileMethod; import com.weaver.common.batch.entity.BatchDocumentMessage; import com.weaver.common.batch.entity.BatchFile; import com.weaver.common.batch.entity.ExcelSheet; import com.weaver.common.batch.sender.BatchExportSender; import com.weaver.common.cache.tablecache.impl.ComInfoCache; import com.weaver.common.component.table.WeaTable; import com.weaver.common.component.table.column.WeaTableColumn; import com.weaver.common.component.table.page.Page; import com.weaver.common.distribution.genid.IdGenerator; import com.weaver.common.elog.annotation.HandleElog; import com.weaver.common.elog.annotation.OperateType; import com.weaver.common.elog.annotation.handle.ElogMethodHandler; import com.weaver.common.elog.annotation.handle.MethodHandler; import com.weaver.common.elog.consts.ElogEsTableConsts; import com.weaver.common.elog.dao.QueryCommonTabeMapper; import com.weaver.common.elog.dto.*; import com.weaver.common.elog.enums.ElogConsts; import com.weaver.common.elog.service.ApplicationContextProvider; import com.weaver.common.elog.service.ElogHandleService; import com.weaver.common.elog.util.*; import com.weaver.common.hrm.cache.HrmAvatarComInfo; import com.weaver.common.hrm.cache.HrmEmployeeComInfo; import com.weaver.common.hrm.domain.organization.HrmConditionResultType; import com.weaver.common.hrm.domain.organization.HrmOrgEmpCondition; import com.weaver.common.hrm.entity.employee.HrmEmployee; import com.weaver.common.hrm.service.HrmCommonEmployeeService; import com.weaver.common.hrm.util.HrmCommonUtil; import com.weaver.common.hrm.util.HrmI18nUtil; import com.weaver.common.i18n.label.SystemEnv; import com.weaver.common.i18n.tool.config.date.format.DateRangeTransformer; import com.weaver.common.i18n.tool.util.I18nUtil; import com.weaver.common.mybatis.baseConfig.WeaDatabaseIdProvider; import com.weaver.common.mybatis.util.DatabaseUtil; import com.weaver.common.security.util.SecurityUtil; import com.weaver.framework.rpc.context.impl.TenantRpcContext; import com.weaver.teams.security.context.UserContext; import com.weaver.teams.security.user.User; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.elasticsearch.action.admin.indices.get.GetIndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.xcontent.XContentType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.AnnotationUtils; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static com.weaver.common.elog.consts.LogConstants.MAPPING_TEMPLATE; public class LoggerTableService implements ILoggerTableService { private static final Logger logger = LoggerFactory.getLogger(LoggerTableService.class); @Autowired private LocalElogDaoMapper localElogDaoMapper; @Autowired private ComInfoCache comInfoCache; @Autowired private HrmCommonUtil hrmCommonUtil; @Autowired private QueryCommonTabeMapper queryCommonTabeMapper; @Autowired private RestHighLevelClient restHighLevelClient; @Resource private BatchExportSender batchExportSender; @Resource private DateRangeTransformer dateRangeTransformer; @Autowired private HrmCommonEmployeeService hrmCommonEmployeeService; private static final String databaseId = DatabaseUtil.getDatabaseId(); @Override public WeaTable queryLogs(String data) { //解析数据 ElogBean elogBean = ElogServiceUtils.getElogBean(data); // columIndex统一转为小写 Optional.ofNullable(elogBean.getShowColumns()) .ifPresent(list -> { list.forEach(x -> { if (StringUtils.isNotBlank(x.getColumIndex())) { x.setColumIndex(x.getColumIndex().toLowerCase()); } }); }); List showColums = elogBean.getShowColumns(); String module = elogBean.getModule(); String function = elogBean.getFunction(); String searchMap = elogBean.getSearchMap(); String pageSize = elogBean.getPageSize(); String pageNum = elogBean.getPageNum(); String downloadSize = elogBean.getDownloadSize(); List filterConditionDtos = elogBean.getFilterConditionDtos(); String transMethod = elogBean.getTransMethod(); Map authParamsJson = elogBean.getAuthParamsJson(); //获取 context 数据 LoggerContext context = new LoggerContext(); context.setModuleName(module); context.setFunctionName(function); context.setTenant_key(getTenantKey()); // context.setOperator(getEmployeeId()); //获取主表 String tableName = ElogSeviceUtils.getTableName(module, function); //获取weaTable WeaTable weaTable = new WeaTable(); List recordColumns = getWeaColumns(data, showColums, module, function, weaTable); //获取条件sql String searchMapsql = getSearchMapSql(searchMap, module, function,elogBean.getShowColumns()); String sb = getQueryCondition(filterConditionDtos); sb = searchMapsql.concat(sb); //处理数据权限 Map res = getCustomAuthSql(transMethod, authParamsJson, "auth"); if (!res.isEmpty()) { Object flag = res.get("flag"); if (flag != null && flag instanceof Boolean) { boolean f = (boolean) flag; if (!f) { weaTable.setCustomParameters(res); return weaTable; } } } String customSql = getCustomSql(transMethod, sb, "before"); //处理数据权限(前缀) Map hashMap = addPermissionHandler(transMethod); logger.info("查询条件sql:{}", customSql); //处理数据权限(对接权限sql) PermissionParams permissionParams = getPermissionParams(hashMap); String permissionId = permissionParams.getPermissionId(); String permissionType = permissionParams.getPermissionType(); String mainDataTable = permissionParams.getMainDataTable(); String mainDataTableAlias = permissionParams.getMainDataTableAlias(); String primaryKey = permissionParams.getPrimaryKey(); String permissionTargetId = permissionParams.getPermissionTargetId(); String permissionConfigSourceId = permissionParams.getPermissionConfigSourceId(); // 设置操作菜单 //weaTable.getOperates().add(new WeaTableOperate("查看", 1)); // 分页 //Page page = ElogSeviceUtils.getPage(); Page page = null; if (StringUtils.isEmpty(downloadSize)) { page = new Page(ElogSeviceUtils.getIntValue(pageNum, 1), ElogSeviceUtils.getIntValue(pageSize, 10)); } else { int pagesize = ElogSeviceUtils.getIntValue(downloadSize, 5000); page = new Page(1, pagesize); } String columns = getshowColumsStr(showColums); Map countMap = new HashMap<>(); Long countNum = 0l; //最终查询前 List interceptChain = ApplicationContextProvider.getServiceBean(ElogHandleService.class) .stream().filter(Objects::nonNull) .filter(x -> x instanceof ElogHandleService) .map(x -> (ElogHandleService) x) .collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(interceptChain)) { for (ElogHandleService handleService : interceptChain) { Class itemClass = handleService.getClass(); HandleElog annotation = itemClass.getAnnotation(HandleElog.class); if(Objects.isNull(annotation)){ annotation = AnnotationUtils.findAnnotation(itemClass, HandleElog.class); } if(Objects.nonNull(annotation)){ if(module.equalsIgnoreCase(annotation.modulename())){ String employeeId = getUserId(); long id = StringUtils.isEmpty(employeeId) ? -1 : Long.parseLong(employeeId); ElogHandleDto elogHandleDto = new ElogHandleDto(module,function,context.getTenant_key(),id,customSql,filterConditionDtos); boolean preQuery = handleService.preQuery(elogHandleDto); customSql = elogHandleDto.getSql(); } } } } // 查询 List list = new ArrayList<>(); if (StringUtils.isNotEmpty(permissionId) || StringUtils.isNotEmpty(permissionType) || StringUtils.isNotEmpty(mainDataTableAlias) || StringUtils.isNotEmpty(mainDataTable) || StringUtils.isNotEmpty(permissionTargetId) || StringUtils.isNotEmpty(permissionConfigSourceId)) { list = localElogDaoMapper.queryElogList(page, context, null, tableName, customSql, mainDataTable, permissionId, permissionType, mainDataTableAlias, primaryKey,permissionTargetId,permissionConfigSourceId,"*"); countNum = localElogDaoMapper.elogCountOnlyNum(context, tableName, customSql, mainDataTable, permissionId, permissionType, mainDataTableAlias, primaryKey,permissionTargetId,permissionConfigSourceId); } else { list = localElogDaoMapper.queryElogList(page, context, null, tableName, customSql,"*"); countMap = localElogDaoMapper.elogCount(context, tableName, customSql); } String databaseId = WeaDatabaseIdProvider.databaseId; if ("st".equals(databaseId)) { //st数据库 date类型特殊处理 list.forEach(map -> { map.forEach((k, v) -> { if (v instanceof Date) { map.put(k, DateUtil.format((Date) v, "yyyy-MM-dd HH:mm:ss")); } }); }); } String propertiesValue = module + "." + function + ".es"; String value = ApplicationContextProvider.getPropertiesValue(propertiesValue); logger.info("propertiesValue:{},value:{}", propertiesValue,value); if (StringUtils.isNotEmpty(value) && !value.equalsIgnoreCase("${" + propertiesValue + "}")) { //if判断通过说明走了自定义ES存储es String[] fields = getESfields(value); if (fields != null && fields.length > 0) { for (Map map : list) { String logDate = map.get("log_date").toString(); logger.info("logDate:{}" ,logDate); String esDate = logDate.substring(0, 10); //先判断表存不存在,不存在创建 if (checkEsTableIsExist(esDate)) { // 根据id通过es查询大字段(params)然后赋值 SearchRequest searchRequest = new SearchRequest(getElogESTableName(true,esDate)); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 只获取指定字段 searchSourceBuilder.fetchSource(fields, null); // 根据id匹配 searchSourceBuilder.query(QueryBuilders.termQuery("id",map.get("id").toString())); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = null; try { searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); } catch (IOException e) { logger.info("查询ES出现异常:{}",e.getMessage()); } SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); if (searchHits != null && searchHits.length > 0) { // 根据id匹配唯一,所以直接取第一个 Map sourceAsMap = searchHits[0].getSourceAsMap(); if (Objects.nonNull(sourceAsMap) && sourceAsMap.size() > 0) { logger.info("ES查出来的sourceAsMap:{}",JSON.toJSONString(sourceAsMap)); map.putAll(sourceAsMap); } } } } } } //处理转换其他数据库类型值 list = ElogSeviceSwitchUtils.getSwitchDatabaseData(list); //处理用户信息Data // 大小写转换 ElogSeviceSwitchUtils.changKey2Lower(list); transSwitchDataInfo(list,recordColumns); //转换多语言 //ElogSeviceSwitchUtils.switchValues(list, recordColumns, true); //ElogSeviceSwitchUtils.switchChangeValues(list); logger.info("开始执行转换方法"); if (Util.isNotEmpty(transMethod)) { logger.info("转换方法:{}", transMethod); // 消费到消息,通过MethodHandler调用对应的方法 MethodHandler methodHandler = ElogMethodHandler.loadMethodHandler(transMethod); if (methodHandler != null) { try { logger.info("执行方法前的数据:{}", JSON.toJSONString(list)); methodHandler.execute(list); logger.info("执行方法后的数据:{}", JSON.toJSONString(list)); } catch (Exception e) { logger.error("转换出错:" + e); } } } page.setTotal(ElogSeviceUtils.getLongValue(countMap.get("counts") + "", 0)); page.setRecords(switchString(list)); if (!countNum.equals(0l)) { //countNum不为0 则覆盖 page.setTotal(countNum); } // 处理后的数据 // weaTable.setDisplayData(DataTransform.userProcessData(page.getRecords())); // 处理操作菜单权限 //weaTable.setOperatesPermission(DataTransform.userOperatesPermission(page.getRecords())); // 处理选择框权限 //weaTable.setCheckBoxPermission(DataTransform.userCheckBoxPermission(page.getRecords())); // 存放结果集 weaTable.setPage(page); return weaTable; } @Override public WeaTable queryLogsPapi(String data, HttpServletRequest request) { return null; } @Override public List getDetailChangesPapi(String module, String function, String mainid, String transMethod, HttpServletRequest request) { return null; } private String getshowColumsStr(List showColums) { StringBuffer sb = new StringBuffer(); sb.append("id,uuid,targetid,params,operatetype,link_id,link_type,"); for (ShowColumsDto showColum : showColums) { String columIndex = showColum.getColumIndex(); if ("date".equalsIgnoreCase(columIndex) || "createdate".equalsIgnoreCase(columIndex)){ columIndex = "log_date"; }else if ("operator".equalsIgnoreCase(columIndex)){ columIndex = "log_operator"; }else if ("modulenamespan".equalsIgnoreCase(columIndex)){ columIndex = "modulename"; } else if ("functionnameespan".equalsIgnoreCase(columIndex)){ columIndex = "functionname"; } else if ("avatar".equals(columIndex)) { continue; } sb.append(columIndex).append(","); } String substring = sb.toString().substring(0, sb.toString().length() - 1); return substring; } private PermissionParams getPermissionParams(Map hashMap) { PermissionParams permissionParams = new PermissionParams(); String permissionId = getPermissionStr(hashMap, "permissionId"); String permissionType = getPermissionStr(hashMap, "permissionType"); String mainDataTableAlias = getPermissionStr(hashMap, "mainDataTableAlias"); String mainDataTable = getPermissionStr(hashMap, "mainDataTable"); String primaryKey = getPermissionStr(hashMap, "primaryKey"); String permissionTargetId = getPermissionStr(hashMap, "permissionTargetId"); String permissionConfigSourceId = getPermissionStr(hashMap, "permissionConfigSourceId"); permissionParams.setPermissionId(permissionId); permissionParams.setPermissionType(permissionType); permissionParams.setMainDataTableAlias(mainDataTableAlias); permissionParams.setMainDataTable(mainDataTable); permissionParams.setPrimaryKey(primaryKey); permissionParams.setPermissionTargetId(permissionTargetId); permissionParams.setPermissionConfigSourceId(permissionConfigSourceId); return permissionParams; } private List getWeaColumns(String data, List showColums, String module, String function, WeaTable weaTable) { // 每一个Table的唯一标识 weaTable.setPageUid(IdGenerator.generate() + ""); // 表头 //weaTable.getColumns().add(new WeaTableColumn("id","id", true)); List recordColumns = new ArrayList<>(); if (showColums != null && showColums.size() > 0) { for (ShowColumsDto showColum : showColums) { if (showColum.isTransfLanguage()) { recordColumns.add(showColum.getColumIndex()); } if (StringUtils.isNotBlank(showColum.getAliasColumName())) { WeaTableColumn weaTableColumn = new WeaTableColumn(showColum.getAliasColumName(), showColum.getColumIndex(), getColumnsWidth(showColum), "", showColum.isHide()); if (showColum.isNewLine()) { weaTableColumn.setNewLine(showColum.isNewLine()); } weaTable.getColumns().add(weaTableColumn); } else if (StringUtils.isNotBlank(showColum.getColumName())) { WeaTableColumn weaTableColumn = new WeaTableColumn(FieldNameMap.getMainFieldNameMap(data, function, showColum.getColumName()), showColum.getColumIndex(), getColumnsWidth(showColum), "", showColum.isHide()); if (showColum.isNewLine()) { weaTableColumn.setNewLine(showColum.isNewLine()); } weaTable.getColumns().add(weaTableColumn); } } } else { weaTable.getColumns().add(new WeaTableColumn(FieldNameMap.getMainFieldNameMap(module, function, "moduleName"), "modulenamespan", "5%")); weaTable.getColumns().add(new WeaTableColumn(FieldNameMap.getMainFieldNameMap(module, function, "functionName"), "functionnamespan", "5%")); weaTable.getColumns().add(new WeaTableColumn(FieldNameMap.getMainFieldNameMap(module, function, "clientIp"), "clientip", "5%")); weaTable.getColumns().add(new WeaTableColumn(FieldNameMap.getMainFieldNameMap(module, function, "operateTypeName"), "operatetypename", "5%")); weaTable.getColumns().add(new WeaTableColumn(FieldNameMap.getMainFieldNameMap(module, function, "targetName"), "targetname", "5%")); weaTable.getColumns().add(new WeaTableColumn(FieldNameMap.getMainFieldNameMap(module, function, "date"), "createdate", "5%")); weaTable.getColumns().add(new WeaTableColumn(FieldNameMap.getMainFieldNameMap(module, function, "operatorName"), "operatorname", "5%")); } return recordColumns; } private String getTargetid(List filterConditionDtos) { if (!filterConditionDtos.isEmpty()) { for (FilterConditionDto filterConditionDto : filterConditionDtos) { if ("targetid".equalsIgnoreCase(filterConditionDto.getColumIndex())) { return filterConditionDto.getValue(); } } } return ""; } private String getPermissionStr(Map hashMap, String str) { if (hashMap != null && hashMap.size() > 0) { Object obj = hashMap.get(str); if (obj != null) { return obj.toString(); } } return ""; } /** * 处理数据权限 * * @param transMethod * @return */ private Map addPermissionHandler(String transMethod) { Map hashMap = new HashMap(); hashMap.put("permissionId", ""); hashMap.put("permissionType", ""); hashMap.put("mainDataTableAlias", ""); hashMap.put("mainDataTable", ""); hashMap.put("primaryKey", ""); hashMap.put("permissionTargetId", ""); hashMap.put("permissionConfigSourceId", ""); MethodHandler beforeMethodHandler = ElogMethodHandler.loadMethodHandler("permission" + transMethod); if (beforeMethodHandler != null) { try { Object execute = beforeMethodHandler.execute(hashMap); if (execute != null) { if (execute instanceof Map) { return (Map) execute; } } } catch (Exception e) { logger.error("转换出错:" + e); throw new RuntimeException(e.getMessage()); } } return hashMap; } private Map getCustomAuthSql(String transMethod, Map params, String prefix) { MethodHandler beforeMethodHandler = ElogMethodHandler.loadMethodHandler(prefix + transMethod); Map hashMap = new HashMap<>(); if (beforeMethodHandler != null) { try { hashMap.put("flag", true); hashMap.put("msg", ""); hashMap.putAll(params); Object execute = beforeMethodHandler.execute(hashMap); if (execute != null && execute instanceof Map) { Map map = (Map) execute; return map; } } catch (Exception e) { logger.error("转换出错:" + e); throw new RuntimeException(e.getMessage()); } } return hashMap; } private String getCustomSql(String transMethod, String sql, String prefix) { MethodHandler beforeMethodHandler = ElogMethodHandler.loadMethodHandler(prefix + transMethod); boolean flag = false; if (beforeMethodHandler != null) { try { String subSql = ""; if (sql.length() > 5) { flag = true; subSql = sql.substring(5, sql.length()); } Object execute = beforeMethodHandler.execute(subSql); if (execute != null) { if (execute instanceof String) { StringBuffer sb = null; if(execute.toString().length()==0){ sb = new StringBuffer(); } else if (flag || execute.toString().length() > 0) { sb = new StringBuffer(" and "); } else { sb = new StringBuffer(); } sb.append(execute.toString()); return sb.toString(); } } } catch (Exception e) { logger.error("转换出错:" + e); throw new RuntimeException(e.getMessage()); } } return sql; } private void transUserInfo(List list) { List operators = new ArrayList<>(); if (list != null && list.size() > 0) { for (Map map : list) { //避免暴露内网地址 map.remove("requesturl"); Object operator = map.get("operator"); if (operator != null && StringUtils.isNotBlank(operator.toString())) { operators.add(ElogSeviceUtils.getLongValue(operator.toString())); } } } List cacheList = comInfoCache.getCacheList(HrmEmployeeComInfo.class, operators); Map infoHashMap = new HashMap<>(); if (cacheList != null && cacheList.size() > 0) { for (HrmEmployeeComInfo hrmEmployeeComInfo : cacheList) { HrmAvatarComInfo hrmAvatarComInfo = (HrmAvatarComInfo) comInfoCache.getCacheById(HrmAvatarComInfo.class, hrmEmployeeComInfo.getAvatar()); ElogHrmSimpleEmployeeInfo info = new ElogHrmSimpleEmployeeInfo(); if (hrmAvatarComInfo != null) { info.setAvatarP3Id(hrmAvatarComInfo.getP3()); } info.setId(hrmEmployeeComInfo.getId()); info.setUserName(hrmEmployeeComInfo.getUsername()); infoHashMap.put(hrmEmployeeComInfo.getId(), info); } } if (list != null && list.size() > 0) { for (Map map : list) { Object operator = map.get("operator"); if (map.get("params") != null && map.get("params").toString().startsWith("H4s")) { map.put("params", ElogSeviceUtils.uncompress(map.get("params").toString())); } map.put("dboperatorname", Util.null2String(map.get("operatorname"))); if (operator != null && StringUtils.isNotBlank(operator.toString())) { Map i18nOperatorMap = new HashMap<>(); ElogHrmSimpleEmployeeInfo hrmEmployeeComInfo = infoHashMap.get(Long.parseLong(operator.toString())); if (hrmEmployeeComInfo != null) { //获取最新的人员名称并进行多语言转换 i18nOperatorMap.put(Long.parseLong(operator.toString()),hrmEmployeeComInfo.getUserName()); Map parseI18nOperator = HrmI18nUtil.batchCovertEmployee(i18nOperatorMap, map.get("tenant_key").toString()); map.put("operatorname", parseI18nOperator.get(Long.parseLong(operator.toString()))); // if (StringUtils.isNotEmpty(hrmEmployeeComInfo.getUserName())) { // map.put("operatorname", hrmEmployeeComInfo.getUserName()); // } if (hrmEmployeeComInfo.getAvatarP3Id() != null) { map.put("avatar", hrmEmployeeComInfo.getAvatarP3Id()); } } } } } } private void transSwitchDataInfo(List list, List recordColumns) { List operators = new ArrayList<>(); if (list != null && list.size() > 0) { for (Map map : list) { //避免暴露内网地址 map.remove("requesturl"); map.put("dboperatorname", Util.null2String(map.get("operatorname"))); ElogSeviceSwitchUtils.switchDatabaseField(map); Object operator = map.get("operator"); if (operator != null && StringUtils.isNotBlank(operator.toString())) { operators.add(ElogSeviceUtils.getLongValue(operator.toString())); } if (map.get("PARAMS") != null) { map.put("params", JSONObject.toJSON(map.get("PARAMS"))); } else if (map.get("params") != null) { map.put("params", JSONObject.toJSON(map.get("params"))); } for (String recordColumn : recordColumns) { Object val = map.get(recordColumn); if (val != null) { map.put(recordColumn, ElogSeviceSwitchUtils.transfi18Method(val.toString())); } } Object modulename = map.get("modulename"); if (modulename != null) { map.put("modulenamespan", ElogSeviceSwitchUtils.getModuleName(modulename.toString())); } } } List cacheList = comInfoCache.getCacheList(HrmEmployeeComInfo.class, operators); Map infoHashMap = new HashMap<>(); if (cacheList != null && cacheList.size() > 0) { for (HrmEmployeeComInfo hrmEmployeeComInfo : cacheList) { ElogHrmSimpleEmployeeInfo info = new ElogHrmSimpleEmployeeInfo(); info.setId(hrmEmployeeComInfo.getId()); info.setUserName(hrmEmployeeComInfo.getUsername()); infoHashMap.put(hrmEmployeeComInfo.getId(), info); } } if (list != null && list.size() > 0) { for (Map map : list) { Object operator = map.get("operator"); if (map.get("params") != null && map.get("params").toString().startsWith("H4s")) { map.put("params", ElogSeviceUtils.uncompress(map.get("params").toString())); map.put("params",SecurityUtil.encodeForHtml(map.get("params").toString(), true)); } //获取最新的人员名称并进行多语言转换 if (operator != null && StringUtils.isNotBlank(operator.toString())) { Map i18nOperatorMap = new HashMap<>(); ElogHrmSimpleEmployeeInfo hrmEmployeeComInfo = infoHashMap.get(Long.parseLong(operator.toString())); if (hrmEmployeeComInfo != null && StringUtils.isNotEmpty(hrmEmployeeComInfo.getUserName())) { i18nOperatorMap.put(Long.parseLong(operator.toString()),hrmEmployeeComInfo.getUserName()); Map parseI18nOperator = HrmI18nUtil.batchCovertEmployee(i18nOperatorMap, map.get("tenant_key").toString()); map.put("operatorname", parseI18nOperator.get(Long.parseLong(operator.toString()))); // map.put("operatorname", hrmEmployeeComInfo.getUserName()); } } } } } /** * 查询头像相关信息 * * @param id * @return */ // private String queryAvatarInfo(long id) { // Map avatarInfoMap = queryAvatarInfoMapper.queryAvatarInfo(id); // if (avatarInfoMap != null) { // if (avatarInfoMap.get("p3") != null) { // return avatarInfoMap.get("p3").toString(); // } // } // return ""; // } /** * 获取宽度 * * @param showColum * @return */ private String getColumnsWidth(ShowColumsDto showColum) { if (StringUtils.isBlank(showColum.getWidth())) { return "5%"; } else { return showColum.getWidth(); } } private String getTenantKey() { User currentUser = UserContext.getCurrentUser(); if (currentUser != null) { return currentUser.getTenantKey(); } else { String tenantKey = TenantRpcContext.getTenantKey(); if (StringUtils.isNotBlank(tenantKey)) { return tenantKey; } } return ""; } private String getEmployeeId() { User currentUser = UserContext.getCurrentUser(); if (currentUser != null&&!currentUser.isAdmin()) { String employeeId = TenantRpcContext.getEmployeeId(); return StringUtils.isNotBlank(employeeId) ? employeeId : ""; } return ""; } private String getUserId(){ User currentUser = UserContext.getCurrentUser(); if (currentUser != null) { return currentUser.getEmployeeId().toString(); } String employeeId = TenantRpcContext.getEmployeeId(); return StringUtils.isNotBlank(employeeId) ? employeeId : ""; } /** * 拼接搜索条件 * * @param searchMap * @param module * @param function * @return */ private String getSearchMapSql(String searchMap, String module, String function, List showColumns) { StringBuffer sb = new StringBuffer(); Map map = JSON.parseObject(searchMap); if (map == null) return sb.toString(); Iterator> iterators = map.entrySet().iterator(); while (iterators.hasNext()) { Map.Entry next = iterators.next(); String key = next.getKey(); SecurityUtil.sqlCheck(key); if ("date".equals(key) || "createdate".equals(key)) { Object date = next.getValue(); if (date != null) { if (StringUtils.isNotBlank(date.toString())) { List dates = (List) date; if (dates != null && dates.size() == 2) { Object startDate = dates.get(0); Object endDate = dates.get(1); startDate = ElogSeviceUtils.checkValSql(startDate.toString()); endDate = ElogSeviceUtils.checkValSql(endDate.toString()); if (StringUtils.isNotBlank(startDate.toString()) && StringUtils.isNotBlank(endDate.toString())) { startDate = startDate.toString().replaceAll("'", "''"); endDate = endDate.toString().replaceAll("'", "''"); String dateRangeAfter = dateRangeTransformer.getDateRangeAfter(startDate.toString()); String dateRangeBefore = dateRangeTransformer.getDateRangeBefore(endDate.toString()); sb.append(" and log_date ").append(" between ").append(getSwithDatabaseDate(dateRangeAfter)).append(" and ").append(getSwithDatabaseDate(dateRangeBefore)).append(" "); } else if (StringUtils.isNotBlank(startDate.toString())) { String dateRangeAfter = dateRangeTransformer.getDateRangeAfter(startDate.toString()); sb.append(" and log_date ").append(" >= ").append(getSwithDatabaseDate(dateRangeAfter)).append(" "); } else if (StringUtils.isNotBlank(endDate.toString())) { String dateRangeBefore = dateRangeTransformer.getDateRangeBefore(endDate.toString()); sb.append(" and log_date ").append(" <= ").append(getSwithDatabaseDate(dateRangeBefore)).append(" "); } } } } } else if ("operator".equals(next.getKey())) { Object operator = next.getValue(); if (operator != null) { if (StringUtils.isNotBlank(operator.toString())) { operator = ElogSeviceUtils.checkValSql(operator.toString()); operator = operator.toString().replaceAll("'", "''"); if (StringUtils.isNumeric(operator.toString()) && operator.toString().length() > 15 ) { sb.append(" and log_operator = ").append(operator.toString()).append(" "); } else { List likeNameHrmEmployeeList = hrmCommonEmployeeService.queryEmpsByCondidtion( new HrmOrgEmpCondition().setNameLikeList(Arrays.asList(operator.toString())).setTenantKey(getTenantKey()), HrmConditionResultType.BEAN.name()); if (likeNameHrmEmployeeList != null && likeNameHrmEmployeeList.size() > 0) { List ids = likeNameHrmEmployeeList.stream().map(HrmEmployee::getId).collect(Collectors.toList()); if (ids != null && ids.size() > 0) { sb.append(" and ( operatorname like '%").append(operator.toString()).append("%' ") .append(" or log_operator in (").append(StringUtils.join(ids, ",")).append(")) "); } } else { sb.append(" and operatorname like '%").append(operator.toString()).append("%' "); } } } } } else if ("modulename".equals(next.getKey())) { Object moduleName = next.getValue(); if (moduleName != null) { moduleName = moduleName.toString().replaceAll("'", "''"); if (StringUtils.isNotBlank(moduleName.toString())) { moduleName = ElogSeviceUtils.checkValSql(moduleName.toString()); //sb.append(" and modulename = '").append(moduleName.toString()).append("' "); StringBuffer stringBuffer = new StringBuffer(); if (isEnglish(moduleName.toString())) { Map moduleMap = ElogSeviceSwitchUtils.moduleMap; Iterator> iterator = moduleMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry nextObj = iterator.next(); if (nextObj.getKey().contains(moduleName.toString())) { stringBuffer.append("'").append(nextObj.getKey()).append("',"); } } } else { Map moduleMap = ElogSeviceSwitchUtils.moduleMap; Iterator> iterator = moduleMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry nextObj = iterator.next(); String val = ElogSeviceSwitchUtils.getModuleName(nextObj.getValue() + ""); if (val.contains(moduleName.toString())) { stringBuffer.append("'").append(nextObj.getKey()).append("',"); } } } String str = ""; if (stringBuffer.toString().length() > 0) { str = stringBuffer.substring(0, stringBuffer.length() - 1); String inVals = str.toString().replaceAll("''", "'"); sb.append(" and modulename in (").append(inVals).append(") "); } else { sb.append(" and modulename = '").append(moduleName.toString()).append("' "); } } } } else if (databaseId.equalsIgnoreCase(ElogConsts.POSTGRESQL) && "targetid".equalsIgnoreCase(next.getKey())){ //兼容PG环境int类型不支持模糊搜索的问题 String value = next.getValue().toString().replaceAll("'", "''"); value = ElogSeviceUtils.checkValSql(value.toString()); if (value.startsWith("_")) { value = value.replace("_", "\\_"); } //将类型转为varchar再进行查询 sb.append(" and ").append("cast(").append(key).append(" as VARCHAR(255) )").append(" like '%").append(value).append("%' "); } else { if (next.getValue() != null && StringUtils.isNotBlank(key) && StringUtils.isNotBlank(next.getValue().toString())) { String value = next.getValue().toString().replaceAll("'", "''"); value = ElogSeviceUtils.checkValSql(value.toString()); StringBuilder stringBuffer = new StringBuilder(); if (isLikeSearch(showColumns, key)) { String logSearchSql = I18nUtil.getLogSearchSql(ElogSeviceUtils.getTableName(module, function), key, value); String sql = logSearchSql.replaceAll("%_", "%\\\\_"); try { logger.error("执行多语言sql:{}",sql); List maps = queryCommonTabeMapper.queryLabelIds(sql); if (maps != null && maps.size() > 0) { for (Map map1 : maps) { Object indexid = map1.get(key); if (indexid == null || StringUtils.isEmpty(indexid.toString())) { indexid = map1.get(key.toLowerCase()); } if (indexid != null && StringUtils.isNotEmpty(indexid.toString())) { String val = indexid.toString().replace("'", "''"); if (ElogSeviceUtils.checkIsNumber(map.get(key))) { val = "-"+val; value = "-"+value; } stringBuffer.append("'").append(val).append("',"); } } } } catch (Exception e) { logger.error("i18查询sql报错:{}",e.getMessage(),e); } } String str = ""; if (stringBuffer.toString().length() > 0) { str = stringBuffer.substring(0, stringBuffer.length() - 1); if (value.startsWith("_")) { value = value.replace("_", "\\_"); } sb.append(" and (").append(key).append(" like '%").append(value).append("%' "); //String inVals = str.toString().replaceAll("''", "'"); if (str.startsWith("_")) { str = str.replace("_", "\\_"); } if ("operatetypename".equals(key)) { String s = ElogSeviceUtils.checkValSql(next.getValue().toString()); sb.append(matchOperatetype(s)); } sb.append(" or ").append(key).append(" in (").append(str).append(")) "); } else { if ("operatetypename".equals(key)) { sb.append(" and (").append(key).append(" like '%").append(value).append("%' "); String s = ElogSeviceUtils.checkValSql(next.getValue().toString()); sb.append(matchOperatetype(s)).append(")"); } else { if (value.startsWith("_")) { value = value.replace("_", "\\_"); } sb.append(" and ").append(key).append(" like '%").append(value).append("%' "); } } } } } return sb.toString(); } /** * 是否模糊搜索 * @param showColumns * @param key * @return */ private boolean isLikeSearch(List showColumns, String key) { for (ShowColumsDto showColumn : showColumns) { if (key.equalsIgnoreCase(showColumn.getColumIndex()) && showColumn.isTransfLanguage()) { return true; } } return false; } private String getSwithDatabaseDate(String date) { SecurityUtil.ecodeForSql(date); if (ElogConsts.ORACLE.equals(DatabaseUtil.getDatabaseId())) { return " to_date('"+date+"','yyyy-mm-dd hh24:mi:ss') "; } else if (ElogConsts.POSTGRESQL.equals(DatabaseUtil.getDatabaseId())) { return " to_timestamp('"+date+"', 'YYYY-MM-DD HH24:MI:SS') "; } else if (ElogConsts.SQLSERVER.equals(DatabaseUtil.getDatabaseId())) { return " convert(nvarchar(19),'"+date+"',120) "; } else { return " DATE_FORMAT('"+date+"','%Y-%m-%d %H:%i:%s') "; } } public String matchOperatetype(String str) { if (ElogSeviceUtils.currentLanguage() != 8) { return ""; } List list = new ArrayList(); list.add(OperateType.add); list.add(OperateType.update); list.add(OperateType.view); list.add(OperateType.delete); StringBuffer sb = new StringBuffer(); for (String o : list) { if (o.toLowerCase().contains(str.toLowerCase())) { sb.append("'").append(o).append("',"); } } if ("new".toLowerCase().contains(str.toLowerCase())) { sb.append("'add',"); } String sql = ""; if (sb.length() > 0) { sql = sb.toString().substring(0, sb.length() - 1); sql = "or operatetype in (" + sql + ")"; } return sql; } public static boolean isEnglish(String charaString) { return charaString.matches("^[a-zA-Z]*"); } /** * 获取搜索条件 * * @param filterConditionDtos * @return */ private String getQueryCondition(List filterConditionDtos) { StringBuffer sb = new StringBuffer(); if (filterConditionDtos != null && filterConditionDtos.size() > 0) { for (FilterConditionDto filterConditionDto : filterConditionDtos) { if (StringUtils.isNotBlank(filterConditionDto.getColumIndex())) { sb.append(getsql(filterConditionDto)); } } } return sb.toString(); } /** * 拼接sql * * @param filterConditionDto * @return */ private String getsql(FilterConditionDto filterConditionDto) { StringBuffer sb = new StringBuffer(); /* if (StringUtils.isNotBlank(filterConditionDto.getSql())) { sb.append(" ").append(filterConditionDto.getSql()).append(" "); return sb.toString(); }*/ SecurityUtil.sqlCheck(filterConditionDto.getColumIndex()); filterConditionDto.setConnectCondition(ElogSeviceUtils.checkConditionSql(filterConditionDto.getConnectCondition())); filterConditionDto.setType(ElogSeviceUtils.checkTypeSql(filterConditionDto.getType())); filterConditionDto.setValue(ElogSeviceUtils.checkValSql(filterConditionDto.getValue())); switchDatabaseFieldIndex(filterConditionDto); if ("LIKE".equalsIgnoreCase(filterConditionDto.getType())) { if (filterConditionDto.getLike() != null) { sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(" '"). append(filterConditionDto.getLike().getPrefix() != null ? filterConditionDto.getLike().getPrefix() : ""). append(filterConditionDto.getValue()). append(filterConditionDto.getLike().getSuffix() != null ? filterConditionDto.getLike().getSuffix() : ""). append("' "); } } else if ("IN".equalsIgnoreCase(filterConditionDto.getType())) { String[] split = filterConditionDto.getValue().split("\",\""); if (split.length > 0) { StringBuffer str = new StringBuffer("("); String value = ""; if ("targetid".equals(filterConditionDto.getColumIndex()) || "log_operator".equals(filterConditionDto.getColumIndex())) { List list = JSONArray.parseArray(filterConditionDto.getValue(), String.class); for (String s : list) { str.append(s).append(","); } } else { List list = JSONArray.parseArray(filterConditionDto.getValue(), String.class); for (String s : list) { str.append("'").append(s).append("',"); } } value = str.toString().substring(0, str.length() - 1); value += ")"; switchDatabaseFieldIndex(filterConditionDto); sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(value). append(" "); } else if (split.length == 0) { sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(" ('"). append(filterConditionDto.getValue()). append("') "); } } else if ("IS NULL".equalsIgnoreCase(filterConditionDto.getType()) || "IS NOT NULL".equalsIgnoreCase(filterConditionDto.getType())) { sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(" "); } else if ("BETWEEN".equalsIgnoreCase(filterConditionDto.getType())) { String[] split = filterConditionDto.getValue().split("\",\""); StringBuffer stringBuffer = new StringBuffer(); if (split.length > 0) { List list = JSONArray.parseArray(filterConditionDto.getValue(), String.class); String str = ""; for (String s : list) { stringBuffer.append(" '").append(s).append("' AND"); } str = stringBuffer.toString().substring(0, stringBuffer.length() - 3); sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(str). append(" "); } else if (split.length == 0) { sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(" '"). append(filterConditionDto.getValue()). append("' "); } } else { if ("targetid".equals(filterConditionDto.getColumIndex()) || "log_operator".equals(filterConditionDto.getColumIndex())) { if (StringUtils.isNotBlank(filterConditionDto.getValue())) { sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(" "). append(filterConditionDto.getValue()). append(" "); } else { sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(" "). append(-1). append(" "); } } else { sb.append(" "). append(getConnectCondition(filterConditionDto.getConnectCondition())). append(" "). append(filterConditionDto.getColumIndex()). append(" "). append(getQueryType(filterConditionDto.getType())). append(" '"). append(filterConditionDto.getValue()). append("' "); } } return sb.toString(); } private void switchDatabaseFieldIndex(FilterConditionDto filterConditionDto) { if ("operator".equalsIgnoreCase(filterConditionDto.getColumIndex())) { filterConditionDto.setColumIndex("log_operator"); } else if ("date".equalsIgnoreCase(filterConditionDto.getColumIndex())) { filterConditionDto.setColumIndex("log_date"); } else if ("result".equalsIgnoreCase(filterConditionDto.getColumIndex())) { filterConditionDto.setColumIndex("log_result"); } } /** * 获取查询类型 * * @param type * @return */ private String getQueryType(String type) { //如果不填默认是= if (StringUtils.isBlank(type)) { return " = "; } return type; } /** * 获取连接条件 * * @param connectCondition * @return */ private String getConnectCondition(String connectCondition) { //如果不填默认是AND if (StringUtils.isBlank(connectCondition)) { return " AND "; } return connectCondition; } @Override public List> getDetailChanges(String module, String function, String mainid, String detailTransMethod) { List> list = getDetailChangesMethod(module, function, mainid, detailTransMethod, null); return list; } /** * 明细分页查询 * @param module * @param function * @param mainid * @param detailTransMethod * @param current * @param pageSize * @return */ @Override public WeaTable getDetailChangePages(String module, String function, String mainid, String detailTransMethod, String current, String pageSize) { Integer pageNum = Util.getIntValue(current, 1); Integer size = Util.getIntValue(pageSize, 10); Page page = new Page(pageNum,size); List> list = getDetailChangesMethod(module, function, mainid, null, page); //查询分页总数 String tableName = ElogSeviceUtils.getTableName(module, function, true); Integer total = localElogDaoMapper.queryAllChangesPageCounts(tableName, mainid); page.setTotal(total); WeaTable weaTable =new WeaTable(); weaTable.setColumns(getDetailColumns(list)); weaTable.setPage(page); weaTable.setData(list); if (Util.isNotEmpty(detailTransMethod)) { // 消费到消息,通过MethodHandler调用对应的方法 MethodHandler methodHandler = ElogMethodHandler.loadMethodHandler(detailTransMethod); if (methodHandler != null) { try { methodHandler.execute(weaTable); } catch (Exception e) { logger.error("转换出错:" + e); } } } return weaTable; } private List getDetailColumns(List> list) { List columns = new ArrayList<>(); if (Util.isNotEmpty(list)) { List detailcontexts= (List) list.get(0).get("detailcontexts"); if (Util.isNotEmpty(detailcontexts)) { for (Map map : detailcontexts) { WeaTableColumn weaTableColumn = new WeaTableColumn(); // 列表属性名 weaTableColumn.setDataIndex((String) map.get("fieldname")); //显示名称 多语言转换 fieldnamelabelid weaTableColumn.setTitle((String) map.get("fieldname")); columns.add(weaTableColumn); } } } return columns; } public List> getDetailChangesMethod(String module, String function, String mainid, String detailTransMethod,Page page) { List list = new ArrayList<>(); String tableName = ElogSeviceUtils.getTableName(module, function, true); String maintableName = ElogSeviceUtils.getTableName(module, function, false); List maps = localElogDaoMapper.queryAllMainData(maintableName, mainid); for (Map map : maps) { if (map.get("params") != null && ElogConsts.ES.equalsIgnoreCase(map.get("params").toString())) { String logDate = map.get("log_date").toString(); logger.info("logDate:{}" ,logDate); String esDate = logDate.substring(0, 10); //先判断表存不存在,不存在创建 if (checkEsTableIsExist(esDate)) { // 根据id通过es查询大字段(params)然后赋值 SearchRequest searchRequest = new SearchRequest(getElogESTableName(true,esDate)); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // 只获取指定字段 String[] fields = {"params"}; searchSourceBuilder.fetchSource(fields, null); // 根据id匹配 searchSourceBuilder.query(QueryBuilders.termQuery("id",map.get("id").toString())); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = null; try { searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); } catch (IOException e) { logger.info("查询ES出现异常:{}",e.getMessage()); } SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); if (searchHits != null && searchHits.length > 0) { // 根据id匹配唯一,所以直接取第一个 Map sourceAsMap = searchHits[0].getSourceAsMap(); if (Objects.nonNull(sourceAsMap) && Objects.nonNull(sourceAsMap.get("params")) && StringUtils.isNotEmpty(sourceAsMap.get("params").toString())) { logger.info("ES查出来的params:{}",sourceAsMap.get("params")); map.put("params",sourceAsMap.get("params")); } } } } if (map.get("params") != null && map.get("params").toString().startsWith("H4s")) { map.put("params", ElogSeviceUtils.uncompress(map.get("params").toString())); map.put("params",SecurityUtil.encodeForHtml(map.get("params").toString(), true)); } } maps = ElogSeviceSwitchUtils.getSwitchDatabaseData(maps); ElogSeviceSwitchUtils.changKey2Lower(maps); List allChangesData = new ArrayList<>(); //如果有分页数据则走分页方法 if (Objects.nonNull(page) ) { // Integer offset = (pageNum - 1) * size; //分页查询明细数据 allChangesData = localElogDaoMapper.queryAllChangesDataPages(tableName, mainid, page); } else { //没有被则不分页 allChangesData = localElogDaoMapper.queryAllChangesData(tableName, mainid); } ElogSeviceSwitchUtils.changKey2Lower(allChangesData); allChangesData = ElogSeviceSwitchUtils.getSwitchDatabaseData(allChangesData); List mainlist = new ArrayList<>(); List detaillist = new ArrayList<>(); if (allChangesData != null && allChangesData.size() > 0) { for (Map allChangesDatum : allChangesData) { Object o = allChangesDatum.get("isdetail"); if (o != null) { if ("0".equals(o.toString())) { mainlist.add(allChangesDatum); } else { detaillist.add(allChangesDatum); } } } } // List mainlist = localElogDaoMapper.queryAllMainChanges(tableName, mainid); // List detaillist = localElogDaoMapper.queryAllDetailChanges(tableName, mainid); //List moduleInfo = queryCommonTabeMapper.queryModuleNameInfo(module); List moduleInfo = new ArrayList<>(); processDetailInfo(mainlist, detaillist, moduleInfo); Map map = ElogSeviceSwitchUtils.switchChangeValue(mainlist, maps); Map detailMap = ElogSeviceSwitchUtils.switchDetailChangeValue(detaillist); map.putAll(detailMap); if (maps != null && maps.size() > 0) { Map maininfoMap = maps.get(0); String operatetypename = (String)maininfoMap.get("operatetypename"); String targetname = (String)maininfoMap.get("targetname"); //长度大于1避免部分模块为1,2,3这类的操作类型 if (StringUtils.isNumeric(operatetypename) && operatetypename.length() > 1 && operatetypename.length() < 10) { String transfOperatetypename = ElogSeviceSwitchUtils.transfLanguageLableid(Long.parseLong(operatetypename), operatetypename); maininfoMap.put("operatetypename",transfOperatetypename); } if (StringUtils.isNumeric(targetname) && targetname.length() > 1 && targetname.length() < 10) { String transfTargetname = ElogSeviceSwitchUtils.transfLanguageLableid(Long.parseLong(targetname), targetname); maininfoMap.put("targetname",transfTargetname); } map.put("maininfo",maininfoMap); map.put("detailtitle", ""); } list.add(map); if (Util.isNotEmpty(detailTransMethod)) { // 消费到消息,通过MethodHandler调用对应的方法 MethodHandler methodHandler = ElogMethodHandler.loadMethodHandler(detailTransMethod); if (methodHandler != null) { try { methodHandler.execute(list); } catch (Exception e) { logger.error("转换出错:" + e); } } } //List transfLanguageData = ElogSeviceSwitchUtils.transfLanguageData(list); return list; } /** * 处理修改详情转多语言(主表和明细表) * * @param mainlist * @param detaillist * @param commonTableInfo * @return */ private void processDetailInfo(List mainlist, List detaillist, List commonTableInfo) { Map tablenameMap = new HashMap<>(); Map fieldnameMap = new HashMap<>(); Map valueMap = new HashMap<>(); if (commonTableInfo != null && commonTableInfo.size() > 0) { for (Map commonTableInfoMap : commonTableInfo) { JSONObject commonTableInfoMapJs = JSONObject.parseObject(JSONObject.toJSONString(commonTableInfoMap)); String tablename = commonTableInfoMapJs.getString("table_name"); String tablename_labelid = commonTableInfoMapJs.getString("tablename_labelid"); String fieldname = commonTableInfoMapJs.getString("field_name"); String fieldname_labelid = commonTableInfoMapJs.getString("fieldname_labelid"); String values_kvpairs = commonTableInfoMapJs.getString("values_kvpairs"); fieldnameMap.put(fieldname, fieldname_labelid); if (StringUtils.isNotBlank(fieldname) && StringUtils.isNotBlank(values_kvpairs)) { JSONObject jsonObject = JSONObject.parseObject(values_kvpairs); valueMap.put(fieldname, jsonObject); } Object tablenameObj = tablenameMap.get(tablename); if (tablenameObj == null) { tablenameMap.put(tablename, tablename_labelid); } } } if (mainlist != null && mainlist.size() > 0 && fieldnameMap.size() > 0 && valueMap.size() > 0) { for (Map mainlistMap : mainlist) { JSONObject mainMapJs = JSONObject.parseObject(JSONObject.toJSONString(mainlistMap)); String fielddesc = mainMapJs.getString("fielddesc"); String oldvalue = mainMapJs.getString("oldvalue"); String newvalue = mainMapJs.getString("newvalue"); if (fieldnameMap.get(fielddesc) != null) { mainlistMap.put("fielddesc", ElogSeviceSwitchUtils.transfLanguageLableid(ElogSeviceUtils.getLongValue(fieldnameMap.get(fielddesc).toString()), fieldnameMap.get(fielddesc).toString())); } if (valueMap.get(fielddesc) != null) { JSONObject jsonObject = JSONObject.parseObject(valueMap.get(fielddesc).toString()); String oldvalueStr = jsonObject.getString(oldvalue); String newvalueStr = jsonObject.getString(newvalue); if (StringUtils.isNotBlank(oldvalueStr)) { mainlistMap.put("oldvalue", ElogSeviceSwitchUtils.transfLanguageLableid(ElogSeviceUtils.getLongValue(oldvalueStr), oldvalue)); } if (StringUtils.isNotBlank(newvalueStr)) { mainlistMap.put("newvalue", ElogSeviceSwitchUtils.transfLanguageLableid(ElogSeviceUtils.getLongValue(newvalueStr), newvalue)); } } } } if (detaillist != null && detaillist.size() > 0 && fieldnameMap.size() > 0 && valueMap.size() > 0) { for (Map detaillistMap : detaillist) { JSONObject mainMapJs = JSONObject.parseObject(JSONObject.toJSONString(detaillistMap)); String tablename = mainMapJs.getString("tablename"); String fielddesc = mainMapJs.getString("fielddesc"); String oldvalue = mainMapJs.getString("oldvalue"); String newvalue = mainMapJs.getString("newvalue"); if (tablenameMap.get(tablename) != null) { detaillistMap.put("tablename", ElogSeviceSwitchUtils.transfLanguageLableid(ElogSeviceUtils.getLongValue(tablenameMap.get(tablename).toString()), tablenameMap.get(tablename).toString())); } if (fieldnameMap.get(fielddesc) != null) { detaillistMap.put("fielddesc", ElogSeviceSwitchUtils.transfLanguageLableid(ElogSeviceUtils.getLongValue(fieldnameMap.get(fielddesc).toString()), fieldnameMap.get(fielddesc).toString())); } if (valueMap.get(fielddesc) != null) { JSONObject jsonObject = JSONObject.parseObject(valueMap.get(fielddesc).toString()); String oldvalueStr = jsonObject.getString(oldvalue); String newvalueStr = jsonObject.getString(newvalue); if (StringUtils.isNotBlank(oldvalueStr)) { detaillistMap.put("oldvalue", ElogSeviceSwitchUtils.transfLanguageLableid(ElogSeviceUtils.getLongValue(oldvalueStr), oldvalue)); } if (StringUtils.isNotBlank(newvalueStr)) { detaillistMap.put("newvalue", ElogSeviceSwitchUtils.transfLanguageLableid(ElogSeviceUtils.getLongValue(newvalueStr), newvalue)); } } } } } @Override public List queryLogList(String module, String function, String current, String pageSize, String condition) { LoggerContext context = new LoggerContext(); context.setModuleName(module); context.setFunctionName(function); int pagenum = Util.getIntValue(current, 1) - 1; int size = Util.getIntValue(pageSize, 10); int start = pagenum * size; int end = start + size; Page page = new Page(pagenum, size); String limit = " limit " + start + "," + (end - start); String tableName = ElogSeviceUtils.getTableName(module, function); List list = localElogDaoMapper.queryElogList(page, context, null, tableName, null,"*"); list = ElogSeviceSwitchUtils.getSwitchDatabaseData(list); return switchString(list); } @Override public List queryCardLogList(String data) { JSONObject map = JSONObject.parseObject(data); String module = ""; String function = ""; String pageNum = ""; String pageSize = ""; String dataset = ""; String searchMap = ""; String sColum = ""; String fColum = ""; String transMethod = null; List showColums = new ArrayList<>(); List filterConditionDtos = new ArrayList<>(); String authParams = ""; Map jsonObject = new HashMap(); if (map != null) { module = map.getString("module"); function = map.getString("function"); pageNum = map.getString("pageNum"); pageSize = map.getString("pageSize"); //dataset = map.get("dataset").toString(); searchMap = map.getString("searchMap"); sColum = map.getString("showColums"); showColums = JSONArray.parseArray(sColum, ShowColumsDto.class); fColum = map.getString("filterConditions"); transMethod = map.getString("transMethod"); filterConditionDtos = JSONArray.parseArray(fColum, FilterConditionDto.class); authParams = map.getString("authParams"); jsonObject = JSONObject.parseObject(authParams); } LoggerContext context = new LoggerContext(); context.setModuleName(module); context.setFunctionName(function); context.setTenant_key(getTenantKey().toLowerCase()); // 分页 //Page pages = ElogSeviceUtils.getPage(); String sb = getQueryCondition(filterConditionDtos); logger.info("elog查询条件拼接sql:{}", sb); // 消费到消息,通过MethodHandler调用对应的方法 //String targetid = getTargetid(filterConditionDtos); Map customAuthMap = getCustomAuthSql(transMethod, jsonObject, "auth"); if (!customAuthMap.isEmpty()) { Object flag = customAuthMap.get("flag"); if (flag != null && flag instanceof Boolean) { boolean f = (boolean) flag; if (!f) { List list = new ArrayList<>(); list.add(customAuthMap); return list; } } } String customSql = getCustomSql(transMethod, sb, "before"); Page pages = new Page(ElogSeviceUtils.getIntValue(pageNum, 1), ElogSeviceUtils.getIntValue(pageSize, 10)); int page = Util.getIntValue(pages.getCurrent() + "", 1) - 1; int size = Util.getIntValue(pages.getSize() + "", 10); int start = page * size; int end = start + size; String limit = " limit " + start + "," + (end - start); String tableName = ElogSeviceUtils.getTableName(module, function); long l = System.currentTimeMillis(); Map hashMap = addPermissionHandler(transMethod); String permissionId = ""; String permissionType = ""; String mainDataTableAlias = ""; String mainDataTable = ""; String primaryKey = ""; String permissionTargetId = ""; String permissionConfigSourceId = ""; permissionId = getPermissionStr(hashMap, "permissionId"); permissionType = getPermissionStr(hashMap, "permissionType"); mainDataTableAlias = getPermissionStr(hashMap, "mainDataTableAlias"); mainDataTable = getPermissionStr(hashMap, "mainDataTable"); primaryKey = getPermissionStr(hashMap, "primaryKey"); permissionTargetId = getPermissionStr(hashMap, "permissionTargetId"); permissionConfigSourceId = getPermissionStr(hashMap, "permissionConfigSourceId"); //String columns = getshowColumsStr(showColums); List list = new ArrayList<>(); Map countMap = new HashMap<>(); if (StringUtils.isNotEmpty(permissionId) || StringUtils.isNotEmpty(permissionType) || StringUtils.isNotEmpty(mainDataTableAlias) || StringUtils.isNotEmpty(mainDataTable) || StringUtils.isNotEmpty(permissionTargetId) || StringUtils.isNotEmpty(permissionConfigSourceId)) { list = localElogDaoMapper.queryElogList(pages, context, null, tableName, customSql, mainDataTable, permissionId, permissionType, mainDataTableAlias, primaryKey,permissionTargetId,permissionConfigSourceId,"*"); countMap = localElogDaoMapper.elogCountByMorePermission(context, tableName, customSql, mainDataTable, permissionId, permissionType, mainDataTableAlias, primaryKey, permissionTargetId,permissionConfigSourceId); } else { list = localElogDaoMapper.queryElogList(pages, context, null, tableName, customSql,"*"); long l1 = System.currentTimeMillis(); logger.info("elog查询列表耗时:{}", (l1 - l)); countMap = localElogDaoMapper.elogCount(context, tableName, customSql); long l2 = System.currentTimeMillis(); logger.info("elog查询总数耗时:{}", (l2 - l1)); } list = ElogSeviceSwitchUtils.getSwitchDatabaseData(list); if (list != null && list.size() > 0) { //if ("1".equals(pageNum)){ list.get(0).put("total", ElogSeviceUtils.getLongValue(countMap.get("counts") + "", 0)); //} } transUserInfo(list); long l3 = System.currentTimeMillis(); //System.out.println("elog查询名称和头像耗时:{}"+ (l3-l2)); transfLanguageData(list, showColums); if (Util.isNotEmpty(transMethod)) { // 消费到消息,通过MethodHandler调用对应的方法 MethodHandler methodHandler = ElogMethodHandler.loadMethodHandler(transMethod); if (methodHandler != null) { try { methodHandler.execute(list); } catch (Exception e) { logger.error("转换出错:" + e); } } } long l4 = System.currentTimeMillis(); logger.info("elog查询转换耗时:{}", (l4 - l3)); List res = switchString(list); logger.info("elog查询总耗时:{}", (l4 - l)); return res; } /** * 转换数据成多语言,结合前端转 * * @param lists * @param showColums */ public static List transfLanguageData(List lists, List showColums) { if (lists != null && lists.size() > 0) { for (Map map : lists) { if (map != null) { Iterator> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); for (ShowColumsDto showColum : showColums) { if (StringUtils.isNotBlank(showColum.getColumIndex()) && showColum.isTransfLanguage() && entry.getKey().equals(showColum.getColumIndex()) && !Objects.isNull(entry.getValue()) && StringUtils.isNumeric(entry.getValue().toString())) { if (entry.getValue() instanceof Integer || entry.getValue() instanceof Long || entry.getValue() instanceof String) { map.put(entry.getKey(), ElogSeviceSwitchUtils.transfLanguageLableid(ElogSeviceUtils.getLongValue(entry.getValue().toString()), entry.getValue().toString())); } else { //map.put(entry.getKey(), ElogSeviceSwitchUtils.handlerBaseDataMethod(entry.getValue().toString())); map.put(entry.getKey(), entry.getValue()); } } else if (StringUtils.isNotBlank(showColum.getColumIndex()) && showColum.isTransfLanguage() && entry.getKey().equals(showColum.getColumIndex()) && !Objects.isNull(entry.getValue())) { //read view add edit update delete if ("add".equals(entry.getValue().toString()) || "创建".equals(entry.getValue().toString())) { map.put(entry.getKey(), SystemEnv.getHtmlLabelName(63252, "新增")); } else if ("read".equals(entry.getValue().toString()) || "view".equals(entry.getValue().toString()) || "查看".equals(entry.getValue().toString())) { map.put(entry.getKey(), SystemEnv.getHtmlLabelName(55172, "查看")); } else if ("edit".equals(entry.getValue().toString()) || "update".equals(entry.getValue().toString()) || "更新".equals(entry.getValue().toString())) { map.put(entry.getKey(), SystemEnv.getHtmlLabelName(63253, "修改")); } else if ("delete".equals(entry.getValue().toString()) || "删除".equals(entry.getValue().toString()) ) { map.put(entry.getKey(), SystemEnv.getHtmlLabelName(63254, "删除")); } else if (entry.getValue().toString().contains("取消关联标签 ")) { String val = entry.getValue().toString().replace("取消关联标签 ", SystemEnv.getHtmlLabelName(83237, "取消关联标签 ") + " "); map.put(entry.getKey(), val); } else if (entry.getValue().toString().contains("关联标签 ")) { String val = entry.getValue().toString().replace("关联标签 ", SystemEnv.getHtmlLabelName(83236, "关联标签 ") + " "); map.put(entry.getKey(), val); } } } } } } } return lists; } @Override public Map countLog(String module, String function) { LoggerContext context = new LoggerContext(); context.setModuleName(module); context.setFunctionName(function); context.setTenant_key(getTenantKey()); String tableName = ElogSeviceUtils.getTableName(module, function); return localElogDaoMapper.elogCount(context, tableName, null); } @Override public List queryDetailLogList(String module, String function, String current, String pageSize, String condition, String mainId) { LoggerContext context = new LoggerContext(); context.setModuleName(module); context.setFunctionName(function); context.setTenant_key(getTenantKey()); context.setUuid(mainId); int page = Util.getIntValue(current, 1) - 1; int size = Util.getIntValue(pageSize, 10); int start = page * size; int end = start + size; String limit = " limit " + start + "," + (end - start); // 还需要支持下查询 String tableName = ElogSeviceUtils.getTableName(module, function, true); List list = localElogDaoMapper.queryDetailElogList(context, limit, tableName, null); list = ElogSeviceSwitchUtils.getSwitchDatabaseData(list); return switchString(list); } @Override public Map countDestailLog(String module, String function, String mainId) { LoggerContext context = new LoggerContext(); context.setModuleName(module); context.setFunctionName(function); context.setTenant_key(getTenantKey()); context.setUuid(mainId); String tableName = ElogSeviceUtils.getTableName(module, function, true); return localElogDaoMapper.elogDetailCount(context, tableName, null); } @Override public WeaTable queryElogTraceInfo(String traceId, String module, String function, Integer currentPage, Integer pageSize, String traceTransMethod) { WeaTable weaTable = new WeaTable(); if (StringUtils.isNotEmpty(traceId)) { String tableName = ElogSeviceUtils.getTableName(module, function); Integer offset = (currentPage - 1) * pageSize; List list = localElogDaoMapper.queryElogTraceInfo(traceId, tableName, offset, pageSize); for (Map map : list) { if (map.get("modulename") != null) { map.put("modulenamespan", ElogSeviceSwitchUtils.getModuleName(map.get("modulename").toString())); } } //list = ElogSeviceSwitchUtils.getSwitchDatabaseData(list); int count = localElogDaoMapper.queryElogTraceInfoCount(traceId, tableName); weaTable.setTotal(count); Page page = new Page(); page.setTotal(count); page.setSize(pageSize); page.setCurrent(currentPage); weaTable.setPage(page); if (Util.isNotEmpty(traceTransMethod)) { // 消费到消息,通过MethodHandler调用对应的方法 MethodHandler methodHandler = ElogMethodHandler.loadMethodHandler(traceTransMethod); if (methodHandler != null) { try { methodHandler.execute(list); } catch (Exception e) { logger.error("转换出错:" + e); } } } weaTable.setData(list); } return weaTable; } @Override public List queryLogInfoByCustom(String module, String function, String field, String value, boolean isDetail) { List list = new ArrayList(); String tableName = ElogSeviceUtils.getTableName(module, function, isDetail); if (StringUtils.isNotBlank(field) && StringUtils.isNotBlank(value)) { StringBuffer sql = new StringBuffer(); sql.append(field).append(" = '").append(value).append("' "); list = localElogDaoMapper.queryLogInfoByCustom(tableName, sql.toString()); } return list; } @Override public List queryLogInfoByCustom(String module, String function, String field, String value) { return queryLogInfoByCustom(module, function, field, value, false); } public List switchString(List list) { if (list != null) { return list.stream().map(m -> { Set en = m.entrySet(); for (Map.Entry entry : en) { if (entry.getValue() != null) { entry.setValue(String.valueOf(entry.getValue())); } } return m; }).collect(Collectors.toList()); } else { return list; } } @Override public BatchDocumentMessage downloadLog(String data) { JSONObject jsonObject = JSONObject.parseObject(data); String module = jsonObject.getString("downloadmodule"); String function = jsonObject.getString("function"); String serviceName = jsonObject.getString("serviceName"); String fileName = jsonObject.getString("fileName"); String passWord = jsonObject.getString("passWord"); if (StringUtils.isEmpty(fileName)) { fileName = SystemEnv.getHtmlLabelName(191432,"日志记录"); } BatchDocumentMessage batchDocumentMessage = new BatchDocumentMessage(); WeaTable weaTable = queryLogs(data); List columns = weaTable.getColumns(); List headers = new ArrayList<>(); if (columns != null && !columns.isEmpty()) { for (WeaTableColumn column : columns) { Map header = new HashMap<>(); header.put("key", column.getDataIndex()); header.put("name", column.getTitle()); headers.add(header); } } List> dataList = weaTable.getData(); List> maps = new ArrayList<>(); if (dataList != null && !dataList.isEmpty()) { dataList.stream().forEach(m -> { Map map = new HashMap<>(); headers.stream().forEach(h -> { map.put(h.get("key").toString(), m.get(h.get("key"))); }); maps.add(map); }); } //必传--业务id batchDocumentMessage.setBizId(IdGenerator.generate() + ""); //必传-处理名称 batchDocumentMessage.setHandlerName("ebatchdemo"); //必传-服务名称 batchDocumentMessage.setServiceName(serviceName); //必传-数据类型 batchDocumentMessage.setDataType(fileName); //任务id batchDocumentMessage.setBatchTaskId(IdGenerator.generate()); //必传-模块 batchDocumentMessage.setModule(module); //com.weaver.teams.domain.EntityType 中的module(没有的话需要找温明刚维护下) //必传-功能 batchDocumentMessage.setFunction(function); //必传-eteamsid batchDocumentMessage.setEteamsId(TenantRpcContext.getEteamsId()); //非必传 if (StringUtils.isNotBlank(passWord)) { batchDocumentMessage.setPassword(passWord); } //必传 BatchFile batchFile = new BatchFile(); batchFile.setName(fileName); //必传 batchFile.setFileType(FileType.EXCEL); //必传 batchFile.setHandlerFileMethod(HandlerFileMethod.HANDLER_EXCEL_WITH_DATA); batchFile.setTemplateId(1l); List excelSheets = new ArrayList<>(); ExcelSheet excelSheet = new ExcelSheet(); excelSheet.setHeader(headers); excelSheet.setData(maps); excelSheet.setName(fileName); excelSheets.add(excelSheet); batchFile.setExcelSheets(excelSheets); batchDocumentMessage.setBatchFile(batchFile); batchDocumentMessage.setChunk(false);//不分片 batchExportSender.sendBatchExport(batchDocumentMessage); return batchDocumentMessage; } public Boolean checkEsTableIsExist(String date) { try { String esMainIndex = getElogESTableName(true, date); //先检查表是否存在 不存在则创建 boolean existsLog = isExistsIndex(esMainIndex); return existsLog; } catch (Exception e) { logger.info("创建相关ES表失败:{}", e.getMessage(), e); } return false; } /** * 判断一个索引是否存在 * * @param indexName * @return */ public boolean isExistsIndex(String indexName) { GetIndexRequest request = new GetIndexRequest(); try { boolean exists = restHighLevelClient.indices().exists(request.indices(indexName), RequestOptions.DEFAULT); return exists; } catch (Exception e) { logger.info("判断索引是否存在出现异常:{}", e.getMessage()); } return false; } /** * 创建主表语句 * * @throws IOException */ private void createLogIndex(String esMainIndex) { // 1.创建Request对象 CreateIndexRequest request = new CreateIndexRequest(esMainIndex); // 2.准备请求的参数:DSL语句 request.source(MAPPING_TEMPLATE, XContentType.JSON); // 3.发送请求 try { restHighLevelClient.indices().create(request, RequestOptions.DEFAULT); } catch (IOException e) { logger.info("创建ES主表失败:{}", e.getMessage()); } } private String getElogESTableName(boolean flag, String date) { String currentDate = ""; if (StringUtils.isEmpty(date)) { currentDate = DateUtils.getCurrentDate().replaceAll("-", ""); } else { currentDate = date.replaceAll("-", ""); } return getEsMainIndex(flag, currentDate); } private String getEsMainIndex(boolean flag, String date) { if (flag) { return ElogEsTableConsts.ELOG_CENTER_LOGS_ES + date; } return ElogEsTableConsts.ELOG_CENTER_LOGSDETAIL_ES + date; } private String[] getESfields(String value) { String[] split = value.split(","); List list = new ArrayList<>(); for (String s : split) { switch (s.toLowerCase()) { case "interfacename": list.add("interfacename"); break; case "operatetype": list.add("operatetype"); break; case "operatedesc": list.add("operatedesc"); break; case "params": list.add("params"); break; case "clientip": list.add("clientip"); break; case "groupnamelabel": list.add("groupnamelabel"); break; case "redoservice": list.add("redoservice"); break; case "redocontext": list.add("redocontext"); break; case "cancelservice": list.add("cancelservice"); break; case "cancelcontext": list.add("cancelcontext"); break; case "device": list.add("device"); break; case "groupid": list.add("groupid"); break; case "belongmainid": list.add("belongmainid"); break; case "requesturl": list.add("requesturl"); break; case "requesturi": list.add("requesturi"); break; case "log_result": list.add("logResult"); break; case "fromterminal": list.add("fromterminal"); break; case "resultdesc": list.add("resultdesc"); break; case "old_content": list.add("oldContent"); break; case "link_type": list.add("linkType"); break; } } //list转为数组 if (list.size() > 0) { String[] strings = list.toArray(new String[list.size()]); return strings; } return null; } }