org.aspectj.lang.Signature Java Examples

The following examples show how to use org.aspectj.lang.Signature. 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: WebLogAcpect.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    LogMenthodName logMenthodName = method.getAnnotation(LogMenthodName.class);
    String time = (System.currentTimeMillis() - startTime.get()) + "ms";
    if (method.isAnnotationPresent(LogMenthodName.class)) {
        String token = request.getHeader(AuthSign.token);
        Long id = AuthSign.getUserId(token);
        if (id != 0) {
            logAdminAgent.setReturnParam(Arrays.asList(ret).toString());
            logAdminAgent.setTime(time);
            logAdminAgent.setOperatorId(id);
            logAdminAgent.setOperatorPlatform(LogAdminAgentAppEnum.ANDROID_SYS.getSystem());
            logAdminAgent.setLoginFacility(HttpRequestUtil.getSystemDevice(request));
            logAdminAgentService.save(logAdminAgent);
        }
    }
    // 处理完请求,返回内容
    logger.info("返回内容: " + Arrays.asList(ret));
    logger.info("耗时 : " + time);
    startTime.remove();

}
 
Example #2
Source File: DatasourceSelectorAspect.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 前置操作,拦截具体请求,获取header里的数据源id,设置线程变量里,用于后续切换数据源
 */
@Before("datasourcePointcut()")
public void doBefore(JoinPoint joinPoint) {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    // 排除不可切换数据源的方法
    DefaultDatasource annotation = method.getAnnotation(DefaultDatasource.class);
    if (null != annotation) {
        DatasourceConfigContextHolder.setDefaultDatasource();
    } else {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        String configIdInHeader = request.getHeader("Datasource-Config-Id");
        if (StringUtils.hasText(configIdInHeader)) {
            long configId = Long.parseLong(configIdInHeader);
            DatasourceConfigContextHolder.setCurrentDatasourceConfig(configId);
        } else {
            DatasourceConfigContextHolder.setDefaultDatasource();
        }
    }
}
 
Example #3
Source File: AspectUtil.java    From FS-Blog with Apache License 2.0 6 votes vote down vote up
/**
 * 获取连接点的制定类型的注解
 *
 * @param joinPoint 连接点
 * @param clazz     注解类
 *
 * @return 注解
 */
public static Annotation getAnnotation(ProceedingJoinPoint joinPoint, Class clazz) {
  try {
    // 拦截的对象
    Object object = joinPoint.getTarget();
    Signature signature = joinPoint.getSignature();
    // 拦截方法名
    String methodName = signature.getName();
    Class[] parameterTypes = ((MethodSignature) signature).getMethod().getParameterTypes();

    try {
      // 反射目标方法
      Method method = object.getClass().getDeclaredMethod(methodName, parameterTypes);
      // 获取注解
      return method.getDeclaredAnnotation(clazz);
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    }
  } catch (Throwable throwable) {
    throwable.printStackTrace();
  }
  return null;
}
 
Example #4
Source File: PerformanceMonitor.java    From springboot-seed with MIT License 6 votes vote down vote up
/**
 * Monitor the elapsed time of method on controller layer, in
 * order to detect performance problems as soon as possible.
 * If elapsed time > 1 s, log it as an error. Otherwise, log it
 * as an info.
 */
@Around("controllerLayer()")
public Object monitorElapsedTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    // Timing the method in controller layer
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Object result = proceedingJoinPoint.proceed();
    stopWatch.stop();

    // Log the elapsed time
    double elapsedTime = stopWatch.getTime() / 1000.0;
    Signature signature = proceedingJoinPoint.getSignature();
    String infoString = "[" + signature.toShortString() + "][Elapsed time: " + elapsedTime + " s]";
    if (elapsedTime > 1) {
        log.error(infoString + "[Note that it's time consuming!]");
    } else {
        log.info(infoString);
    }

    // Return the result
    return result;
}
 
