1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
| @Slf4j @Intercepts({ @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}) }) public class OperationLogPlugin implements Interceptor {
private static final Set<String> MONITOR_TABLE = new HashSet<>();
static { String[] table = { "agency_merchant", "pay_merchantChannel", "agency_merchantSettle", "agency_vendor", "agency_merchantWechat", "agency_outlet" }; for (String s : table) { MONITOR_TABLE.add(s.toLowerCase()); } }
@Override public Object intercept(Invocation invocation) throws Throwable { BoundSql boundSql = null; StatementHandler statementHandler; if (invocation.getTarget() instanceof StatementHandler) { statementHandler = (StatementHandler) invocation.getTarget(); boundSql = statementHandler.getBoundSql(); } else { return invocation.proceed(); }
Object[] args = invocation.getArgs(); Statement statement = (Statement) args[0];
String preSql = boundSql.getSql(); MySqlStatementParser mySqlStatementParser = new MySqlStatementParser(preSql); SQLStatement sqlStatement = mySqlStatementParser.parseStatement(); SQLExprTableSource sqlTableSource = null; SQLExpr where = null; if (sqlStatement instanceof SQLSelectStatement) { return invocation.proceed(); } else if (sqlStatement instanceof SQLInsertStatement) {
return invocation.proceed(); } else if (sqlStatement instanceof SQLUpdateStatement) { SQLUpdateStatement sqlUpdateStatement = (SQLUpdateStatement) sqlStatement; sqlTableSource = (SQLExprTableSource) sqlUpdateStatement.getTableSource(); where = sqlUpdateStatement.getWhere(); } else if (sqlStatement instanceof SQLDeleteStatement) {
return invocation.proceed(); } else { return invocation.proceed(); } String tableName = sqlTableSource.toString(); if (where == null) { return invocation.proceed(); } Connection connection = statement.getConnection(); Long id = 0L; List<Map<String, Object>> beforeImage; List<Map<String, Object>> afterImage; if (MONITOR_TABLE.contains(tableName.toLowerCase())) { String beforeImagePreSql = String.format("SELECT * FROM %s where %s", tableName, where.toString()); RoutingStatementHandler routingStatementHandler = (RoutingStatementHandler) getJdkDynamicProxyTargetObject(statementHandler); StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(routingStatementHandler, "delegate"); MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement"); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); Object parameterObject = boundSql.getParameterObject(); List<SQLObject> children = where.getChildren(); int whereConditionCount = getWhereConditionCount(children, 0); List<ParameterMapping> newParameterMapping = new ArrayList<>(parameterMappings.size()); for (int i = parameterMappings.size() - whereConditionCount; i < parameterMappings.size(); i++) { newParameterMapping.add(parameterMappings.get(i)); } BoundSql beforeImageBoundSql = new BoundSql(mappedStatement.getConfiguration(), beforeImagePreSql, newParameterMapping, parameterObject); ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, beforeImageBoundSql); PreparedStatement prepareStatement = connection.prepareStatement(beforeImagePreSql); parameterHandler.setParameters(prepareStatement); ResultSet rs = prepareStatement.executeQuery(); beforeImage = convertList(rs); id = (Long) beforeImage.get(0).get("id"); } else { return invocation.proceed(); } Object proceed = invocation.proceed(); if (beforeImage.size() == 1) { String afterImageSql = String.format("SELECT * from %s where id = %s", tableName, id); PreparedStatement prepareStatement = connection.prepareStatement(afterImageSql); ResultSet rs = prepareStatement.executeQuery(); afterImage = convertList(rs); List<Map<String, Object>> difference = difference(beforeImage.get(0), afterImage.get(0));
AuthenticationDto authentication = null; try { AuthUtil bean = SpringUtil.getBean(AuthUtil.class); authentication = bean.getAuthentication(); } catch (Exception e) { log.warn("获取用户信息失败"); }
String userId = authentication == null ? "" : String.valueOf(authentication.getUserId()); String merchantId = authentication == null ? "" : String.valueOf(authentication.getMerchantId());
String operationLogSQL = "INSERT INTO `pay_1`.`operation_log`(`uid`, `merchantId`, `tableName`, `operationCode`, `primaryKey`, `oriValue`, `newValue`, `recordTime`)" + "VALUES(?, ?, ?, ?, ?, ?, ?, ?);"; PreparedStatement operationLogStatement = connection.prepareStatement(operationLogSQL); operationLogStatement.setString(1, userId); operationLogStatement.setString(2, merchantId); operationLogStatement.setString(3, tableName); operationLogStatement.setString(4, "UPDATE"); operationLogStatement.setString(5, String.valueOf(id)); operationLogStatement.setString(6, JsonUtil.entity2Json(difference.get(0))); operationLogStatement.setString(7, JsonUtil.entity2Json(difference.get(1))); operationLogStatement.setInt(8, TimeUtil.getNow()); operationLogStatement.execute(); } return proceed; }
@Override public Object plugin(Object target) { if (target instanceof StatementHandler) { return Plugin.wrap(target, this); } else { return target; } }
@Override public void setProperties(Properties properties) { Interceptor.super.setProperties(properties); }
private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception { Field field = proxy.getClass().getSuperclass().getDeclaredField("h"); field.setAccessible(true); Plugin pluginProxy = (Plugin) field.get(proxy); Field target = pluginProxy.getClass().getDeclaredField("target"); target.setAccessible(true); return target.get(pluginProxy); }
private int getWhereConditionCount(List<SQLObject> listCommon, int sum) { for (SQLObject sqlObject : listCommon) { if (sqlObject instanceof SQLBinaryOpExpr) { SQLBinaryOpExpr sqlObject1 = (SQLBinaryOpExpr) sqlObject; List<SQLObject> chList = sqlObject1.getChildren(); sum = getWhereConditionCount(chList, sum); } else if (sqlObject instanceof SQLIdentifierExpr) { sum += 1; } } return sum; }
private static List<Map<String, Object>> convertList(ResultSet rs) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); try { ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { Map<String, Object> rowData = new HashMap<String, Object>(); for (int i = 1; i <= columnCount; i++) { Object object = rs.getObject(i); if (object instanceof BigInteger) { rowData.put(md.getColumnName(i), ((BigInteger) object).longValue()); } else { rowData.put(md.getColumnName(i), object); } } list.add(rowData); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } rs = null; } catch (SQLException e) { e.printStackTrace(); } } return list; }
private List<Map<String, Object>> difference(Map<String, Object> beforeImage, Map<String, Object> afterImage) { List<Map<String, Object>> result = new ArrayList<>(); result.add(new HashMap<>()); result.add(new HashMap<>()); for (Map.Entry<String, Object> beforeEntry : beforeImage.entrySet()) { String key = beforeEntry.getKey(); Object beforeValue = beforeEntry.getValue(); Object afterValue = afterImage.get(key); if (!Objects.equals(beforeValue, afterValue)) { result.get(0).put(key, beforeValue); result.get(1).put(key, afterValue); } } return result; } }
|