Java Code Examples for org.apache.ibatis.plugin.Invocation

The following examples show how to use org.apache.ibatis.plugin.Invocation. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: joyqueue   Source File: PaginationInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
    BoundSql boundSql = statementHandler.getBoundSql();
    if (log.isDebugEnabled()) {
        log.debug("raw SQL : " + boundSql.getSql());
    }
    if (boundSql.getSql() == null || boundSql.getSql().isEmpty() || boundSql.getSql().contains(" limit ")) {
        return invocation.proceed();
    }
    MetaObject metaStatementHandler = null;
    RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
    if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
        return invocation.proceed();
    }
    String originalSql = (String) metaStatementHandler.getValue("delegate.boundSql.sql");
    metaStatementHandler.setValue("delegate.boundSql.sql",
            getLimitString(originalSql, rowBounds.getOffset(), rowBounds.getLimit()));
    metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
    metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
    if (log.isDebugEnabled()) {
        log.debug("pagination SQL : " + boundSql.getSql());
    }
    return invocation.proceed();
}
 
Example 2
Source Project: joyqueue   Source File: PageResultInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    // 目标对象转换
    ResultSetHandler resultSetHandler = (ResultSetHandler) invocation.getTarget();

    // 获取MappedStatement,Configuration对象
    MetaObject metaObject =
            MetaObject.forObject(resultSetHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("mappedStatement");
    String statement = mappedStatement.getId();
    if (!isPageSql(statement,metaObject.getValue("boundSql.parameterObject"))) {
        return invocation.proceed();
    }

    // 获取分页参数
    QPageQuery pageQuery = (QPageQuery) metaObject.getValue("boundSql.parameterObject");

    List<PageResult> result = new ArrayList<PageResult>(1);
    PageResult page = new PageResult();
    page.setPagination(pageQuery.getPagination());
    page.setResult((List) invocation.proceed());
    result.add(page);

    return result;
}
 
Example 3
Source Project: mybatis-test   Source File: MySqlPagingPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    RowBounds rb = (RowBounds) args[ROW_BOUNDS_INDEX];
    if (rb == RowBounds.DEFAULT) {
        return invocation.proceed();
    }
    args[ROW_BOUNDS_INDEX] = RowBounds.DEFAULT;

    MappedStatement ms = (MappedStatement) args[MAPPED_STATEMENT_INDEX];
    BoundSql boundSql = ms.getBoundSql(args[PARAMETER_INDEX]);

    System.out.println();
    String sql = boundSql.getSql();
    String limit = String.format("LIMIT %d,%d", rb.getOffset(), rb.getLimit());
    sql = sql + " " + limit;

    SqlSource sqlSource = new StaticSqlSource(ms.getConfiguration(), sql, boundSql.getParameterMappings());

    Field field = MappedStatement.class.getDeclaredField("sqlSource");
    field.setAccessible(true);
    field.set(ms, sqlSource);

    return invocation.proceed();
}
 
Example 4
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object[] args = invocation.getArgs();
	MappedStatement ms = (MappedStatement) args[0];
	Object parameter = args[1];
	if (args[3] != null) {
		return invocation.proceed();
	}
	//用自定义handler
	CustomHandler handler = HandlerResolver.resolve(ms, parameter);
	if (handler == null) {
		return invocation.proceed();
	}
	args[3] = handler;
	invocation.proceed();
	return handler.getResult();
}
 
Example 5
Source Project: dubbo-mock   Source File: PageInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 拦截后要执行的方法
 */
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Page<?> page = PageThreadLocal.getThreadLocalPage();
    if (page == null) {
        return invocation.proceed();
    }
    PageThreadLocal.removeThreadLocalPage();
    RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();
    // 通过反射获取到当前RoutingStatementHandler对象的delegate属性
    StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");
    BoundSql boundSql = delegate.getBoundSql();
    MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement");
    // 获取当前要执行的Sql语句,也就是我们直接在Mapper映射语句中写的Sql语句
    String sql = boundSql.getSql();
    // 是否查询总页数和总数据 默认为TRUE
    if (page.getTotalFlag()) {
        // 给当前的page参数对象设置总记录数
        this.setTotalRecord(page, mappedStatement, boundSql, sql);
    }

    String pageSql = this.getPageSql(sql, page);
    // 利用反射设置当前BoundSql对应的sql属性为我们建立好的分页Sql语句
    ReflectUtil.setFieldValue(boundSql, "sql", pageSql);
    return invocation.proceed();
}
 