Example #5
Source File: HttpAspect.java    From yue-library with Apache License 2.0 6 votes vote down vote up
@Before("pointcut()")
	public void doVerifyBefore(JoinPoint joinPoint) {
        // 1. 参数校验
        Signature signature = joinPoint.getSignature();
        
        // 2. 开发环境-打印日志
        String ip = ServletUtils.getClientIP();
		String uri = request.getRequestURI();
//		UserDTO user_info = null;
//		if (!uri.startsWith("/open")) {
//			user_info = UserUtils.getUser(request, redis, UserDTO.class);
//		}
		
        log.info("ip={}", ip);
		log.info("uri={}", uri);
//		log.info("user_info={}", user_info);
		log.info("method={}", request.getMethod());
		log.info("class_method={}", signature.getDeclaringTypeName() + "." + signature.getName() + "()");
	}
 
Example #6
Source File: AbstractAspect.java    From kieker with Apache License 2.0 6 votes vote down vote up
/**
 * This is an advice which will be used after the construction of an object.
 *
 * @param thisObject
 * @param jp
 *            The static information about this joint point.
 */
// HINT: This may be logged multiple times due to super constructor calls...
@AfterReturning("monitoredConstructor() && this(thisObject) && notWithinKieker()")
public void afterConstruction(final Object thisObject, final JoinPoint.StaticPart jp) {
	if (!CTRLINST.isMonitoringEnabled()) {
		return;
	}
	final Signature signature = jp.getSignature();
	if (!CTRLINST.isProbeActivated(this.signatureToLongString(signature))) {
		return;
	}
	// common fields
	TraceMetadata trace = TRACEREGISTRY.getTrace();
	final boolean newTrace = trace == null;
	if (newTrace) {
		trace = TRACEREGISTRY.registerTrace();
		CTRLINST.newMonitoringRecord(trace);
	}
	final ConstructionEvent crecord = new ConstructionEvent(TIME.getTime(), trace.getTraceId(), trace.getNextOrderId(), signature.getDeclaringTypeName(),
			System.identityHashCode(thisObject));
	CTRLINST.newMonitoringRecord(crecord);
}
 
Example #7
Source File: MethodCallInterceptor.java    From cat-boot with Apache License 2.0 6 votes vote down vote up
@Around("monitored()")
public Object requestMapping(final ProceedingJoinPoint pcp) throws Throwable {
    Signature signature = pcp.getSignature();
    if (signature instanceof MethodSignature) {
        Method method = ((MethodSignature) signature).getMethod();

        MethodProfiling annotation = AnnotationUtils.findAnnotation(method, MethodProfiling.class);
        if (annotation == null) {
            annotation = AnnotationUtils.findAnnotation(pcp.getTarget().getClass(), MethodProfiling.class);
        }
        if (annotation != null) {
            return traceMethodCall(pcp, annotation.logCallStatistics(), annotation.logMethodCall(), annotation.maxToStringLength());
        }
    }
    return traceMethodCall(pcp);
}
 
Example #8
Source File: LogUtils.java    From MyUploader-Backend with Apache License 2.0 6 votes vote down vote up
/**
 * 日志输出到文件, 提供给日志切面
 * @param joinPoint
 * @param ex
 */
public static void logToFile(JoinPoint joinPoint, Throwable ex) {
    //出错行
    int lineNumber = ex.getStackTrace()[0].getLineNumber();
    //方法签名
    Signature signature = joinPoint.getSignature();
    //参数
    Object[] args = joinPoint.getArgs();
    StringBuilder builder = new StringBuilder();
    if (args.length > 0) {
        for (Object o : args) {
            builder.append(o);
        }
    }
    log.error("方法:" + signature + " | " + "参数:" + builder.toString() +
            " | " + "错误行:" + lineNumber + " | " + "时间:" + new Date() +
            " | " + "异常内容:" + ex.toString()
    );
}
 
Example #9
Source File: Metrics.java    From joinery with GNU General Public License v3.0 6 votes vote down vote up
private static Annotation getAnnotation(final Signature signature,
                            final Class<? extends Annotation> annotationClass) {
    if (signature instanceof ConstructorSignature) {
        final Constructor<?> ctor = ConstructorSignature.class.cast(signature)
                                .getConstructor();
        return ctor.getAnnotation(annotationClass);
    } else if (signature instanceof MethodSignature) {
        return MethodSignature.class.cast(signature)
                .getMethod()
                .getAnnotation(annotationClass);
    } else if (signature instanceof FieldSignature) {
        return FieldSignature.class.cast(signature)
                .getField()
                .getAnnotation(annotationClass);
    }

    throw new RuntimeException(
            "Unsupported signature type " + signature.getClass().getName()
        );
}
 
