Java Code Examples for org.aspectj.lang.ProceedingJoinPoint#proceed()

The following examples show how to use org.aspectj.lang.ProceedingJoinPoint#proceed() . 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 File: PortAuditor.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Audits the creation of a port.
 *
 * @param proceedingJoinPoint join point
 * @return port
 * @throws Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.PortDAO+) && "
        + "execution(org.apache.nifi.connectable.Port createPort(java.lang.String, org.apache.nifi.web.api.dto.PortDTO))")
public Port createPortAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    // perform the underlying operation
    Port port = (Port) proceedingJoinPoint.proceed();

    // audit the port creation
    final Action action = generateAuditRecord(port, Operation.Add);

    // save the actions
    if (action != null) {
        saveAction(action, logger);
    }

    return port;
}
 
Example 2
Source File: RetryAspect.java    From WeBASE-Collect-Bee with Apache License 2.0 6 votes vote down vote up
@Around("RetryPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    Method method = ((MethodSignature) point.getSignature()).getMethod();
    Retry retry = method.getAnnotation(Retry.class);
    for (int i = 0; i < retry.times(); i++) {
        try {
            if (i != 0) {
                log.info("The {} times to retry {}", i + 1, method.getName());
            }
            return point.proceed();
        } catch (IOException e) {
            log.error("IOException: {}", e.getMessage());
            Thread.sleep(retry.interval() * 1000);
        }
    }
    throw new IOException();
}
 
Example 3
Source File: RedisCacheAspect.java    From mall with Apache License 2.0 6 votes vote down vote up
@Around("cacheAspect()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    Object result = null;
    try {
        result = joinPoint.proceed();
    } catch (Throwable throwable) {
        //有CacheException注解的方法需要抛出异常
        if (method.isAnnotationPresent(CacheException.class)) {
            throw throwable;
        } else {
            LOGGER.error(throwable.getMessage());
        }
    }
    return result;
}
 