Example 6
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object object=invocation.getArgs()[0];
	if(object instanceof MappedStatement){
		MappedStatement  statement=(MappedStatement) object;
		Configuration config = statement.getConfiguration();
		DataSource dataSource= config.getEnvironment().getDataSource();
		if(dataSource instanceof DynamicDataSource){
			DynamicDataSource dynamicDataSource=((DynamicDataSource)dataSource); 
			Dialect dialect= dynamicDataSource.getDialect();
			if(pageHelpers.containsKey(dialect)){
				log.debug("将使用{}的PageHelper....",dialect);
				return pageHelpers.get(dialect).intercept(invocation);
			}else{
				log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
			}
		}else{
			log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
		}
	}else{
		log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
	}
	return pageHelper.intercept(invocation);
}
 
Example 7
Source Project: azeroth   Source File: RwRouteHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {

    Object[] objects = invocation.getArgs();
    MappedStatement ms = (MappedStatement) objects[0];
    //已指定强制使用
    if (DataSourceContextHolder.get().isForceUseMaster()) {
        logger.debug("Method[{}] force use Master..", ms.getId());
        return null;
    }

    //读方法
    if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
        //!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
        if (!ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
            DataSourceContextHolder.get().useSlave(true);
            logger.debug("Method[{} use Slave Strategy..", ms.getId());
        }
    } else {
        logger.debug("Method[{}] use Master Strategy..", ms.getId());
        DataSourceContextHolder.get().useSlave(false);
    }

    return null;
}
 
Example 8
Source Project: jeesuite-libs   Source File: RwRouteHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	//已指定强制使用
	if(MybatisRuntimeContext.isForceUseMaster()){
		logger.debug("Method[{}] force use Master..",ms.getId());
		return null;
	}
	
	//读方法
	if(ms.getSqlCommandType().equals(SqlCommandType.SELECT)){
		//!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
		if(!ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)){				
			MybatisRuntimeContext.useSlave(true);
			logger.debug("Method[{} use Slave Strategy..",ms.getId());
		}
	}else{
		logger.debug("Method[{}] use Master Strategy..",ms.getId());
		MybatisRuntimeContext.useSlave(false);
	}
	
	return null;
}
 
Example 9
Source Project: Zebra   Source File: PageInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private Object queryLimit(Invocation invocation, Object[] args, MappedStatement ms, BoundSql boundSql, RowBounds rb)
		throws InvocationTargetException, IllegalAccessException {
	String limitSql = dialect.getLimitSql(boundSql.getSql(), rb.getOffset(), rb.getLimit());
	BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), limitSql, boundSql.getParameterMappings(),
			boundSql.getParameterObject());
	MetaObject mo = (MetaObject) ReflectionUtils.getFieldValue(boundSql, "metaParameters");
	ReflectionUtils.setFieldValue(newBoundSql, "metaParameters", mo);

	args[0] = buildMappedStatement(ms, new SqlSourceWrapper(newBoundSql), ms.getId() + "_LIMIT",
			ms.getResultMaps());
	args[2] = new RowBounds();
	args[3] = null;

	try {
		DaoContextHolder.setSqlName(buildDaoName(ms.getId()) + "_LIMIT");
		return invocation.proceed();
	} finally {
		DaoContextHolder.clearSqlName();
	}
}
 
