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

The following examples show how to use org.aspectj.lang.ProceedingJoinPoint#getSignature() . 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: DebugLogAspect.java    From AndroidProject with Apache License 2.0 6 votes vote down vote up
/**
 * 方法执行前切入
 */
private void enterMethod(ProceedingJoinPoint joinPoint, DebugLog debugLog) {
    if (!AppConfig.isDebug()) {
        return;
    }

    CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();

    // 方法所在类
    String className = codeSignature.getDeclaringType().getName();
    // 方法名
    String methodName = codeSignature.getName();
    // 方法参数名集合
    String[] parameterNames = codeSignature.getParameterNames();
    // 方法参数集合
    Object[] parameterValues = joinPoint.getArgs();

    //记录并打印方法的信息
    StringBuilder builder = getMethodLogInfo(className, methodName, parameterNames, parameterValues);

    log(debugLog.value(), builder.toString());

    final String section = builder.toString().substring(2);
    Trace.beginSection(section);
}
 
Example 2
Source File: DataSourceAspect.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable
{
    MethodSignature signature = (MethodSignature) point.getSignature();

    Method method = signature.getMethod();

    DataSource dataSource = method.getAnnotation(DataSource.class);

    if (StringUtils.isNotNull(dataSource))
    {
        DynamicDataSourceContextHolder.setDateSoureType(dataSource.value().name());
    }

    try
    {
        return point.proceed();
    }
    finally
    {
        // 销毁数据源 在执行方法之后
        DynamicDataSourceContextHolder.clearDateSoureType();
    }
}
 
Example 3
Source File: SqlRouterAspect.java    From dubbox with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param joinPoint
 * @param sqlHint
 * @throws Throwable
 * @date 2016年11月30日
 * @author Ternence
 */
private void process(ProceedingJoinPoint joinPoint, String sqlHint) throws Throwable {
	try {
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();

		RouterInfo info = new RouterInfo(msHint.getRouteMasterHint());
		if (method != null) {
			MasterOnly annotation = method.getAnnotation(MasterOnly.class);
			Scope scope = annotation.scope();
			info.setScope(scope);
		}

		RouterContext.put(RouterConsts.ROUTER_KEY, info);
		joinPoint.proceed();
	} finally {
		RouterContext.cleanup();
	}
}
 
