wuxw
2022-11-11 81fa5b8cc976e642925544be6fabd8ff9504fd24
java110-db/src/main/java/com/java110/db/Java110MybatisInterceptor.java
old mode 100644 new mode 100755
@@ -3,6 +3,7 @@
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.client.RestTemplate;
import com.java110.core.context.Environment;
import com.java110.core.factory.Java110TransactionalFactory;
import com.java110.db.dao.IQueryServiceDAO;
import com.java110.dto.order.OrderItemDto;
@@ -11,34 +12,18 @@
import com.java110.utils.util.DateUtil;
import com.java110.utils.util.StringUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import com.java110.core.log.LoggerFactory;
import org.springframework.http.*;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.*;
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class,
@@ -64,18 +49,23 @@
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        Map<String, Object> sqlValue = new HashMap<>();
        //获取sql语句
        String sql = showSql(configuration, boundSql);
        restTemplate = ApplicationContextFactory.getBean("restTemplate", RestTemplate.class);
        String sql = showSql(configuration, boundSql, sqlValue, sqlCommandType);
        if(Environment.isStartBootWay()){
            restTemplate = ApplicationContextFactory.getBean("outRestTemplate", RestTemplate.class);
        }else {
            restTemplate = ApplicationContextFactory.getBean("restTemplate", RestTemplate.class);
        }
        switch (sqlCommandType) {
            case INSERT:
                dealInsertSql(mappedStatement, parameter, sql);
                dealInsertSql(mappedStatement, parameter, sql, sqlValue);
                break;
            case UPDATE:
                dealUpdateSql(mappedStatement, parameter, sql);
                dealUpdateSql(mappedStatement, parameter, sql, sqlValue);
                break;
            case DELETE:
                dealDeleteSql(mappedStatement, parameter, sql);
                dealDeleteSql(mappedStatement, parameter, sql, sqlValue);
                break;
        }
        return invocation.proceed();