Example 10
Source Project: genericdao   Source File: SqlUtil.java    License: Artistic License 2.0 6 votes vote down vote up
/**
     * Mybatis拦截器方法
     *
     * @param invocation 拦截器入参
     * @return 返回执行结果
     * @throws Throwable 抛出异常
     */
    public Object processPage(Invocation invocation) throws Throwable {
        try{
            Object result = _processPage(invocation);
            clearLocalPage();
            //扩展当前分页对象,使用spring的分页对象
            if(result instanceof PageHelper){
//            	MybatisPage page = (MybatisPage) result ;
//            	Page resultPage = new PageImpl(page , new PageRequest(page.getPageNum(), page.getPageSize()), page.getTotal()) ;
//            	return resultPage ;
            	return new MybatisPageImpl((PageHelper) result) ;
            }
            return result;
        } finally {
            clearLocalPage();
        }
    }
 
Example 11
Source Project: easyooo-framework   Source File: PaginationPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object[] args = invocation.getArgs();
	
	// no paging
	if(!isPaging(args)){
		return invocation.proceed();
	}

	// process for paging
	InvocationContext context = getInvocationContext(invocation);
	InvocationContext newContext = processIntercept(context);

	swapParameter(newContext, args);
	Object result = invocation.proceed();
	
	if(result != null && result instanceof List){
		newContext.getPagination().setRecords((List<?>)result);
	}
	
	return result;
}
 
Example 12
Source Project: pinpoint   Source File: BindingLogPlugin32.java    License: Apache License 2.0 6 votes vote down vote up
private void bindingLog(Invocation invocation) throws SQLException {

        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        StatementType statementType = ms.getStatementType();
        if (StatementType.PREPARED == statementType || StatementType.CALLABLE == statementType) {
            Log statementLog = ms.getStatementLog();
            if (isDebugEnable(statementLog)) {
                BoundSql boundSql = ms.getBoundSql(parameterObject);

                String sql = boundSql.getSql();
                List<String> parameterList = getParameters(ms, parameterObject, boundSql);
                debug(statementLog, "==> BindingLog: " + bindLogFormatter.format(sql, parameterList));
            }
        }
    }
 
Example 13
@Override
public void inbound(HandlerContext ctx) throws Throwable {
    ExecutorInvocation executorInvocation = (ExecutorInvocation) ctx.getPipeline().getTarget();
    Invocation invocation = executorInvocation.getInvocation();
    String method = executorInvocation.getMethodName();
    if (!method.equals("query")) {
        executorInvocation.setResult(invocation.proceed());
    } else {
        if (executorInvocation.isBoundSqlChanged() && Objects.isNotNull(executorInvocation.getBoundSql())) {
            executorInvocation.setResult(executorInvocation.getExecutor().query(executorInvocation.getMappedStatement(), executorInvocation.getParameter(), executorInvocation.getRowBounds(), executorInvocation.getResultHandler(), executorInvocation.getCacheKey(), executorInvocation.getBoundSql()));
        } else {
            executorInvocation.setResult(invocation.proceed());
        }
    }
}
 
Example 14
Source Project: DDMQ   Source File: MybatisInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {
    Object returnValue;
    if (showDetailSql || showCostTime) {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();

        long start = System.currentTimeMillis();
        returnValue = invocation.proceed();
        long end = System.currentTimeMillis();
        long time = (end - start);

        String sql = getSql(configuration, boundSql, sqlId, time);
        if (slowSqlMs != 0 && time > slowSqlMs) {
            log.warn(sql);
        } else {
            log.info(sql);
        }
    } else {
        returnValue = invocation.proceed();
    }
    return returnValue;
}
 
Example 15
Source Project: mybatis-test   Source File: ExamplePlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    Object[] args = invocation.getArgs();
    System.out.println(method + " - " + args);
    return invocation.proceed();
}
 
Example 16
Source Project: ssm-demo   Source File: PageInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 拦截后要执行的方法
 */