Example 4
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 5
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if(MDC.get(APIConstants.CORRELATION_ID) == null) {
        if (messageContext != null) {
            Map headers =
                    (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null) {
                String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
                if (correlationId != null) {
                    MDC.put(APIConstants.CORRELATION_ID, correlationId);
                }
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 6
Source File: RedisLockAspect.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 将spel表达式转换为字符串
 * @param joinPoint 切点
 * @return redisKey
 */
private String getRedisKey(ProceedingJoinPoint joinPoint,String lockName,String spel) {
	Signature signature = joinPoint.getSignature();
	MethodSignature methodSignature = (MethodSignature) signature;
	Method targetMethod = methodSignature.getMethod();
	Object target = joinPoint.getTarget();
	Object[] arguments = joinPoint.getArgs();
	return REDISSON_LOCK_PREFIX + lockName + StrUtil.COLON + SpelUtil.parse(target,spel, targetMethod, arguments);
}
 
Example 7
Source File: DataSourceAspect.java    From spring-boot-study with MIT License 5 votes vote down vote up
/**
 * 拦截方法指定为 dataSourcePointCut
 * */
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Class targetClass = point.getTarget().getClass();
    Method method = signature.getMethod();

    DataSource targetDataSource = (DataSource)targetClass.getAnnotation(DataSource.class);
    DataSource methodDataSource = method.getAnnotation(DataSource.class);
    if(targetDataSource != null || methodDataSource != null){
        String value;
        if(methodDataSource != null){
            value = methodDataSource.value();
        }else {
            value = targetDataSource.value();
        }

        DynamicContextHolder.setDataSource(value);
        logger.debug("set datasource is {}", value);
    }

    try {
        return point.proceed();
    } finally {
        DynamicContextHolder.clearDataSource();
        logger.debug("clean datasource");
    }
}
 
Example 8
Source File: SysLogAspect.java    From sdb-mall with Apache License 2.0 5 votes vote down vote up
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
	MethodSignature signature = (MethodSignature) joinPoint.getSignature();
	Method method = signature.getMethod();

	io.sdb.model.SysLog sysLog = new io.sdb.model.SysLog();
	SysLog syslog = method.getAnnotation(SysLog.class);
	if(syslog != null){
		//注解上的描述
		sysLog.setOperation(syslog.value());
	}

	//请求的方法名
	String className = joinPoint.getTarget().getClass().getName();
	String methodName = signature.getName();
	sysLog.setMethod(className + "." + methodName + "()");

	//请求的参数
	Object[] args = joinPoint.getArgs();
	try{
		String params = new Gson().toJson(args[0]);
		sysLog.setParams(params);
	}catch (Exception e){

	}

	//获取request
	HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
	//设置IP地址
	sysLog.setIp(IPUtils.getIpAddr(request));

	//用户名
	String username = ((SysUser) SecurityUtils.getSubject().getPrincipal()).getUsername();
	sysLog.setUsername(username);

	sysLog.setTime(time);
	sysLog.setCreateDate(new Date());
	//保存系统日志
	sysLog.save();
}
 
Example 9
Source File: AbstractAspect.java    From kieker with Apache License 2.0 5 votes vote down vote up
@Around("monitoredOperation() && !this(java.lang.Object) && notWithinKieker()")
public Object staticOperation(final ProceedingJoinPoint thisJoinPoint) throws Throwable { // NOCS (Throwable)
	if (!CTRLINST.isMonitoringEnabled()) {
		return thisJoinPoint.proceed();
	}
	final Signature sig = thisJoinPoint.getSignature();
	final String operationSignature = this.signatureToLongString(sig);
	if (!CTRLINST.isProbeActivated(operationSignature)) {
		return thisJoinPoint.proceed();
	}
	// common fields
	TraceMetadata trace = TRACEREGISTRY.getTrace();
	final boolean newTrace = trace == null;
	if (newTrace) {
		trace = TRACEREGISTRY.registerTrace();
		CTRLINST.newMonitoringRecord(trace);
	}
	final long traceId = trace.getTraceId();
	final String clazz = sig.getDeclaringTypeName();
	// measure before execution
	CTRLINST.newMonitoringRecord(new BeforeOperationEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz));
	// execution of the called method
	final Object retval;
	try {
		retval = thisJoinPoint.proceed();
	} catch (final Throwable th) { // NOPMD NOCS (catch throw might ok here)
		// measure after failed execution
		CTRLINST.newMonitoringRecord(new AfterOperationFailedEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz, th.toString()));
		throw th;
	} finally {
		if (newTrace) { // close the trace
			TRACEREGISTRY.unregisterTrace();
		}
	}
	// measure after successful execution
	CTRLINST.newMonitoringRecord(new AfterOperationEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz));
	return retval;
}
 
Example 10
Source File: MergeCore.java    From ace-merge with Apache License 2.0 5 votes vote down vote up
/**
 * aop方式加工
 *
 * @param pjp
 * @param anno
 * @return
 * @throws Throwable
 */
public Object mergeData(ProceedingJoinPoint pjp, MergeResult anno) throws Throwable {
    Object proceed = pjp.proceed();
    try {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method m = signature.getMethod();
        ParameterizedType parameterizedType = (ParameterizedType) m.getGenericReturnType();
        Type rawType = parameterizedType.getRawType();
        List<?> result = null;
        // 获取当前方法的返回值
        Type[] types = parameterizedType.getActualTypeArguments();
        Class clazz = ((Class) types[0]);
        // 非list直接返回
        if (anno.resultParser().equals(DefaultMergeResultParser.class) && ((Class) rawType).isAssignableFrom(List.class)) {
            result = (List<?>) proceed;
            mergeResult(clazz, result);
            return result;
        } else {
            IMergeResultParser bean = BeanFactoryUtils.getBean(anno.resultParser());
            result = bean.parser(proceed);
            mergeResult(clazz, result);
            return proceed;
        }
    } catch (Exception e) {
        log.error("某属性数据聚合失败", e);
        return proceed;
    }

}
 