Example #10
Source File: LockableAspect.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
private Object execute(Class<? extends LockableStrategy> clazz, ProceedingJoinPoint point, Signature signature) throws Throwable {
    Method method = ((MethodSignature) signature).getMethod();
    // 获取锁策略
    LockableStrategy strategy = strategies.get(method);
    if (strategy == null) {
        synchronized (method) {
            if (strategy == null) {
                strategy = ReflectionUtility.getInstance(clazz, method);
                strategies.put(method, strategy);
            }
        }
    }
    Object[] arguments = point.getArgs();
    try (Lockable lock = strategy.getLock(arguments)) {
        lock.open();
        return point.proceed(arguments);
    }
}
 
Example #11
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 #12
Source File: WebAopLog.java    From Jpom with MIT License 6 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
    if (aopLogInterface != null) {
        aopLogInterface.before(joinPoint);
    }
    // 接收到请求,记录请求内容
    IS_LOG.set(ExtConfigBean.getInstance().isConsoleLogReqResponse());
    Signature signature = joinPoint.getSignature();
    if (signature instanceof MethodSignature) {
        MethodSignature methodSignature = (MethodSignature) signature;
        ResponseBody responseBody = methodSignature.getMethod().getAnnotation(ResponseBody.class);
        if (responseBody == null) {
            RestController restController = joinPoint.getTarget().getClass().getAnnotation(RestController.class);
            if (restController == null) {
                IS_LOG.set(false);
            }
        }
    }
}
 
Example #13
Source File: OptimisticLockAspect.java    From youran with Apache License 2.0 6 votes vote down vote up
@Around("servicePointcut()")
public Object doServiceAround(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
    Signature signature = thisJoinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    final Method targetMethod = methodSignature.getMethod();
    OptimisticLock optimisticLock = targetMethod.getAnnotation(OptimisticLock.class);
    if (optimisticLock == null) {
        throw new RuntimeException("乐观锁aop异常");
    }

    Class<? extends Exception>[] catchTypes = optimisticLock.catchType();
    if (catchTypes == null || catchTypes.length == 0) {
        throw new RuntimeException("乐观锁aop异常");
    }
    int retry = optimisticLock.retry();
    Object object = tryServiceProceed(thisJoinPoint, catchTypes, retry);
    return object;
}
 
Example #14
Source File: AspectjAopInterceptor.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
public Object checkAndDeleteCacheTransactional(ProceedingJoinPoint pjp) throws Throwable {
    Signature signature = pjp.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(CacheDeleteTransactional.class)) {
        CacheDeleteTransactional cache = method.getAnnotation(CacheDeleteTransactional.class);// method.getAnnotationsByType(Cache.class)[0];
        return this.deleteCacheTransactional(pjp, cache);
    }
    try {
        return pjp.proceed();
    } catch (Throwable e) {
        throw e;
    }
}
 