public Object intercept(Invocation invocation) throws Throwable {
	// 对于StatementHandler其实只有两个实现类,
	// 一个是RoutingStatementHandler,
	// 另一个是抽象类BaseStatementHandler,
	// BaseStatementHandler有三个子类,分别是SimpleStatementHandler,PreparedStatementHandler和CallableStatementHandler,
	// SimpleStatementHandler是用于处理Statement的,
	// PreparedStatementHandler是处理PreparedStatement的,
	// 而CallableStatementHandler是 处理CallableStatement的。
	// Mybatis在进行Sql语句处理的时候都是建立的RoutingStatementHandler,而在RoutingStatementHandler里面拥有一个StatementHandler类型的delegate属性,
	// RoutingStatementHandler会依据Statement的不同建立对应的BaseStatementHandler,
	// 即SimpleStatementHandler、PreparedStatementHandler或CallableStatementHandler,
	// 在RoutingStatementHandler里面所有StatementHandler接口方法的实现都是调用的delegate对应的方法。
	// 我们在PageInterceptor类上已经用@Signature标记了该Interceptor只拦截StatementHandler接口的prepare方法,
	// 又因为Mybatis只有在建立RoutingStatementHandler的时候是通过Interceptor的plugin方法进行包裹的,
	// 所以我们这里拦截到的目标对象肯定是RoutingStatementHandler对象。
	RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();

	// 通过反射获取到当前RoutingStatementHandler对象的delegate属性
	StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");

	// 获取到当前StatementHandler的boundSql,这里不管是调用handler.getBoundSql()还是直接调用delegate.getBoundSql()结果是一样的,因为之前已经说过了
	// RoutingStatementHandler实现的所有StatementHandler接口方法里面都是调用的delegate对应的方法。
	BoundSql boundSql = delegate.getBoundSql();

	// 拿到当前绑定Sql的参数对象,就是我们在调用对应的Mapper映射语句时所传入的参数对象
	Object obj = boundSql.getParameterObject();

	// 这里我们简单的通过传入的是Page对象就认定它是需要进行分页操作的。
	if (obj instanceof Page<?>) {

		Page<?> page = (Page<?>) obj;

		// 通过反射获取delegate父类BaseStatementHandler的mappedStatement属性
		MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement");

		// 拦截到的prepare方法参数是一个Connection对象
		Connection connection = (Connection) invocation.getArgs()[0];

		// 获取当前要执行的Sql语句,也就是我们直接在Mapper映射语句中写的Sql语句
		String sql = boundSql.getSql();

		// 给当前的page参数对象设置总记录数
		this.setTotalRecord(page, mappedStatement, connection);

		// 获取分页Sql语句
		String pageSql = this.getPageSql(page, sql);

		// 利用反射设置当前BoundSql对应的sql属性为我们建立好的分页Sql语句
		ReflectUtil.setFieldValue(boundSql, "sql", pageSql);

	}

	return invocation.proceed();
}
 
Example 17
@Override
public Object plugin(Object target) {
	//只拦截Executor对象,减少目标被代理的次数
	if (target instanceof Executor) {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), interfaces, (InvocationHandler) (proxy, method, args) -> {
			if (method.getName().equals("query")) {
				return interceptor.intercept(new Invocation(target, method, args));
			}
			return method.invoke(target, args);
		});
	} else {
		return target;
	}
}
 
Example 18
Source Project: DDMQ   Source File: MybatisInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {
    Object returnValue;
    if (showDetailSql || showCostTime) {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();

        long start = System.currentTimeMillis();
        returnValue = invocation.proceed();
        long end = System.currentTimeMillis();
        long time = (end - start);

        String sql = getSql(configuration, boundSql, sqlId, time);
        if (slowSqlMs != 0 && time > slowSqlMs) {
            log.warn(sql);
        } else {
            log.info(sql);
        }
    } else {
        returnValue = invocation.proceed();
    }
    return returnValue;
}
 
Example 19
Source Project: blog   Source File: MyPlugin.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 代替拦截对象方法内容
 */
@Override
public Object intercept(Invocation invocation) throws Throwable {
	System.err.println("======before===============");
	Object obj = invocation.proceed();
	System.err.println("======after===============");
	return obj;
}
 