Example 11
Source File: JsonRawStringAspect.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * TODO(P2) try to do this with aspect @DeclareError
  *
 * Checks that the method annotated with {@link JsonRawString} also has the
 * {@link JsonRawValue} for Jackson to actually serialize as expected.
 *
 * @param pjp
 */
private void checkMethodHasJsonRawValueAnnotation(ProceedingJoinPoint pjp) {

    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method targetMethod = methodSignature.getMethod();

    if (targetMethod.getAnnotation(JsonRawValue.class) == null) {
        throw new RuntimeException("The method annotated with @JsonRawString must also be annotated with @JsonRawValue");
    }
}
 
Example 12
Source File: PrintRunTimeAop.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
@Around(value = "pointcut() && @annotation(com.github.misterchangray.common.annotation.PrintRunTime)")
public Object around(ProceedingJoinPoint point) throws Throwable {
    Long time, time2;
    Object res;
    time = new Date().getTime();
    res = point.proceed();

    time2 = new Date().getTime();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();

    System.out.println("[" + DateUtils.dateToStr(new Date()) + "] " + method + "- has spend " + ((time2 - time) / 1000) + "s");

    return  res;
}
 
Example 13
Source File: TraceAspect.java    From Android-AOPExample with Apache License 2.0 5 votes vote down vote up
@Around("methodAnnotatedWithDebugTrace() || constructorAnnotatedDebugTrace()")
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
  String className = methodSignature.getDeclaringType().getSimpleName();
  String methodName = methodSignature.getName();

  final StopWatch stopWatch = new StopWatch();
  stopWatch.start();
  Object result = joinPoint.proceed();
  stopWatch.stop();

  DebugLog.log(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis()));

  return result;
}
 
Example 14
Source File: DataSourceAspect.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 获取需要切换的数据源
 */
public DataSource getDataSource(ProceedingJoinPoint point)
{
    MethodSignature signature = (MethodSignature) point.getSignature();
    DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
    if (Objects.nonNull(dataSource))
    {
        return dataSource;
    }

    return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
}
 
Example 15
Source File: StopWatchAdvice.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Around advice that logs methods times for all service methods.
 *
 * @param pjp the proceeding join point.
 *
 * @return the return value of the method we are advising.
 * @throws Throwable if there were any problems executing the method.
 */
@Around("serviceMethods()")
public Object logMethodTime(ProceedingJoinPoint pjp) throws Throwable
{
    // Get the target class being called.
    Class<?> targetClass = pjp.getTarget().getClass();

    // Get the target method being called.
    MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature();
    Method targetMethod = targetMethodSignature.getMethod();
    if (targetMethod.getDeclaringClass().isInterface())
    {
        // Get the underlying implementation if we are given an interface.
        targetMethod = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), targetMethod.getParameterTypes());
    }

    // Only keep a stop watch if the class and method aren't suppressing logging and the log level is info.
    if ((AnnotationUtils.findAnnotation(targetClass, SuppressLogging.class) == null) &&
        (AnnotationUtils.findAnnotation(targetMethod, SuppressLogging.class) == null) && (LOGGER.isInfoEnabled()))
    {
        // Start the stop watch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Proceed to the join point (i.e. call the method and let it return).
        Object returnValue = pjp.proceed();

        // Log the duration.
        long durationMilliseconds = stopWatch.getTime();
        LOGGER.info("javaMethod=\"{}.{}\" javaMethodDurationTimeInMilliseconds={} javaMethodDurationTimeFormatted=\"{}\"", targetClass.getName(),
            targetMethodSignature.getName(), durationMilliseconds, HerdDateUtils.formatDuration(durationMilliseconds));

        // Return the method return value.
        return returnValue;
    }
    else
    {
        // Invoke the method normally.
        return pjp.proceed();
    }
}
 