Example #15
Source File: TraceActivity.java    From ArgusAPM with Apache License 2.0 5 votes vote down vote up
@Around("activityOnXXX()")
public Object activityOnXXXAdvice(ProceedingJoinPoint proceedingJoinPoint) {
    Object result = null;
    try {
        Activity activity = (Activity) proceedingJoinPoint.getTarget();
        //        Log.d("AJAOP", "Aop Info" + activity.getClass().getCanonicalName() +
        //                "\r\nkind : " + thisJoinPoint.getKind() +
        //                "\r\nargs : " + thisJoinPoint.getArgs() +
        //                "\r\nClass : " + thisJoinPoint.getClass() +
        //                "\r\nsign : " + thisJoinPoint.getSignature() +
        //                "\r\nsource : " + thisJoinPoint.getSourceLocation() +
        //                "\r\nthis : " + thisJoinPoint.getThis()
        //        );
        long startTime = System.currentTimeMillis();
        result = proceedingJoinPoint.proceed();
        String activityName = activity.getClass().getCanonicalName();

        Signature signature = proceedingJoinPoint.getSignature();
        String sign = "";
        String methodName = "";
        if (signature != null) {
            sign = signature.toString();
            methodName = signature.getName();
        }

        if (!TextUtils.isEmpty(activityName) && !TextUtils.isEmpty(sign) && sign.contains(activityName)) {
            invoke(activity, startTime, methodName, sign);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    return result;
}
 
Example #16
Source File: WebLogAspect.java    From macrozheng-mall with MIT License 5 votes vote down vote up
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    //获取当前请求对象
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    //记录请求信息(通过logstash传入elasticsearch)
    WebLog webLog = new WebLog();
    Object result = joinPoint.proceed();
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(ApiOperation.class)) {
        ApiOperation log = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(log.value());
    }
    long endTime = System.currentTimeMillis();
    webLog.setBasePath(RequestUtil.getBasePath(request));
    webLog.setIp(request.getRemoteUser());
    webLog.setMethod(request.getMethod());
    webLog.setParameter(getParameter(method, joinPoint.getArgs()));
    webLog.setResult(result);
    webLog.setSpendTime((int) (endTime - startTime.get()));
    webLog.setStartTime(startTime.get());
    webLog.setUri(request.getRequestURI());
    webLog.setUrl(request.getRequestURL().toString());
    Map<String,Object> logMap = new HashMap<>();
    logMap.put("url",webLog.getUrl());
    logMap.put("method",webLog.getMethod());
    logMap.put("parameter",webLog.getParameter());
    logMap.put("spendTime",webLog.getSpendTime());
    logMap.put("description",webLog.getDescription());
    //        LOGGER.info("{}", JsonUtil.objectToJson(webLog));
    LOGGER.info(Markers.appendEntries(logMap),JsonUtil.objectToJson(webLog));
    return result;
}
 
Example #17
Source File: RetryAspect.java    From retry with Apache License 2.0 5 votes vote down vote up
private Method getCurrentMethod(ProceedingJoinPoint point) {
    try {
        Signature sig = point.getSignature();
        MethodSignature msig = (MethodSignature) sig;
        Object target = point.getTarget();
        return target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: VisitLogAspect.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
/**
 * 是否存在注解,如果存在就获取
 */
private VLog getAnnotationLog(JoinPoint joinPoint) {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method != null) {
        return method.getAnnotation(VLog.class);
    }
    return null;
}
 
Example #19
Source File: TxAdvice.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param thisJoinPoint
 * @return Object
 * @throws Throwable <br>
 */
@Around("tx()")
public Object invoke(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
    Signature sig = thisJoinPoint.getSignature();
    if (sig instanceof MethodSignature) {
        MethodSignature msig = (MethodSignature) sig;
        Object target = thisJoinPoint.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());

        Tx tx = AnnotationUtils.findAnnotation(currentMethod, Tx.class);
        if (tx != null && !TxManager.isRetry()) {

            ClientInfo clientInfo = new ClientInfo(TxManager.getTraceId(),
                StringUtils.isNotEmpty(tx.name()) ? tx.name() : TxManager.getMarker(currentMethod));
            clientInfo.setArgs(ArgsSerializationUtil.serializeArgs(thisJoinPoint.getArgs()));
            clientInfo.setMaxRetryTimes(tx.maxRetryTimes());
            clientInfo.setRetryConfigs(tx.retryConfigs());

            return TxInvokerProxy.registInvoke(clientInfo, () -> {
                try {
                    return thisJoinPoint.proceed();
                }
                catch (Throwable e) {
                    throw e instanceof FrameworkException ? (FrameworkException) e : new FrameworkException(e);
                }
            });
        }
    }

    return thisJoinPoint.proceed();
}
 
Example #20
Source File: LogAspect.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
/**
 * get annotation of <code>com.dimple.framework.aspectj.lang.annotation.Log</code>
 *
 * @param joinPoint join point
 * @return the annotation of <code>com.dimple.framework.aspectj.lang.annotation.Log</code>,if can not find will return <code>null</code>
 */
private Log getAnnotationLog(JoinPoint joinPoint) {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    if (method != null) {
        return method.getAnnotation(Log.class);
    }
    return null;
}
 