Example 20
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    MappedStatement mappedStatement = (MappedStatement) args[0];
    Object parameter = args[1];
    //从当前线程获取需要进行数据权限控制的业务
    DataPermission dataPermission = DPHelper.getLocalDataPermissions();
    //判断有没有进行数据权限控制,是不是最高权限的管理员(这里指的是数据权限的白名单用户)
    if (dataPermission != null && dataPermission.getAdmin() == false) {
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        String sql = boundSql.getSql();
        //获得方法类型
        Select select = (Select) CCJSqlParserUtil.parse(sql);
        select.getSelectBody().accept(new SelectVisitorImpl());
        //判断当前sql是否被修改
        if (DPHelper.getChangeTable()) {
            //访问各个visitor
            //TODO:解析动态sql会失败
            BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), select.toString(), boundSql
                    .getParameterMappings(), parameter);
            String newMsId = mappedStatement.getId() + DATA_PERMISSION;
            MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql), newMsId);
            args[0] = newMs;
            DPHelper.clearChangeTable();
        }
    }
    return invocation.proceed();
}
 
Example 21
Source Project: oneplatform   Source File: SsensitiveOperProtectHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	if(ms.getSqlCommandType().equals(SqlCommandType.DELETE)){
		throw new JeesuiteBaseException(ExceptionCode.OPTER_NOT_ALLOW.code, "当前已开启敏感操作保护");
	}
	return null;
}
 
Example 22
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	if(!ms.getSqlCommandType().equals(SqlCommandType.SELECT)){
		if(SecurityUtil.getLoginUserInfo().getName().startsWith("test")){
			throw new JeesuiteBaseException(4003, "测试账号已开启敏感操作保护");
		}
	}
	return null;
}
 
Example 23
Source Project: Shop-for-JavaWeb   Source File: PreparePaginationInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
    public Object intercept(Invocation ivk) throws Throwable {
        if (ivk.getTarget().getClass().isAssignableFrom(RoutingStatementHandler.class)) {
            final RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();
            final BaseStatementHandler delegate = (BaseStatementHandler) Reflections.getFieldValue(statementHandler, DELEGATE);
            final MappedStatement mappedStatement = (MappedStatement) Reflections.getFieldValue(delegate, MAPPED_STATEMENT);

//            //拦截需要分页的SQL
////            if (mappedStatement.getId().matches(_SQL_PATTERN)) { 
//            if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(), _SQL_PATTERN) != -1) {
                BoundSql boundSql = delegate.getBoundSql();
                //分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
                Object parameterObject = boundSql.getParameterObject();
                if (parameterObject == null) {
                    log.error("参数未实例化");
                    throw new NullPointerException("parameterObject尚未实例化!");
                } else {
                    final Connection connection = (Connection) ivk.getArgs()[0];
                    final String sql = boundSql.getSql();
                    //记录统计
                    final int count = SQLHelper.getCount(sql, connection, mappedStatement, parameterObject, boundSql, log);
                    Page<Object> page = null;
                    page = convertParameter(parameterObject, page);
                    page.setCount(count);
                    String pagingSql = SQLHelper.generatePageSql(sql, page, DIALECT);
                    if (log.isDebugEnabled()) {
                        log.debug("PAGE SQL:" + pagingSql);
                    }
                    //将分页sql语句反射回BoundSql.
                    Reflections.setFieldValue(boundSql, "sql", pagingSql);
                }
                
                if (boundSql.getSql() == null || "".equals(boundSql.getSql())){
                    return null;
                }
                
            }
//        }
        return ivk.proceed();
    }
 
Example 24
Source Project: jeesuite-libs   Source File: SensitiveOperProtectHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	if(ms.getSqlCommandType().equals(SqlCommandType.DELETE)){
		throw new JeesuiteBaseException(4003, "当前已开启敏感操作保护");
	}
	return null;
}
 
