235 lines
9.8 KiB
Java
235 lines
9.8 KiB
Java
package com.zhgd.mybatis;
|
|
|
|
import cn.hutool.core.collection.CollUtil;
|
|
import cn.hutool.core.util.StrUtil;
|
|
import com.alibaba.fastjson.JSONObject;
|
|
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
|
|
import com.baomidou.mybatisplus.core.toolkit.StringPool;
|
|
import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
|
|
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
|
|
import com.zhgd.annotation.DataScope;
|
|
import com.zhgd.xmgl.security.util.SecurityUtils;
|
|
import com.zhgd.xmgl.util.EnvironmentUtil;
|
|
import lombok.Setter;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import net.sf.jsqlparser.schema.Table;
|
|
import net.sf.jsqlparser.statement.insert.Insert;
|
|
import net.sf.jsqlparser.statement.select.*;
|
|
import org.apache.ibatis.executor.Executor;
|
|
import org.apache.ibatis.executor.statement.StatementHandler;
|
|
import org.apache.ibatis.mapping.BoundSql;
|
|
import org.apache.ibatis.mapping.MappedStatement;
|
|
import org.apache.ibatis.mapping.SqlCommandType;
|
|
import org.apache.ibatis.session.ResultHandler;
|
|
import org.apache.ibatis.session.RowBounds;
|
|
import org.springframework.web.context.request.RequestContextHolder;
|
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
|
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import java.lang.reflect.Method;
|
|
import java.sql.Connection;
|
|
import java.sql.SQLException;
|
|
import java.util.*;
|
|
|
|
@Slf4j
|
|
public class DataScopeInterceptor extends JsqlParserSupport implements InnerInterceptor {
|
|
|
|
@Setter
|
|
private DataScopeHandler dataScopeHandler;
|
|
|
|
public static boolean findIgnoreDataScope(Object parameter, DataScope annotation) {
|
|
if (annotation == null || !annotation.enable()) {
|
|
return true;
|
|
}
|
|
if (parameter instanceof Map) {
|
|
for (Object val : ((Map<?, ?>) parameter).values()) {
|
|
if (val instanceof String) {
|
|
if (val.equals("ignoreDataScope")) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (parameter instanceof String) {
|
|
return parameter.equals("ignoreDataScope");
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public static boolean isNotSqlTest() {
|
|
try {
|
|
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
|
|
return request.getParameter("qqq") == null;
|
|
} catch (Exception e) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
private static String getCallPositionForDev() {
|
|
StringBuilder sb = new StringBuilder();
|
|
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
|
|
for (StackTraceElement e : stackTrace) {
|
|
if (e.getClassName().startsWith("com.zhgd") && notInPackage(e.getClassName()) && !e.getClassName().contains("$$")) {
|
|
sb.append(StrUtil.subAfter(e.getClassName(),".",true));
|
|
sb.append(".");
|
|
sb.append(e.getMethodName());
|
|
sb.append("(");
|
|
sb.append(StrUtil.subAfter(e.getClassName(), ".", true));
|
|
sb.append(".java:");
|
|
sb.append(e.getLineNumber());
|
|
sb.append(")");
|
|
sb.append(" \r\n ");
|
|
sb.append(" > ");
|
|
}
|
|
}
|
|
return sb.toString();
|
|
}
|
|
|
|
private static boolean notInPackage(String className) {
|
|
return !className.startsWith("com.zhgd.mybatis") && !className.startsWith("com.zhgd.xmgl.config") && !className.startsWith("com.zhgd.xmgl.security");
|
|
}
|
|
|
|
private static String getCallPosition() {
|
|
StringBuilder sb = new StringBuilder();
|
|
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
|
|
for (StackTraceElement e : stackTrace) {
|
|
if (e.getClassName().startsWith("com.zhgd.xmgl")) {
|
|
sb.append(e.getClassName());
|
|
sb.append(".");
|
|
sb.append(e.getMethodName());
|
|
sb.append("(");
|
|
sb.append(StrUtil.subAfter(e.getClassName(), ".", true));
|
|
sb.append(".java:");
|
|
sb.append(e.getLineNumber());
|
|
sb.append(")");
|
|
break;
|
|
}
|
|
}
|
|
return sb.toString();
|
|
}
|
|
|
|
public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
|
|
PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
|
|
MappedStatement ms = mpSh.mappedStatement();
|
|
SqlCommandType sct = ms.getSqlCommandType();
|
|
try {
|
|
Class<?> clazz = Class.forName(ms.getId().substring(0, ms.getId().lastIndexOf(StringPool.DOT)));
|
|
String methodName = ms.getId().substring(ms.getId().lastIndexOf(".") + 1);
|
|
if (EnvironmentUtil.getActiveEnvironment().equals("gsx-other-env-show-dev")) {
|
|
//开发环境
|
|
if (sct == SqlCommandType.SELECT) {
|
|
log.debug("查询mapper: {} {}#{}", getCallPositionForDev(), clazz.getName(), methodName);
|
|
} else if (sct == SqlCommandType.UPDATE) {
|
|
log.debug("更新mapper: {} {}#{}", getCallPositionForDev(), clazz.getName(), methodName);
|
|
} else if (sct == SqlCommandType.INSERT) {
|
|
log.debug("插入mapper: {} {}#{}", getCallPositionForDev(), clazz.getName(), methodName);
|
|
} else if (sct == SqlCommandType.DELETE) {
|
|
log.debug("删除mapper: {} {}#{}", getCallPositionForDev(), clazz.getName(), methodName);
|
|
}
|
|
} else {
|
|
if (sct == SqlCommandType.SELECT) {
|
|
log.debug("查询mapper方法: {} >>> {}#{}", getCallPosition(), clazz.getName(), methodName);
|
|
} else if (sct == SqlCommandType.UPDATE) {
|
|
log.debug("更新mapper方法: {} >>> {}#{}", getCallPosition(), clazz.getName(), methodName);
|
|
} else if (sct == SqlCommandType.INSERT) {
|
|
log.debug("插入mapper方法: {} >>> {}#{}", getCallPosition(), clazz.getName(), methodName);
|
|
} else if (sct == SqlCommandType.DELETE) {
|
|
log.debug("删除mapper方法: {} >>> {}#{}", getCallPosition(), clazz.getName(), methodName);
|
|
}
|
|
}
|
|
} catch (Exception e) {
|
|
log.error(e.getMessage(), e);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
protected void processInsert(Insert insert, int index, String sql, Object obj) {
|
|
//dataScopeHandler.addParam(insert, obj);
|
|
}
|
|
|
|
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
|
|
try {
|
|
if (SecurityUtils.getUser() == null) {
|
|
return;
|
|
}
|
|
Class<?> clazz = Class.forName(ms.getId().substring(0, ms.getId().lastIndexOf(StringPool.DOT)));
|
|
String methodName = ms.getId().substring(ms.getId().lastIndexOf(".") + 1);
|
|
DataScope annotation = null;
|
|
Method[] declaredMethods = clazz.getDeclaredMethods();
|
|
Optional<DataScope> dsOption = Arrays.stream(declaredMethods).filter(method -> method.getName().equals(methodName)).map(method -> method.getAnnotation(DataScope.class)).filter(Objects::nonNull).findFirst();
|
|
annotation = dsOption.orElseGet(() -> clazz.getAnnotation(DataScope.class));
|
|
if (findIgnoreDataScope(parameter, annotation) && isNotSqlTest()) {
|
|
return;
|
|
}
|
|
PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
|
|
JSONObject jo = new JSONObject();
|
|
jo.put("ds", annotation);
|
|
jo.put("parameter", parameter);
|
|
mpBs.sql(this.parserSingle(mpBs.sql(), jo));
|
|
} catch (Exception e) {
|
|
log.error(e.getMessage(), e);
|
|
}
|
|
}
|
|
|
|
protected void processSelect(Select select, int index, String sql, Object obj) {
|
|
this.processSelectBody(select.getSelectBody(), obj);
|
|
}
|
|
|
|
protected void processSelectBody(SelectBody selectBody, Object obj) {
|
|
if (selectBody != null) {
|
|
if (selectBody instanceof PlainSelect) {
|
|
this.processPlainSelect((PlainSelect) selectBody, obj);
|
|
} else if (selectBody instanceof WithItem) {
|
|
WithItem withItem = (WithItem) selectBody;
|
|
this.processSelectBody(withItem.getSelectBody(), obj);
|
|
} else {
|
|
SetOperationList operationList = (SetOperationList) selectBody;
|
|
if (operationList.getSelects() != null && operationList.getSelects().size() > 0) {
|
|
this.processSelectBody(operationList.getSelects().get(0), obj);
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
protected void processPlainSelect(PlainSelect plainSelect, Object obj) {
|
|
FromItem fromItem = plainSelect.getFromItem();
|
|
if (fromItem instanceof Table) {
|
|
this.dataScopeHandler.getSqlSegment(plainSelect, obj);
|
|
} else {
|
|
processFromItem(fromItem, obj);
|
|
}
|
|
|
|
// 如果还存在关联查询
|
|
List<Join> joins = plainSelect.getJoins();
|
|
if (CollUtil.isNotEmpty(joins)) {
|
|
for (Join join : joins) {
|
|
processJoin(join, obj);
|
|
}
|
|
}
|
|
}
|
|
|
|
protected void processFromItem(FromItem fromItem, Object obj) {
|
|
if (fromItem instanceof SubSelect) {
|
|
SubSelect subSelect = (SubSelect) fromItem;
|
|
if (subSelect.getSelectBody() != null) {
|
|
processSelectBody(subSelect.getSelectBody(), obj);
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
* 处理关联查询
|
|
*
|
|
* @param join 关联查询
|
|
* @param obj
|
|
*/
|
|
protected void processJoin(Join join, Object obj) {
|
|
FromItem joinTable = join.getRightItem();
|
|
if (joinTable instanceof SubSelect) {
|
|
processSelectBody(((SubSelect) joinTable).getSelectBody(), obj);
|
|
}
|
|
}
|
|
}
|