Example 16
Source File: ReliableOnConsumedAspect.java    From x7 with Apache License 2.0 4 votes vote down vote up
@Around("cut() && @annotation(reliableOnConsumed) ")
public void around(ProceedingJoinPoint proceedingJoinPoint, ReliableOnConsumed reliableOnConsumed) {

    Object[] args = proceedingJoinPoint.getArgs();
    Object message = args[0];

    Signature signature = proceedingJoinPoint.getSignature();
    String logStr = signature.getDeclaringTypeName() + "." + signature.getName();

    String nextTopic = reliableOnConsumed.nextTopic();
    String[] svcs = reliableOnConsumed.nextSvcs();
    if (StringUtil.isNotNull(nextTopic)){
        if (svcs == null || svcs.length == 0){
            throw new IllegalArgumentException(logStr + ", if config nextTopic, svcs of io.xream.x7.reliable.ReliableOnConsumed can not null, nextTopic: " + nextTopic);
        }
    }

    String svc = reliableOnConsumed.svc();
    if (StringUtil.isNullOrEmpty(svc)){
        svc = VerifyUtil.toMD5(logStr).substring(0,10);
    }

    this.backend.onConsumed(svc, message,
            () -> {
                try {
                    MethodSignature ms = ((MethodSignature) signature);
                    if (ms.getReturnType() == void.class) {
                        proceedingJoinPoint.proceed();
                    } else {
                        Object nextBody = proceedingJoinPoint.proceed();
                        String id = MessageIdGenerator.get();
                        int maxTry = reliableOnConsumed.nextRetryMax();
                        if (StringUtil.isNotNull(nextTopic)){
                            boolean flag = this.backend.createNext(id,maxTry,nextTopic,nextBody,message,svcs);
                            if (!flag){
                                throw new RuntimeException(logStr + ", produce next topic failed: topic: " + nextTopic + ", message:"+ message + ",next body: " + nextBody);
                            }
                        }
                    }
                } catch (Throwable e) {
                    throw new RuntimeException(ExceptionUtil.getMessage(e));
                }
            }
    );

}
 
Example 17
Source File: LogAdvice.java    From spring-boot-practice with Apache License 2.0 4 votes vote down vote up
private String getMethodName(ProceedingJoinPoint pjp) {
    Signature sig = pjp.getSignature();
    return sig.getDeclaringType().getSimpleName() + "#" + sig.getName();
}
 
Example 18
Source File: LogAspect.java    From easyweb with Apache License 2.0 4 votes vote down vote up
@Around("execution(* *..controller..*.*(..))")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		// 获取request
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
		HttpServletRequest request = servletRequestAttributes.getRequest();
		SysLog log=new SysLog();
		// 从注解中获取操作名称、获取响应结果
		Object result = pjp.proceed();
		Signature signature = pjp.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();
		log.setTitle("未知");
		if (method.isAnnotationPresent(ApiOperation.class)) {
			ApiOperation logA = method.getAnnotation(ApiOperation.class);
			log.setTitle(logA.value());

		}

//		if (method.isAnnotationPresent(RequiresPermissions.class)) {
//			RequiresPermissions requiresPermissions = method.getAnnotation(RequiresPermissions.class);
//			String[] permissions = requiresPermissions.value();
//			if (permissions.length > 0) {
//				upmsLog.setPermissions(permissions[0]);
//			}
//		}

		LogUtils.saveLog(request,log);
		endTime = System.currentTimeMillis();
		_log.debug("doAround>>>result={},耗时:{}", result, endTime - startTime);