Example 4
Source File: CacheAspect.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * 定义String结构的缓存逻辑
 * 使用例子:
 * =====@Cache(dataStructure = DataStructure.string, key = "#viewnum", expireTime = 864000)
 *      public String aaa(String viewnum){.....}
 *  
 *
 * @author zhangshaobin
 * @created 2014年11月30日 上午2:51:11
 *
 * @param cache
 * @param method
 * @param pjp
 * @return
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 */
@SuppressWarnings({ "rawtypes" })
private Object hashString(Cache cache, Method method, ProceedingJoinPoint pjp) throws InstantiationException,
		IllegalAccessException {
	int exTime = cache.expireTime();
	String key = parseKey(cache.key(), method, pjp.getArgs());
	Object result = redisOperations.get(key);
	//获取方法返回信息
	Class clazz = (Class) method.getGenericReturnType();// 返回类型
	Object retObj = clazz.newInstance();
	if (retObj instanceof String) { // 判断返回值是不是字符串类型
		if (result == null) {
			try {
				result = pjp.proceed();
				Assert.notNull(key, "key 不能为空值!!");
				Assert.notNull(result, "key  result不能为空值!!");
				redisOperations.setex(key, exTime, result.toString());
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
	}
	return result;
}
 
Example 5
Source File: PerformanceAspect.java    From Spring with Apache License 2.0 5 votes vote down vote up
@Around("SystemArchitecture.Repository()")
public void trace(ProceedingJoinPoint proceedingJP) throws Throwable {
	String methodInformation = proceedingJP.getStaticPart().getSignature().toString();
	final StopWatch stopWatch = new StopWatch(methodInformation);
	stopWatch.start();
	trackCall();
	try {
		proceedingJP.proceed();
	}
	finally {
		stopWatch.stop();
		System.out.println(stopWatch.shortSummary());
	}
}
 
Example 6
Source File: UserAccessAspect.java    From SpringBootBucket with MIT License 5 votes vote down vote up
@Around("@annotation(userAccess)")
public Object around(ProceedingJoinPoint pjp, UserAccess userAccess) {
    //获取注解里的值
    System.out.println("second around:" + userAccess.desc());
    try {
        return pjp.proceed();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        return null;
    }
}
 
Example 7
Source File: UserLoginLogAop.java    From common-mvc with MIT License 5 votes vote down vote up
@Around(value = "createSession()")
public Object createSessionAround(ProceedingJoinPoint point) throws Throwable {
    Object res;
    res = point.proceed();


    ResultSet resultSet = (ResultSet) res;
    if(null == resultSet) return res;

    if(0 != resultSet.getCode()) return res; //打开此行则只记录登录成功的用户

    User user = null;
    String session = null;
    MapBuilder mapBuilder = null;
    if(null != resultSet.getData()) {
        mapBuilder = (MapBuilder) resultSet.getData();
        if(null != mapBuilder) {
            user = (User) mapBuilder.get("user");
            session = (String) mapBuilder.get("Authorization");
        }
    }

    //登录日志数据
    LoginLog loginLog = new LoginLog();
    if(null != user) {
        loginLog.setUserId(user.getId());
    }
    loginLog.setSignInIp(HttpRequestParserUtils.getUserIpAddr(httpServletRequest));
    loginLog.setDeviceInfo(HttpRequestParserUtils.getUserAgent(httpServletRequest));
    loginLog.setSignInTime(new Date());
    loginLog.setSuccess(0 == resultSet.getCode() ? DBEnum.TRUE.getCode() : DBEnum.FALSE.getCode());
    if(0 != resultSet.getCode()) {
        loginLog.setDetailsOfFail(resultSet.getMsg());
    }
    loginLog.setSignInParam(JSONUtils.obj2json(point.getArgs()));
    loginLog.setSession(session);
    loginLogService.insertLog(loginLog);

    return res;
}
 
Example 8
Source File: DisconfAspectJ.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * 获取配置项数据, 只有开启disconf远程才会进行切面
 *
 * @throws Throwable
 */
@Around("anyPublicMethod() && @annotation(disconfItem)")
public Object decideAccess(ProceedingJoinPoint pjp, DisconfItem disconfItem) throws Throwable {

    if (DisClientConfig.getInstance().ENABLE_DISCONF) {
        //
        // 请求仓库配置数据
        //
        DisconfStoreProcessor disconfStoreProcessor = DisconfStoreProcessorFactory.getDisconfStoreItemProcessor();
        Object ret = disconfStoreProcessor.getConfig(null, disconfItem.key());
        if (ret != null) {
            LOGGER.debug("using disconf store value: (" + disconfItem.key() + " , " + ret + ")");
            return ret;
        }
    }

    Object rtnOb;

    try {
        // 返回原值
        rtnOb = pjp.proceed();
    } catch (Throwable t) {
        LOGGER.info(t.getMessage());
        throw t;
    }

    return rtnOb;
}
 
Example 9
Source File: LogAopAspect.java    From permission with Apache License 2.0 5 votes vote down vote up
/**
 * 环绕通知记录日志通过注解匹配到需要增加日志功能的方法
 * 
 * @param pjp
 * @return
 * @throws Throwable
 */
@Around("@annotation(cn.lastwhisper.core.annotation.LogAnno)")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
	// 1.方法执行前的处理,相当于前置通知
	// 获取方法签名
	MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
	// 获取方法
	Method method = methodSignature.getMethod();
	// 获取方法上面的注解
	LogAnno logAnno = method.getAnnotation(LogAnno.class);
	// 获取操作描述的属性值
	String operateType = logAnno.operateType();
	// 创建一个日志对象(准备记录日志)
	Log log = new Log();
	log.setOperatetype(operateType);// 操作说明

	// 当前登录的用户
	User user = UserUtils.getSubjectUser();
	// 设置操作人账号
	log.setOperateor(user.getUser_code());
	String ip = UserUtils.getIpAddress();
	log.setIp(ip);
	Object result = null;
	try {
		// 让代理方法执行
		result = pjp.proceed();
		// 2.相当于后置通知(方法成功执行之后走这里)
		log.setOperateresult("正常");// 设置操作结果
	} catch (SQLException e) {
		// 3.相当于异常通知部分
		log.setOperateresult("异常");// 设置操作结果
	} finally {
		// 4.相当于最终通知
		log.setOperatedate(new Date());// 设置操作日期
		logService.addLog(log);// 添加日志记录
	}
	return result;
}
 
Example 10
Source File: SpringTestAspect.java    From tutorials with MIT License 5 votes vote down vote up
@Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))")
public Object auditMethod(ProceedingJoinPoint jp) throws Throwable {
    String methodName = jp.getSignature().getName();
    accumulator.add("Call to " + methodName);
    Object obj = jp.proceed();
    accumulator.add("Method called successfully: " + methodName);
    return obj;
}
 
Example 11
Source File: RxJava2RateLimiterAspectExt.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * @param proceedingJoinPoint Spring AOP proceedingJoinPoint
 * @param rateLimiter         the configured rateLimiter
 * @param methodName          the method name
 * @return the result object
 * @throws Throwable exception in case of faulty flow
 */
@Override
public Object handle(ProceedingJoinPoint proceedingJoinPoint, RateLimiter rateLimiter,
    String methodName) throws Throwable {
    RateLimiterOperator<?> rateLimiterOperator = RateLimiterOperator.of(rateLimiter);
    Object returnValue = proceedingJoinPoint.proceed();
    return executeRxJava2Aspect(rateLimiterOperator, returnValue);
}
 