Example #21
Source File: WebLogAspect.java    From mall with Apache License 2.0 5 votes vote down vote up
@Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息(通过Logstash传入Elasticsearch)
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation log = method.getAnnotation(ApiOperation.class);
            webLog.setDescription(log.value());
        }
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.setIp(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        webLog.setSpendTime((int) (endTime - startTime));
        webLog.setStartTime(startTime);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        Map<String,Object> logMap = new HashMap<>();
        logMap.put("url",webLog.getUrl());
        logMap.put("method",webLog.getMethod());
        logMap.put("parameter",webLog.getParameter());
        logMap.put("spendTime",webLog.getSpendTime());
        logMap.put("description",webLog.getDescription());
//        LOGGER.info("{}", JSONUtil.parse(webLog));
        LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString());
        return result;
    }
 
Example #22
Source File: AspectjCacheAopProxyChain.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
@Override
public Method getMethod() {
    if (null == method) {
        Signature signature = jp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        this.method = methodSignature.getMethod();
    }
    return method;
}
 
Example #23
Source File: DebugLogAspect.java    From AndroidProject with Apache License 2.0 5 votes vote down vote up
/**
 * 方法执行完毕,切出
 *
 * @param result            方法执行后的结果
 * @param lengthMillis      执行方法所需要的时间
 */
private void exitMethod(ProceedingJoinPoint joinPoint, DebugLog debugLog, Object result, long lengthMillis) {
    if (!AppConfig.isDebug()) {
        return;
    }

    Trace.endSection();

    Signature signature = joinPoint.getSignature();

    String className = signature.getDeclaringType().getName();
    String methodName = signature.getName();

    StringBuilder builder = new StringBuilder("\u21E0 ")
            .append(className)
            .append(".")
            .append(methodName)
            .append(" [")
            .append(lengthMillis)
            .append("ms]");

    //  判断方法是否有返回值
    if (signature instanceof MethodSignature && ((MethodSignature) signature).getReturnType() != void.class) {
        builder.append(" = ");
        builder.append(result.toString());
    }

    log(debugLog.value(), builder.toString());
}
 
Example #24
Source File: ReadWriteSplittingAdvice.java    From tsharding with MIT License 5 votes vote down vote up
@Around("@annotation(com.mogujie.trade.db.ReadWriteSplitting)")
public Object intercept(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    Signature signature = proceedingJoinPoint.getSignature();
    DataSourceType dataSourceType = null;
    if (signature instanceof MethodSignature) {
        // 若已经在事务中 则不做处理
        if (RoutingDataSourceTransactionContext.getCurTransactionDataSource() != null) {
            return proceedingJoinPoint.proceed();
        }

        // 若已经设置为Master 则忽略
        if (ReadWriteSplittingContext.isMaster()) {
            return proceedingJoinPoint.proceed();
        }
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        dataSourceType = this.getDataSourceType(method);
    } else {
        // this may not happend.
        throw new ReadWriteSplittingException("ReadWriteSplitting annotation should only used on method. ");
    }
    ReadWriteSplittingContext.set(dataSourceType);
    logger.debug("{} {} using dataSourceOf {} ", proceedingJoinPoint.getTarget(),
            proceedingJoinPoint.getSignature(), dataSourceType);
    try {
        return proceedingJoinPoint.proceed();
    } finally {
        ReadWriteSplittingContext.clear();
        logger.debug("{} release dataSource of {}", proceedingJoinPoint.getTarget(), dataSourceType);
    }
}
 
Example #25
Source File: StatusCheckAspect.java    From DesignPatterns with Apache License 2.0 5 votes vote down vote up
/**
 * 环绕通知
 * @param pjp
 * @return
 * @throws Throwable
 */