//		upmsLog.setBasePath(RequestUtil.getBasePath(request));
//		upmsLog.setIp(RequestUtil.getIpAddr(request));
//		upmsLog.setMethod(request.getMethod());
//		if (request.getMethod().equalsIgnoreCase("GET")) {
//			upmsLog.setParameter(request.getQueryString());
//		} else {
//			upmsLog.setParameter(ObjectUtils.toString(request.getParameterMap()));
//		}
//		upmsLog.setLogId(StringUtil.guid());
//		upmsLog.setResult(ObjectUtils.toString(result));
//		upmsLog.setSpendTime((int) (endTime - startTime));
//		upmsLog.setStartTime(startTime);
//		upmsLog.setUri(request.getRequestURI());
//		upmsLog.setUrl(ObjectUtils.toString(request.getRequestURL()));
//		upmsLog.setUserAgent(request.getHeader("User-Agent"));
//		upmsLog.setUsername(ObjectUtils.toString(request.getUserPrincipal()));
//		upmsApiService.insertUpmsLogSelective(upmsLog);
		return result;
	}
 
Example 19
Source File: AbstractAspect.java    From kieker with Apache License 2.0 4 votes vote down vote up
/**
 * This advice is used around static operations.
 *
 * @param thisJoinPoint
 *            The joint point of the advice.
 *
 * @return The return value of the joint point's {@code proceed} method.
 *
 * @throws Throwable
 */
@Around("monitoredOperation() && !this(java.lang.Object) && notWithinKieker()")
public Object staticOperation(final ProceedingJoinPoint thisJoinPoint) throws Throwable { // NOCS (Throwable)
	if (!CTRLINST.isMonitoringEnabled()) {
		return thisJoinPoint.proceed();
	}
	final Signature sig = thisJoinPoint.getSignature();
	final String operationSignature = this.signatureToLongString(sig);
	if (!CTRLINST.isProbeActivated(operationSignature)) {
		return thisJoinPoint.proceed();
	}
	// common fields
	TraceMetadata trace = TRACEREGISTRY.getTrace();
	final boolean newTrace = trace == null;
	if (newTrace) {
		trace = TRACEREGISTRY.registerTrace();
		CTRLINST.newMonitoringRecord(trace);
	}
	final long traceId = trace.getTraceId();
	final String clazz = sig.getDeclaringTypeName();
	// measure before execution
	CTRLINST.newMonitoringRecord(new BeforeOperationObjectInterfaceEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz, 0,
			AbstractAspect.getInterface(thisJoinPoint)));
	// execution of the called method
	final Object retval;
	try {
		retval = thisJoinPoint.proceed();
	} catch (final Throwable th) { // NOPMD NOCS (catch throw might ok here)
		// measure after failed execution
		CTRLINST.newMonitoringRecord(new AfterOperationFailedObjectEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz,
				th.toString(), 0));
		throw th;
	} finally {
		if (newTrace) { // close the trace
			TRACEREGISTRY.unregisterTrace();
		}
	}
	// measure after successful execution
	CTRLINST.newMonitoringRecord(new AfterOperationObjectEvent(TIME.getTime(), traceId, trace.getNextOrderId(), operationSignature, clazz, 0));
	return retval;
}
 
Example 20
Source File: AspectJUtils.java    From mojito with Apache License 2.0 3 votes vote down vote up
private <T extends Annotation> List<AnnotatedMethodParam<T>> findAnnotatedMethodParams(ProceedingJoinPoint pjp, Class<T> searchedAnnotation, boolean stopOnFirst) {

        List<AnnotatedMethodParam<T>> list = new ArrayList<>();

        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method m = ms.getMethod();

        Annotation[][] parameterAnnotations = m.getParameterAnnotations();

        boolean notFoundFirst = true;
        Object[] args = pjp.getArgs();

        for (int i = 0; i < parameterAnnotations.length && notFoundFirst; i++) {

            Annotation[] annotations = parameterAnnotations[i];

            for (int j = 0; j < annotations.length && notFoundFirst; j++) {
                Annotation annotation = annotations[j];

                if (searchedAnnotation.isInstance(annotation)) {
                    list.add(new AnnotatedMethodParam(annotation, i, args[i]));

                    if(stopOnFirst) {
                        notFoundFirst = false;
                    }
                }
            }
        }

        return list;
    }