Example 12
Source File: OptimisticLockAspect.java    From youran with Apache License 2.0 5 votes vote down vote up
@Around("daoPointcut()")
public Object doDAOAround(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
    Object[] args = thisJoinPoint.getArgs();
    int count = (int) thisJoinPoint.proceed();
    if ((args[0] instanceof Version) && count <= 0) {
        throw new OptimisticException("更新操作乐观锁异常");
    }
    return count;
}
 
Example 13
Source File: ParameterContextAuditor.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Audits the configuration of a parameter context via updateParameterContext().
 *
 * @param proceedingJoinPoint join point
 * @param parameterContextDTO dto
 * @param parameterContextDAO dao
 * @return parameter context
 * @throws Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.ParameterContextDAO+) && "
        + "execution(org.apache.nifi.parameter.ParameterContext updateParameterContext(org.apache.nifi.web.api.dto.ParameterContextDTO)) && "
        + "args(parameterContextDTO) && "
        + "target(parameterContextDAO)")
public ParameterContext updateParameterContextAdvice(ProceedingJoinPoint proceedingJoinPoint, ParameterContextDTO parameterContextDTO, ParameterContextDAO parameterContextDAO) throws Throwable {
    // determine the initial values for each property/setting that's changing
    ParameterContext parameterContext = parameterContextDAO.getParameterContext(parameterContextDTO.getId());
    final Map<String, String> values = extractConfiguredParameterContextValues(parameterContext, parameterContextDTO);

    // update the processor state
    final ParameterContext updatedParameterContext = (ParameterContext) proceedingJoinPoint.proceed();

    // if no exceptions were thrown, add the processor action...
    parameterContext = parameterContextDAO.getParameterContext(updatedParameterContext.getIdentifier());

    // get the current user
    NiFiUser user = NiFiUserUtils.getNiFiUser();

    // ensure the user was found
    if (user != null) {
        // determine the updated values
        Map<String, String> updatedValues = extractConfiguredParameterContextValues(parameterContext, parameterContextDTO);

        // create a parameter context action
        Date actionTimestamp = new Date();
        Collection<Action> actions = new ArrayList<>();

        // determine the actions performed in this request
        determineActions(user, parameterContext, actions, actionTimestamp, updatedValues, values);

        // ensure there are actions to record
        if (!actions.isEmpty()) {
            // save the actions
            saveActions(actions, logger);
        }
    }

    return updatedParameterContext;
}
 
Example 14
Source File: JdbcAspect.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * Intercepts calls to {@link DataSource#getConnection()} (and related), wrapping the outcome in a
 * {@link TracingConnection} proxy
 *
 * @param pjp the intercepted join point
 * @return a new {@link TracingConnection} proxy wrapping the result of the joint point
 * @throws Throwable in case of wrong JDBC URL
 */
@Around("execution(java.sql.Connection *.getConnection(..)) && target(javax.sql.DataSource)")
public Object getConnection(final ProceedingJoinPoint pjp) throws Throwable {
  Connection conn = (Connection) pjp.proceed();
  if (WrapperProxy.isWrapper(conn, TracingConnection.class)) {
    return conn;
  }
  String url = conn.getMetaData().getURL();
  ConnectionInfo connectionInfo = URLParser.parse(url);
  return WrapperProxy.wrap(conn, new TracingConnection(conn, connectionInfo,
      withActiveSpanOnly, ignoredStatements, GlobalTracer.get()));
}
 
Example 15
Source File: TestXmlAspect.java    From HotswapAgent with GNU General Public License v2.0 4 votes vote down vote up
@Around("execution(* org.hotswap.agent.plugin.spring.testBeans.BeanServiceNoAutowireImpl.hello(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
    return pjp.proceed() + "WithAspect";
}
 
Example 16
Source File: CSRFAspect.java    From LazyREST with Apache License 2.0 4 votes vote down vote up
/**
 * 验证时间戳
 * 验证签名
 * 验证ip
 * .....
 *
 * @param pjp
 * @return
 * @throws Throwable
 */
@Around("controllerAspect()")
public Object execute(ProceedingJoinPoint pjp) throws Throwable {
    // 从切点上获取目标方法
    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String sign = request.getHeader(SIGN);
    String timestamp = request.getHeader(TIMESTAMP);//.substring(0, 11)

    if (StringUtils.isEmpty(sign) || StringUtils.isEmpty(timestamp)) {
        throw new UserException("客户端参数异常");
    }

    /**
     *
     * 验证时间戳如果跟当前时间相差2秒则视为请求无效
     *
     */

    long serverTimestamp = Long.parseLong(String.valueOf(System.currentTimeMillis()).substring(0, 11));

    if ((serverTimestamp - Long.parseLong(timestamp) > 2000)) {
        throw new UserException("客户端参数异常");
    }

    /**
     *
     * 验证签名  sign =  HTTPMETHOD(GET/POST/DELETE/PUT)+ uri(API的访问URI)+timestamp(UNIX时间戳)+length(发送body的数据长度--post才有)\
     *
     * 按照自己项目需求可加入一些动态的验证token机制
     *
     */

    String serverSign = EndecryptUtil.encrytMD5(request.getMethod() + request.getRequestURI() + timestamp);

    if (!(serverSign.equals(sign))) {
        throw new UserException("客户端参数异常");
    }

    // 调用目标方法
    return pjp.proceed();
}
 
Example 17
Source File: AbstractAspectJAdvisorFactoryTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Around(value="org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.Library.integerArgOperation(x)", argNames="x")
public void doubleArg(ProceedingJoinPoint pjp, int x) throws Throwable {
	pjp.proceed(new Object[] {x*2});
}
 
Example 18
Source File: AspectProxyFactoryTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Around("execution(* setAge(*))")
public Object doLog(ProceedingJoinPoint pjp) throws Throwable {
	LogFactory.getLog(LoggingAspectOnSetter.class).debug(Arrays.asList(pjp.getArgs()));
	return pjp.proceed();
}
 
Example 19
Source File: HtmlSanitizer.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Around("execution(* cc.openhome.controller.MemberController.newMessage(..))")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    Object[] args = proceedingJoinPoint.getArgs();
    args[0] = policy.sanitize(args[0].toString());
    return proceedingJoinPoint.proceed(args);
}
 