Example 25
Source Project: Zebra   Source File: PageInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object[] args = invocation.getArgs();
	Object rowBound = args[2];

	MappedStatement ms = (MappedStatement) args[0];
	if (rowBound != null) {
		RowBounds rb = (RowBounds) rowBound;

		// without pagination
		if (rb.getOffset() == RowBounds.NO_ROW_OFFSET && rb.getLimit() == RowBounds.NO_ROW_LIMIT) {
			return invocation.proceed();
		} else {
			BoundSql boundSql = ms.getBoundSql(args[1]);

			if (rowBound instanceof PageModel) {
				// physical pagination with PageModel
				PageModel pageModel = (PageModel) rowBound;
				Object count = queryCount(invocation, args, ms, boundSql);
				Object records = queryLimit(invocation, args, ms, boundSql, pageModel);

				pageModel.setRecordCount((Integer) ((List<?>) count).get(0));
				pageModel.setRecords((List<?>) records);

				return null;
			} else {
				// physical pagination with RowBounds
				return queryLimit(invocation, args, ms, boundSql, rb);
			}
		}
	} else {
		// without pagination
		return invocation.proceed();
	}
}
 
Example 26
Source Project: Zebra   Source File: PageInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private Object queryCount(Invocation invocation, Object[] args, MappedStatement ms, BoundSql boundSql)
		throws InvocationTargetException, IllegalAccessException {
	MappedStatement countRowStatement = COUNT_MAPPED_STATS.get(ms.getId());

	if (countRowStatement == null) {
		String countSql = dialect.getCountSql(boundSql.getSql());
		BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), countSql, boundSql.getParameterMappings(),
				boundSql.getParameterObject());
		MetaObject mo = (MetaObject) ReflectionUtils.getFieldValue(boundSql, "metaParameters");
		ReflectionUtils.setFieldValue(newBoundSql, "metaParameters", mo);
		Object additionalParameters = ReflectionUtils.getFieldValue(boundSql, "additionalParameters");
		ReflectionUtils.setFieldValue(newBoundSql, "additionalParameters", additionalParameters);
		List<ResultMap> resultMaps = new ArrayList<ResultMap>();
		ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), ms.getId(), int.class,
				EMPTY_RESULTMAPPING).build();
		resultMaps.add(resultMap);
		countRowStatement = buildMappedStatement(ms, new SqlSourceWrapper(newBoundSql), ms.getId() + "_COUNT",
				resultMaps);
	}

	args[0] = countRowStatement;
	args[2] = new RowBounds();
	args[3] = null;

	try {
		DaoContextHolder.setSqlName(buildDaoName(ms.getId()) + "_COUNT");
		return invocation.proceed();
	} finally {
		DaoContextHolder.clearSqlName();
	}
}
 
Example 27
Source Project: spring-data-mybatis   Source File: AuditingInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

	MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
	SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
	Object target = invocation.getArgs()[1];
	if (INSERT == sqlCommandType) {
		listener.touchForCreate(target);
	}
	else if (UPDATE == sqlCommandType) {
		listener.touchForUpdate(target);
	}
	return invocation.proceed();
}
 
Example 28
Source Project: flowable-engine   Source File: LogSqlExecutionTimePlugin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object retVal = invocation.proceed();
    long endTime = System.currentTimeMillis();
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    LOGGER.debug("SQL Statement {} took {}ms", mappedStatement.getId(), endTime-startTime);
    return retVal;
}
 
Example 29
Source Project: cicada   Source File: MybatisInterceptor.java    License: MIT License 5 votes vote down vote up
public Object intercept(final Invocation invocation) throws Throwable {
  final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
  Object returnValue = null;
  final long start = System.currentTimeMillis();
  returnValue = invocation.proceed();
  final long end = System.currentTimeMillis();

  final String sqlId = mappedStatement.getId();
  final int lastIndex = sqlId.lastIndexOf('.');
  final String className = sqlId.substring(0, lastIndex);
  final String methodName = sqlId.substring(lastIndex + 1);
  Tracer.getInstance().addBinaryAnnotation(className, methodName, (int) (end - start));

  return returnValue;
}
 
Example 30
Source Project: nexus-public   Source File: DataSessionRuleTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object intercept(final Invocation invocation) throws Throwable {
  if (failNextCommit) {
    // close connection without telling MyBatis - proceeding commit will then fail
    ((Executor) invocation.getTarget()).getTransaction().getConnection().close();
    failNextCommit = false;
  }
  return invocation.proceed();
}