@@ -87,14 +77,18 @@
     * @param mappedStatement
     * @param parameter
     */
    private void dealDeleteSql(MappedStatement mappedStatement, Object parameter, String sql) {
    private void dealDeleteSql(MappedStatement mappedStatement, Object parameter, String sql, Map<String, Object> sqlValue) {
        String tmpTable = sql.substring(sql.indexOf("into") + 4, sql.indexOf("("));
        String tmpTable = sql.substring(sql.indexOf("from") + 4, sql.indexOf("where")).trim();
        String tmpTableHasT = tmpTable;
        if(tmpTable.indexOf(" ") > 0){
            tmpTable = tmpTable.substring(0,tmpTable.indexOf(" "));
        }
        String tmpWhere = sql.substring(sql.indexOf("where"));
        //插入操作时之前的 没有数据 所以 preValue 为空对象
        JSONArray preValues = new JSONArray();
        String execSql = "select * from " + tmpTable + " " + tmpWhere;
        String execSql = "select * from " + tmpTableHasT + " " + tmpWhere;
        queryServiceDAOImpl = ApplicationContextFactory.getBean("queryServiceDAOImpl", IQueryServiceDAO.class);
        List<Map<String, Object>> deleteDatas = queryServiceDAOImpl.executeSql(execSql, null);
@@ -123,6 +117,9 @@
        String url = ServiceConstant.SERVICE_ORDER_URL + "/order/oIdApi/createOrderItem";
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity httpEntity = new HttpEntity(orderItemDto.toString(), httpHeaders);
        if(Environment.isStartBootWay()){
            url = ServiceConstant.BOOT_SERVICE_ORDER_URL + "/order/oIdApi/createOrderItem";
        }
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
@@ -136,38 +133,23 @@
     * @param mappedStatement
     * @param parameter
     */
    private void dealUpdateSql(MappedStatement mappedStatement, Object parameter, String sql) {
    private void dealUpdateSql(MappedStatement mappedStatement, Object parameter, String sql, Map<String, Object> sqlValue) {
        //RestTemplate restTemplate = ApplicationContextFactory.getBean("restTemplate", RestTemplate.class);
        String tmpTable = sql.substring(sql.indexOf("update") + 6, sql.indexOf("set"));
        String tmpTable = sql.substring(sql.indexOf("update") + 6, sql.indexOf("set ")).trim();
        String tmpTableHasT = tmpTable;
        if(tmpTable.indexOf(" ") > 0){
            tmpTable = tmpTable.substring(0,tmpTable.indexOf(" "));
        }
        String tmpWhere = sql.substring(sql.indexOf("where"));
        String tmpKey = sql.substring(sql.indexOf("set") + 3, sql.indexOf("where"));
        String[] tmpString = tmpKey.split(",");
        Map tmpAfterMap = new HashMap();
        for (String tmp : tmpString) {
            String[] keyValues = tmp.split("=");
            String key = "";
            if (keyValues.length != 2) {
                throw new IllegalArgumentException("update 语句可能有问题,没有 set 中出错 " + sql);
            }
            if (keyValues[0].contains(".")) {
                key = keyValues[0].substring(keyValues[0].indexOf(".") + 1);
            } else {
                key = keyValues[0];
            }
            tmpAfterMap.put(key.trim(), keyValues[1].trim());
        }
        if (tmpString == null || tmpString.length < 1) {
            throw new IllegalArgumentException("update 语句可能有问题,没有 set 内容 " + sql);
        }
        //插入操作时之前的 没有数据 所以 preValue 为空对象
        JSONArray preValues = new JSONArray();
        JSONArray afterValues = new JSONArray();
        JSONObject afterVaule = null;
        String execSql = "select * from " + tmpTable + " " + tmpWhere;
        String execSql = "select * from " + tmpTableHasT + " " + tmpWhere;
        queryServiceDAOImpl = ApplicationContextFactory.getBean("queryServiceDAOImpl", IQueryServiceDAO.class);
        List<Map<String, Object>> deleteDatas = queryServiceDAOImpl.executeSql(execSql, null);
@@ -177,7 +159,7 @@
                preValues.add(map);
                afterVaule = new JSONObject();
                afterVaule.putAll(map);
                afterVaule.putAll(tmpAfterMap);
                afterVaule.putAll(sqlValue);
                afterValues.add(afterVaule);
            }
        }
@@ -197,7 +179,11 @@
        String url = ServiceConstant.SERVICE_ORDER_URL + "/order/oIdApi/createOrderItem";
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity httpEntity = new HttpEntity(orderItemDto.toString(), httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        ResponseEntity<String> responseEntity = null;
        if(Environment.isStartBootWay()){
            url = ServiceConstant.BOOT_SERVICE_ORDER_URL + "/order/oIdApi/createOrderItem";
        }
        responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new IllegalArgumentException("注册事务回滚日志失败" + responseEntity);
@@ -216,9 +202,9 @@
                Date date = new Date(((Timestamp) value).getTime());
                String tmpValue = DateUtil.getFormatTimeString(date, DateUtil.DATE_FORMATE_STRING_A);
                map.put(key, "'" + tmpValue + "'");
            } else if(value instanceof Double){
            } else if (value instanceof Double) {
                map.put(key, "'" + map.get(key) + "'");
            }else {
            } else {
                if (value != null) {
                    map.put(key, "'" + value.toString() + "'");
                } else {
@@ -234,7 +220,7 @@
     * @param mappedStatement
     * @param parameter
     */
    private void dealInsertSql(MappedStatement mappedStatement, Object parameter, String sql) {
    private void dealInsertSql(MappedStatement mappedStatement, Object parameter, String sql, Map<String, Object> sqlValue) {
        // RestTemplate restTemplate = ApplicationContextFactory.getBean("restTemplate", RestTemplate.class);
@@ -242,24 +228,14 @@
        JSONArray preValues = new JSONArray();
        JSONArray afterValues = new JSONArray();
        JSONObject afterValue = new JSONObject();
        String tmpTable = sql.substring(sql.toLowerCase().indexOf("into") + 4, sql.indexOf("("));
        String tmpKey = sql.substring(sql.indexOf("(") + 1, sql.indexOf(")"));
        String tmpValue = sql.substring(sql.lastIndexOf("(") + 1, sql.lastIndexOf(")"));
        String[] tmpKeys = tmpKey.split(",");
        String[] tmpValues = tmpValue.split(",");
        if (tmpKeys.length != tmpValues.length) {
            throw new IllegalArgumentException("sql 错误 key 和value 个数不等" + sql);
        String tmpTable = sql.substring(sql.toLowerCase().indexOf("into") + 4, sql.indexOf("(")).trim();
        if(tmpTable.indexOf(" ") > 0){
            tmpTable = tmpTable.substring(0,tmpTable.indexOf(" "));
        }
        if (tmpKeys.length < 1) {
            throw new IllegalArgumentException("sql 错误 未找到key" + sql);
        }
        for (int keyIndex = 0; keyIndex < tmpKeys.length; keyIndex++) {
            afterValue.put(tmpKeys[keyIndex], tmpValues[keyIndex]);
        }
        afterValues.add(afterValue);
        afterValues.add(sqlValue);
        JSONObject logText = new JSONObject();
        logText.put("preValue", preValues);
@@ -276,6 +252,9 @@
        String url = ServiceConstant.SERVICE_ORDER_URL + "/order/oIdApi/createOrderItem";
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity httpEntity = new HttpEntity(orderItemDto.toString(), httpHeaders);
        if(Environment.isStartBootWay()){
            url = ServiceConstant.BOOT_SERVICE_ORDER_URL + "/order/oIdApi/createOrderItem";
        }
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
@@ -283,6 +262,7 @@
        }
    }
    @Override
    public Object plugin(Object target) {
@@ -296,31 +276,95 @@
    }
    public String showSql(Configuration configuration, BoundSql boundSql) {
    public String showSql(Configuration configuration, BoundSql boundSql, Map<String, Object> sqlValue, SqlCommandType sqlCommandType) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ").toLowerCase();
        String orgSql = sql;// 原始sql
        List<String> values = new ArrayList<>();
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
                values.add(getParameterValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                        String value = getParameterValue(obj);
                        if(value.contains("${")){
                            value = value.replace("${","\\${");
                        }
                        sql = sql.replaceFirst("\\?", value);
                        values.add(getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                        values.add(getParameterValue(obj));
                    }
                }
            }
        }
        return sql.toLowerCase();
        if (sqlCommandType == SqlCommandType.INSERT) {
            String tmpKey = orgSql.substring(orgSql.indexOf("(") + 1, orgSql.indexOf(")"));
            String[] tmpKeys = tmpKey.split(",");
//            if (values.size() < tmpKeys.length) {
//                throw new IllegalArgumentException("sql 错误 key P和value 个数不等" + sql);
//            }
            for (int keyIndex = 0; keyIndex < tmpKeys.length; keyIndex++) {
                String key = tmpKeys[keyIndex].trim();
                String value = "";
                if (values.size() - 1 < keyIndex) {
                    continue;
                }
                value = values.get(keyIndex);
                if ("''".equals(value)) {
                    continue;
                }
                sqlValue.put(key, value);
            }
        } else if (sqlCommandType == SqlCommandType.UPDATE) {
            String tmpKey = orgSql.substring(sql.indexOf("set") + 3, orgSql.indexOf("where"));
            String[] tmpKeys = tmpKey.split(",");
//            if (values.size() < tmpKeys.length) {
//                throw new IllegalArgumentException("sql 错误 key 和value 个数不等" + sql);
//            }
            for (int keyIndex = 0; keyIndex < tmpKeys.length; keyIndex++) {
                String tmpSetKey = tmpKeys[keyIndex];
                String[] keyValues = tmpSetKey.split("=");
                String key = "";
                if (keyValues.length != 2) {
                    throw new IllegalArgumentException("update 语句可能有问题,没有 set 中出错 " + sql);
                }
                if (keyValues[0].contains(".")) {
                    key = keyValues[0].substring(keyValues[0].indexOf(".") + 1).trim();
                } else {
                    key = keyValues[0].trim();
                }
                String value = "";
                if (values.size() - 1 < keyIndex) {
                    continue;
                }
                value = values.get(keyIndex);
                if ("''".equals(value)) {
                    continue;
                }
                sqlValue.put(key, value);
            }
        } else if (sqlCommandType == SqlCommandType.DELETE) {
        }
        return sql;
    }
    private String getParameterValue(Object obj) {
        String value = null;
@@ -334,10 +378,13 @@
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
                value = "''";
            }
        }
        return value;
    }
}