Example 20
Source File: UserGroupAuditor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Audits the configuration of a single user.
 *
 * @param proceedingJoinPoint join point
 * @param userGroupDTO dto
 * @param userGroupDAO dao
 * @return node
 * @throws Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.UserGroupDAO+) && "
        + "execution(org.apache.nifi.authorization.Group updateUserGroup(org.apache.nifi.web.api.dto.UserGroupDTO)) && "
        + "args(userGroupDTO) && "
        + "target(userGroupDAO)")
public Group updateUserAdvice(ProceedingJoinPoint proceedingJoinPoint, UserGroupDTO userGroupDTO, UserGroupDAO userGroupDAO) throws Throwable {
    // determine the initial values for each property/setting that's changing
    Group user = userGroupDAO.getUserGroup(userGroupDTO.getId());
    final Map<String, String> values = extractConfiguredPropertyValues(user, userGroupDTO);

    // update the user state
    final Group updatedUserGroup = (Group) proceedingJoinPoint.proceed();

    // if no exceptions were thrown, add the user group action...
    user = userGroupDAO.getUserGroup(updatedUserGroup.getIdentifier());

    // get the current user
    NiFiUser niFiUser = NiFiUserUtils.getNiFiUser();

    // ensure the user was found
    if (niFiUser != null) {
        // determine the updated values
        Map<String, String> updatedValues = extractConfiguredPropertyValues(user, userGroupDTO);

        // create a user action
        Date actionTimestamp = new Date();
        Collection<Action> actions = new ArrayList<>();

        // go through each updated value
        for (String property : updatedValues.keySet()) {
            String newValue = updatedValues.get(property);
            String oldValue = values.get(property);
            Operation operation = null;

            // determine the type of operation
            if (oldValue == null || newValue == null || !newValue.equals(oldValue)) {
                operation = Operation.Configure;
            }

            // create a configuration action accordingly
            if (operation != null) {
                final FlowChangeConfigureDetails actionDetails = new FlowChangeConfigureDetails();
                actionDetails.setName(property);
                actionDetails.setValue(newValue);
                actionDetails.setPreviousValue(oldValue);

                // create a configuration action
                FlowChangeAction configurationAction = new FlowChangeAction();
                configurationAction.setUserIdentity(niFiUser.getIdentity());
                configurationAction.setOperation(operation);
                configurationAction.setTimestamp(actionTimestamp);
                configurationAction.setSourceId(user.getIdentifier());
                configurationAction.setSourceName(user.getName());
                configurationAction.setSourceType(Component.UserGroup);
                configurationAction.setActionDetails(actionDetails);
                actions.add(configurationAction);
            }
        }

        // ensure there are actions to record
        if (!actions.isEmpty()) {
            // save the actions
            saveActions(actions, logger);
        }
    }

    return updatedUserGroup;
}