@Around("declareJoinPointExpression()")
public Object doCheck(ProceedingJoinPoint pjp) throws Throwable {
    LOGGER.info("Status check around method start ....");
    Signature signature = pjp.getSignature();
    Class clazz = signature.getDeclaringType();
    boolean check = false;
    Method[] ms = clazz.getMethods();
    Method method = null;
    for(Method m : ms){
        boolean isMExist = m.isAnnotationPresent(StatusCheck.class);
        if(isMExist){
            check = true;
            method = m;
        }
    }

    if(check) {
        Object[] paramValues = pjp.getArgs();
        LOGGER.info("Status check dynamic AOP,paramValues:{}",paramValues);
        CheckResult checkResult = check(method,paramValues);
        if (checkResult != null && checkResult.getCheckResult() != VALID_UPDATE) {
            LOGGER.error("Status check failure,check method:{},paramValues:{},checkMsg:{}",method.getName(),paramValues,checkResult.getCheckMessage());
            return checkResult;
        }

    }
    //execute the target method
    CheckResult result = (CheckResult)pjp.proceed();
    LOGGER.info("execute the target method,the return result_msg:{}",result.getCheckMessage());
    LOGGER.info("Status check around method end ....");
    return result;
}
 
Example #26
Source File: AbstractAspect.java    From kieker with Apache License 2.0 5 votes vote down vote up
@Around("monitoredOperation() && this(thisObject) && !target(java.lang.Object) && notWithinKieker()")
public Object member2staticOperation(final Object thisObject, final ProceedingJoinPoint thisJoinPoint,
		final EnclosingStaticPart thisEnclosingJoinPoint) throws Throwable { // NOCS
	if (!CTRLINST.isMonitoringEnabled()) {
		return thisJoinPoint.proceed();
	}
	final Signature calleeSig = thisJoinPoint.getSignature();
	final String callee = this.signatureToLongString(calleeSig);
	if (!CTRLINST.isProbeActivated(callee)) {
		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();
	// caller
	final String caller = this.signatureToLongString(thisEnclosingJoinPoint.getSignature());
	final String callerClazz = thisObject.getClass().getName();
	final int callerObject = System.identityHashCode(thisObject);
	// callee
	final String calleeClazz = calleeSig.getDeclaringTypeName();
	// measure before call
	CTRLINST.newMonitoringRecord(new CallOperationObjectEvent(TIME.getTime(), traceId, trace.getNextOrderId(), caller, callerClazz, callee, calleeClazz,
			callerObject, 0));
	// call of the called method
	final Object retval;
	try {
		retval = thisJoinPoint.proceed();
	} finally {
		if (newTrace) { // close the trace
			TRACEREGISTRY.unregisterTrace();
		}
	}
	return retval;
}
 
Example #27
Source File: AspectjAopInterceptor.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
public Object checkAndProceed(ProceedingJoinPoint pjp) throws Throwable {
    Signature signature = pjp.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(Cache.class)) {
        Cache cache = method.getAnnotation(Cache.class);// method.getAnnotationsByType(Cache.class)[0];
        return this.proceed(pjp, cache);
    }

    try {
        return pjp.proceed();
    } catch (Throwable e) {
        throw e;
    }
}
 
Example #28
Source File: ServiceMonitor.java    From springboot-seed with MIT License 5 votes vote down vote up
/**
 * Monitor whether exception is thrown in service layer. If exception
 * has been thrown, in order to detecting it conveniently, log the
 * situation where it happened. Then create a server internal error
 * exception and throw it out.
 */
@AfterThrowing(pointcut = "com.wind.monitor.ServiceMonitor.serviceLayer()", throwing = "e")
public void monitorException(JoinPoint joinPoint, Throwable e) {
    // Log the situation where exception happened
    Object[] args = joinPoint.getArgs();
    Signature signature = joinPoint.getSignature();
    log.error("[" + signature.toShortString() + "]" + Arrays.toString(args) + "[" + e.toString() + "]");

    // Throw a new server internal error exception
    throw new ServerInternalErrorException(e.getMessage(), e);
}
 
Example #29
Source File: MethodInvocationProceedingJoinPoint.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Signature getSignature() {
	if (this.signature == null) {
		this.signature = new MethodSignatureImpl();
	}
	return this.signature;
}
 
Example #30
Source File: Utils.java    From automon with Apache License 2.0 5 votes vote down vote up
private static Object[] getParameterNames(Object[] argValues, JoinPoint jp) {
    Signature signature = jp.getSignature();
    if (signature instanceof CodeSignature) {
        return ((CodeSignature) signature).getParameterNames();
    } else {
        return new Object[argValues.length];
    }
}