org.aspectj.lang.ProceedingJoinPoint Java Examples

The following examples show how to use org.aspectj.lang.ProceedingJoinPoint. 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: SyncDatabaseExt.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Around("syncDeleteEsData()")  
   public Object syncDeleteEsData(ProceedingJoinPoint pjp) throws Throwable{  
   	Object[] args  = pjp.getArgs() ;
   	if(args.length == 1){
   		Object data = args[0] ;
   		if(data instanceof List){
   			List<Object> dataList = (List<Object>)data ;
   			for(Object dbData : dataList){
   				UKTools.multiupdate(new MultiUpdateEvent<Object>(dbData , dbDataRes, UKDataContext.MultiUpdateType.DELETE.toString()));
   			}
   		}else{
   			if(data instanceof ESBean){
   				UKTools.multiupdate(new MultiUpdateEvent<Object>(data, dbDataRes, UKDataContext.MultiUpdateType.DELETE.toString()));
   			}else{
   				UKTools.multiupdate(new MultiUpdateEvent<Object>(data, dbDataRes, UKDataContext.MultiUpdateType.DELETE.toString()));
   			}
   		}
   	}
       return pjp.proceed();  
   }
 
Example #2
Source File: TIPSystemIntegrationModuleImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@Profiled(
   logFailuresSeparately = true,
   tag = "0.TIPSystemIntegrationModuleImpl#getStatusMessages",
   logger = "org.perf4j.TimingLogger_Executor"
)
public String getStatusMessages(String sGuid, String dGuid) throws IntegrationModuleException {
   JoinPoint var14 = Factory.makeJP(ajc$tjp_6, this, this, sGuid, dGuid);
   TimingAspect var10000 = TimingAspect.aspectOf();
   Object[] var15 = new Object[]{this, sGuid, dGuid, var14};
   ProceedingJoinPoint var10001 = (new TIPSystemIntegrationModuleImpl$AjcClosure13(var15)).linkClosureAndJoinPoint(69648);
   Annotation var10002 = ajc$anno$6;
   if (ajc$anno$6 == null) {
      var10002 = ajc$anno$6 = TIPSystemIntegrationModuleImpl.class.getDeclaredMethod("getStatusMessages", String.class, String.class).getAnnotation(Profiled.class);
   }

   return (String)var10000.doPerfLogging(var10001, (Profiled)var10002);
}
 
Example #3
Source File: SysLogRecoderAspect.java    From mumu with Apache License 2.0 6 votes vote down vote up
/**
 * 处理注解MumuLog日志
 * @param joinPoint
 * @return
 * @throws Throwable
 */
private Object  handleAnnotationLog(ProceedingJoinPoint joinPoint) throws Throwable {
	//获取请求方法
	Method requestMethod = getMethod(joinPoint.getTarget().getClass(), joinPoint.getSignature().getName(), joinPoint.getArgs());
	if (requestMethod == null) {
		throw new RuntimeException("oh my god! it serious problem!");
	}
	requestMethod.setAccessible(true);

	Object proceed=null;
	//日志注解
	MumuLog log = requestMethod.getAnnotation(MumuLog.class);
	if (log != null && log.required()) {
		SysUserLog userLog = buildLog(joinPoint);
		userLog.setContent(log.name());
		userLog.setOperateType(log.operater());
		userLog.setUserLogStatus(PublicEnum.NORMAL.value());
		userLogService.addSysUserLog(userLog);
		proceed=userLog.getProceed();
	}else{
		proceed=joinPoint.proceed();
	}
	//handlerLoginLog(joinPoint,proceed);
	return proceed;
}
 
Example #4
Source File: FlenderAspect.java    From flender with Apache License 2.0 6 votes vote down vote up
@Around("mobileAnnotatedMethod()")
public void checkMobileConnectivity(ProceedingJoinPoint joinPoint) throws Throwable {

    if (Flender.isConnectedMobile()) {
        joinPoint.proceed();
    } else {
        String mode = getMobileAnnotationParameter(joinPoint);

        if (mode.equals("silent")) {

        } else if (mode.equals("alert")) {
            if (Flender.getMobileUnavailable() != null) {
                Flender.getMobileUnavailable().flenderEvent();
            } else {
                Flender.Toast("Mobile network not available");
            }
        } else {
            throw new UnsupportedModeException("Unsupported mode,leave parameter empty or set to Silent.");
        }
    }
}
 
Example #5
Source File: BindingResultAspect.java    From HIS with Apache License 2.0 6 votes vote down vote up
@Around("BindingResult()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    for (Object arg : args) {
        if (arg instanceof BindingResult) {
            BindingResult result = (BindingResult) arg;
            if (result.hasErrors()) {
                FieldError fieldError = result.getFieldError();
                if(fieldError!=null){
                    return CommonResult.validateFailed(fieldError.getDefaultMessage());
                }else{
                    return CommonResult.validateFailed();
                }
            }
        }
    }
    return joinPoint.proceed();
}
 
Example #6
Source File: LoggingAspect.java    From Full-Stack-Development-with-JHipster with MIT License 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice
 * @return result
 * @throws Throwable throws IllegalArgumentException
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example #7
Source File: LoggingAspect.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice
 * @return result
 * @throws Throwable throws IllegalArgumentException
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example #8
Source File: AbstractIntegrationModule.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@Profiled(
   logFailuresSeparately = true,
   tag = "0.AbstractIntegrationModule#unsealPrescriptionForUnknown",
   logger = "org.perf4j.TimingLogger_Common"
)
protected byte[] unsealPrescriptionForUnknown(KeyResult key, byte[] protectedMessage) throws IntegrationModuleException {
   JoinPoint var5 = Factory.makeJP(ajc$tjp_2, this, this, key, protectedMessage);
   TimingAspect var10000 = TimingAspect.aspectOf();
   Object[] var6 = new Object[]{this, key, protectedMessage, var5};
   ProceedingJoinPoint var10001 = (new AbstractIntegrationModule$AjcClosure5(var6)).linkClosureAndJoinPoint(69648);
   Annotation var10002 = ajc$anno$2;
   if (ajc$anno$2 == null) {
      var10002 = ajc$anno$2 = AbstractIntegrationModule.class.getDeclaredMethod("unsealPrescriptionForUnknown", KeyResult.class, byte[].class).getAnnotation(Profiled.class);
   }

   return (byte[])var10000.doPerfLogging(var10001, (Profiled)var10002);
}
 
Example #9
Source File: BindPointAspect.java    From GyJdbc with Apache License 2.0 6 votes vote down vote up
@Around("processMethod()||processClass()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    Object object = point.getTarget();
    BindPoint classBindPoint = object.getClass().getAnnotation(BindPoint.class);
    if (classBindPoint != null) {
        DataSourceBindHolder.setDataSource(DataSourceBind.bindPoint(classBindPoint));
    }
    String methodName = point.getSignature().getName();
    MethodSignature methodSignature = ((MethodSignature) point.getSignature());
    Class<?>[] parameterTypes = methodSignature.getMethod().getParameterTypes();
    Method method = object.getClass().getMethod(methodName, parameterTypes);
    BindPoint methodBindPoint = method.getAnnotation(BindPoint.class);
    if (methodBindPoint != null) {
        DataSourceBindHolder.setDataSource(DataSourceBind.bindPoint(methodBindPoint));
    }
    try {
        return point.proceed();
    } finally {
        DataSourceBindHolder.clearDataSource();
    }
}
 
Example #10
Source File: KmehrHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@Profiled(
   logFailuresSeparately = true,
   tag = "IntegrationModule#XMLNotificationValidation"
)
public void assertValidNotification(byte[] xmlDocument) throws IntegrationModuleException {
   JoinPoint var3 = Factory.makeJP(ajc$tjp_0, this, this, (Object)xmlDocument);
   TimingAspect var10000 = TimingAspect.aspectOf();
   Object[] var4 = new Object[]{this, xmlDocument, var3};
   ProceedingJoinPoint var10001 = (new KmehrHelper$AjcClosure1(var4)).linkClosureAndJoinPoint(69648);
   Annotation var10002 = ajc$anno$0;
   if (ajc$anno$0 == null) {
      var10002 = ajc$anno$0 = KmehrHelper.class.getDeclaredMethod("assertValidNotification", byte[].class).getAnnotation(Profiled.class);
   }

   var10000.doPerfLogging(var10001, (Profiled)var10002);
}
 
Example #11
Source File: CallMonitoringAspect.java    From java-microservice with MIT License 6 votes vote down vote up
@Around("@annotation(com.apssouza.monitoring.Monitored)")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("callend");
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    if (this.enabled) {
        StopWatch sw = new StopWatch(joinPoint.toShortString());

        sw.start("invoke");
        try {
            return joinPoint.proceed();
        } finally {
            sw.stop();
            synchronized (this) {
                this.callCount++;
                this.accumulatedCallTime += sw.getTotalTimeMillis();
            }
            publisher.publishEvent(new MonitoringInvokedEvent(
                    method.getName(),
                    this.accumulatedCallTime
            ));
        }
    } else {
        return joinPoint.proceed();
    }
}
 
Example #12
Source File: LoggingAspect.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice.
 * @return result.
 * @throws Throwable throws {@link IllegalArgumentException}.
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Logger log = logger(joinPoint);
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName());
        throw e;
    }
}
 
Example #13
Source File: ControllerAop.java    From sanshanblog with Apache License 2.0 6 votes vote down vote up
@Around("responseMsgVoPointcut()")
public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
    long startTime = System.currentTimeMillis();

    ResponseMsgVO<?> result;

    try {
        result = (ResponseMsgVO<?>) pjp.proceed();
        log.info("method:"+pjp.getSignature() + " use time:" + (System.currentTimeMillis() - startTime)+"ms");
    } catch (Throwable e) {
        result = handlerException(pjp, e);
        log.info("method:"+pjp.getSignature() + " use time:" + (System.currentTimeMillis() - startTime)+"ms");
    }

    return result;
}
 
Example #14
Source File: LogAspect.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Around("(execution (public * org.jasig.cas..*.*(..))) && !(execution( * org.jasig.cas..*.set*(..)))")
public Object traceMethod(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    Object returnVal = null;
    final Logger logger = this.getLog(proceedingJoinPoint);
    final String methodName = proceedingJoinPoint.getSignature().getName();

    try {
        if (logger.isTraceEnabled()) {
            final Object[] args = proceedingJoinPoint.getArgs();
            final String arguments;
            if (args == null || args.length == 0) {
                arguments = "";
            } else {
                arguments = Arrays.deepToString(args);
            }
            logger.trace("Entering method [{}] with arguments [{}]", methodName, arguments);
        }
        returnVal = proceedingJoinPoint.proceed();
        return returnVal;
    } finally {
        logger.trace("Leaving method [{}] with return value [{}].", methodName,
                    (returnVal != null ? returnVal.toString() : "null"));
    }
}
 
Example #15
Source File: AbstractAspectJAdvice.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public void setArgumentNamesFromStringArray(String... args) {
	this.argumentNames = new String[args.length];
	for (int i = 0; i < args.length; i++) {
		this.argumentNames[i] = StringUtils.trimWhitespace(args[i]);
		if (!isVariableName(this.argumentNames[i])) {
			throw new IllegalArgumentException(
					"'argumentNames' property of AbstractAspectJAdvice contains an argument name '" +
					this.argumentNames[i] + "' that is not a valid Java identifier");
		}
	}
	if (this.argumentNames != null) {
		if (this.aspectJAdviceMethod.getParameterCount() == this.argumentNames.length + 1) {
			// May need to add implicit join point arg name...
			Class<?> firstArgType = this.aspectJAdviceMethod.getParameterTypes()[0];
			if (firstArgType == JoinPoint.class ||
					firstArgType == ProceedingJoinPoint.class ||
					firstArgType == JoinPoint.StaticPart.class) {
				String[] oldNames = this.argumentNames;
				this.argumentNames = new String[oldNames.length + 1];
				this.argumentNames[0] = "THIS_JOIN_POINT";
				System.arraycopy(oldNames, 0, this.argumentNames, 1, oldNames.length);
			}
		}
	}
}
 
Example #16
Source File: CheckUtil.java    From layui-admin with MIT License 6 votes vote down vote up
/**
 * 校验model上的注解
 *
 * @param pjp 连接点
 */
public static void checkModel(ProceedingJoinPoint pjp) {
    StringBuilder sb = new StringBuilder();
    try {
        //找到BindingResult参数
        List<BindingResult> results = getBindingResult(pjp);
        if (results != null && !results.isEmpty()) {
            for (BindingResult result : results) {
                if (null != result && result.hasErrors()) {
                    //拼接错误信息
                    if (null != result.getFieldErrors()) {
                        for (FieldError fe : result.getFieldErrors()) {
                            sb.append(fe.getField() + "-" + fe.getDefaultMessage()).append(" ");
                        }
                    }
                }
            }

            if (StringUtils.isNotBlank(sb.toString())) {
                fail(sb.toString());//抛出检查异常
            }
        }
    } catch (Exception e) {
        fail(e.getMessage());//抛出检查异常
    }
}
 
Example #17
Source File: AbstractSentinelAspectSupport.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
protected Object handleDefaultFallback(ProceedingJoinPoint pjp, String defaultFallback,
                                       Class<?>[] fallbackClass, Throwable ex) throws Throwable {
    // Execute the default fallback function if configured.
    Method fallbackMethod = extractDefaultFallbackMethod(pjp, defaultFallback, fallbackClass);
    if (fallbackMethod != null) {
        // Construct args.
        Object[] args = fallbackMethod.getParameterTypes().length == 0 ? new Object[0] : new Object[] {ex};
        if (isStatic(fallbackMethod)) {
            return fallbackMethod.invoke(null, args);
        }
        return fallbackMethod.invoke(pjp.getTarget(), args);
    }

    // If no any fallback is present, then directly throw the exception.
    throw ex;
}
 
Example #18
Source File: FirstNameAspect.java    From openregistry with Apache License 2.0 6 votes vote down vote up
@Around("set(@org.openregistry.core.domain.normalization.FirstName * *)")
public Object transformFieldValue(final ProceedingJoinPoint joinPoint) throws Throwable {
    final String value = (String) joinPoint.getArgs()[0];

    if (isDisabled() || value == null || value.isEmpty()) {
        return joinPoint.proceed();
    }

    final String overrideValue = getCustomMapping().get(value);

    if (overrideValue != null) {
        return joinPoint.proceed(new Object[] {overrideValue});
    }

    return joinPoint.proceed(new Object[] {WordUtils.capitalizeFully(value)});
}
 
Example #19
Source File: OauthAuthorizeAspect.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(..))")
public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    Map<String, String> parameters = (Map<String, String>) args[1];
    Principal principal = (Principal) args[3];
    if (principal instanceof TenantUsernamePasswordAuthenticationToken) {
        TenantUsernamePasswordAuthenticationToken tenantToken = (TenantUsernamePasswordAuthenticationToken)principal;
        String clientId = tenantToken.getClientId();
        String requestClientId = parameters.get(OAuth2Utils.CLIENT_ID);
        //判断是否不同租户单点登录
        if (!requestClientId.equals(clientId)) {
            try {
                TenantContextHolder.setTenant(requestClientId);
                //重新查询对应该租户的角色等信息
                LoginAppUser user = userService.findByUsername(tenantToken.getName());
                tenantToken = new TenantUsernamePasswordAuthenticationToken(user, tenantToken.getCredentials(), user.getAuthorities(), requestClientId);
                args[3] = tenantToken;
            } finally {
                TenantContextHolder.clear();
            }
        }
    }
    return joinPoint.proceed(args);
}
 
Example #20
Source File: BrowsersDataProviderAspect.java    From bdt with Apache License 2.0 6 votes vote down vote up
/**
 * If a System property with FORCE_BROWSER exists then Methods in
 * BrowsersDataProvider will return its value.
 *
 * @param pjp ProceedingJoinPoint
 * @return Object
 * @throws Throwable exception
 */
@Around(value = "availableBrowsersCallPointcut(context, testConstructor)")
public Object availableBrowsersCalls(ProceedingJoinPoint pjp, ITestContext context, Constructor<?> testConstructor)
        throws Throwable {

    if (pjp.getArgs().length > 0) {
        if (pjp.getArgs()[0] instanceof ITestContext) {
            if (Arrays.asList(((ITestContext) pjp.getArgs()[0]).getIncludedGroups()).contains("mobile")) {
                return pjp.proceed();
            }
        }
    }

    if (!"".equals(System.getProperty("FORCE_BROWSER", ""))) {
        List<String[]> lData = Lists.newArrayList();
        lData.add(new String[]{System.getProperty("FORCE_BROWSER")});
        logger.debug("Forcing browser to {}",
                System.getProperty("FORCE_BROWSER"));
        return lData.iterator();
    }
    return pjp.proceed();
}
 
Example #21
Source File: OptimisticConcurrencyControlAspect.java    From db-util with Apache License 2.0 5 votes vote down vote up
private Object proceed(ProceedingJoinPoint pjp, Retry retryAnnotation) throws Throwable {
    int times = retryAnnotation.times();
    Class<? extends Throwable>[] retryOn = retryAnnotation.on();
    Assert.isTrue(times > 0, "@Retry{times} should be greater than 0!");
    Assert.isTrue(retryOn.length > 0, "@Retry{on} should have at least one Throwable!");
    if (retryAnnotation.failInTransaction() && TransactionSynchronizationManager.isActualTransactionActive()) {
        throw new IllegalTransactionStateException(
                "You shouldn't retry an operation from within an existing Transaction." +
                        "This is because we can't retry if the current Transaction was already rolled back!");
    }
    LOGGER.info("Proceed with {} retries on {}", times, Arrays.toString(retryOn));
    return tryProceeding(pjp, times, retryOn);
}
 
Example #22
Source File: AopUtil.java    From phone with Apache License 2.0 5 votes vote down vote up
/**
 * 执行切入点方法
 * @param jp
 * @param params 方法参数
 * @return
 */
public static Object executeJoinPointMethod(ProceedingJoinPoint jp,Object[] params){
	Object obj = null;
	try {
		if (params==null||params.length==0) {
			obj = jp.proceed();
		}else{
			obj = jp.proceed(params);
		}
	} catch (Throwable e) {
		e.printStackTrace();
	}
	return obj;
}
 
Example #23
Source File: SwitchDataSource.java    From kratos-1 with Apache License 2.0 5 votes vote down vote up
/**
 * 拦截后需要执行的操作
 * 
 * @author gaoxianglong
 * 
 * @param proceedingJoinPoint
 *            委托对象的上下文信息
 * 
 * @param operation
 *            true为master启始索引,false为slave启始索引
 * 
 * @exception Throwable
 * 
 * @return Object
 */
public Object execute(ProceedingJoinPoint proceedingJoinPoint, boolean operation) {
	long befor = System.currentTimeMillis();
	Object result = null;
	/* 获取委托对象指定方法参数 */
	Object[] params = proceedingJoinPoint.getArgs();
	Object param = params[0];
	if (param.getClass() == String.class) {
		final String SQL = (String) param;
		logger.info("之前的数据库sql-->" + SQL);
		/* 检测是否需要执行分库分表操作 */
		if (kJdbcTemplate.getIsShard()) {
			/* 检测分表模式 */
			if (kJdbcTemplate.getShardMode()) {
				/* 一库一片模式 */
				logger.debug("当前采用的分片模式为一库一片");
				params = oneTbshard(SQL, params, operation).toArray();
			} else {
				/* 库内分片模式 */
				logger.debug("当前采用的分片模式为库内分片");
				params = manyTbshard(SQL, params, operation).toArray();
			}
			String NEW_SQL = params[0].toString();
			logger.info("sharding之后准备执行的数据库sql-->" + NEW_SQL);
		} else {
			/* 获取主/从的起始索引 */
			int index = WeightResolver.getIndex(kJdbcTemplate.getWr_weight(), operation);
			/* 切换数据源到master上 */
			setRoutingIndex(index);
		}
		try {
			/* 执行委托对象的目标方法 */
			result = proceedingJoinPoint.proceed(params);
			logger.debug("执行耗时->" + (System.currentTimeMillis() - befor) + "ms");
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}
	return result;
}
 
Example #24
Source File: CommonAspect.java    From seppb with MIT License 5 votes vote down vote up
public Object printExecuteIntervalLog(ProceedingJoinPoint point) throws Throwable {
    String executeMethod = String.format(POIN_CLASS_METHOD, point.getSignature().getDeclaringTypeName(), point.getSignature().getName());
    Stopwatch started = Stopwatch.createStarted();
    Object obj = point.proceed();
    if (isBlank(ParameterThreadLocal.getHttpId())) {
        return obj;
    }
    aspectLog.info(HTTP_REQUEST_LOG_MESSAGE, ParameterThreadLocal.getHttpId(), executeMethod,
            started.stop().elapsed(TimeUnit.MILLISECONDS));
    return obj;
}
 
Example #25
Source File: ActionAroundAophandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
public void handleAop(JoinPoint joinPoint) throws Throwable {
	ProceedingJoinPoint proceedingJoinPoint = (ProceedingJoinPoint) joinPoint;
	DTSContext context = (DTSContext) proceedingJoinPoint.getArgs()[0];
	String clazzName = proceedingJoinPoint.getTarget().getClass().getName();
	MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
	Method method = signature.getMethod();
	String twoPurchaseAction = method.getName();

	ActivityActionRuleEntity bizActionRule = context.getActivityRuleEntity().getActivityActionRuleEntity(clazzName);

	String service = bizActionRule.getService();

	ActionEntity actionEntity = new ActionEntity(ActivityIdGenerator.generateActionId(twoPurchaseAction), context,
			service, clazzName, twoPurchaseAction);
	try {
		ResultBase<String> resultBase = dtsManager.getAndCreateAction(actionEntity);
		actionEntity.setActionId(resultBase.getValue());

		proceedingJoinPoint.proceed();

		this.actionSuccess(actionEntity);
	} catch (Throwable t) {
		log.error("activityId.actionId:{},errorMessage:{}",
				actionEntity.getActivityId().concat(".").concat(actionEntity.getActionId()), t.getMessage(), t);
		this.actionFail(actionEntity, t.getMessage());
		throw t;
	}
}
 
Example #26
Source File: ActivityInjection.java    From FragmentRigger with MIT License 5 votes vote down vote up
@Around("onSaveInstanceState()")
public Object onSaveInstanceStateProcess(ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = joinPoint.proceed();
    Object puppet = joinPoint.getTarget();
    //Only inject the class that marked by Puppet annotation.
    Object[] args = joinPoint.getArgs();

    Method onSaveInstanceState = getRiggerMethod("onSaveInstanceState", Object.class, Bundle.class);
    onSaveInstanceState.invoke(getRiggerInstance(), puppet, args[0]);
    return result;
}
 
Example #27
Source File: LoggingAspect.java    From JSF-on-Spring-Boot with GNU General Public License v3.0 5 votes vote down vote up
@Around("execution(public java.lang.String *.getCounter(..))")
public Object logBefore(ProceedingJoinPoint joinPoint) throws Throwable {
	String msg = "(null) -> ";
	Object target = joinPoint.getTarget();
	try {
		Field counterField = target.getClass().getDeclaredField("counter");
		int counter = (int) counterField.get(target);
		msg = String.valueOf(counter) + " -> ";
	} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	String s = (String)joinPoint.proceed();
	return msg + s;
}
 
Example #28
Source File: SdsPointAspect.java    From sds with Apache License 2.0 5 votes vote down vote up
/**
 * 处理自定义的异常
 * 这里提供了两种写法,详细见 {@link com.didiglobal.sds.example.chapter3.OrderManageService}
 * 降级方法要求:
 * 1. 降级方法和注解标注的方法要在同一个类上
 * 2. 方法名称必须是 {@link SdsDowngradeMethod} 中的 fallback() 指定的
 * 3. 降级方法的入参类型必须和限流方法的保持一致或者可以多添加一个参数(类型必须为 {@link SdsException},且必须放在最后一个位置)
 *
 * @param pjp {@link ProceedingJoinPoint}
 * @param ex  {@link SdsException}
 * @return 降级方法的返回结果
 */
private Object handleFallback(ProceedingJoinPoint pjp, SdsException ex) {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Class<?> targetClass = pjp.getTarget().getClass();
    Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
    Object[] args = pjp.getArgs();
    Method originMethod = this.getDeclaredMethod(targetClass, signature.getName(), parameterTypes);
    // 上面已经判断过,不会发生 NPE
    SdsDowngradeMethod sdsDowngradeMethodAnnotation = originMethod.getAnnotation(SdsDowngradeMethod.class);
    // 获取降级方法名称
    String fallbackMethodName = sdsDowngradeMethodAnnotation.fallback();
    // 优先查找带异常的方法
    Method fallbackMethod = null;
    Class<?>[] newParameterTypes = Arrays.copyOf(parameterTypes, parameterTypes.length + 1);
    newParameterTypes[newParameterTypes.length - 1] = ex.getClass();
    Object[] newArgs = Arrays.copyOf(args, args.length + 1);
    newArgs[newArgs.length - 1] = ex;
    fallbackMethod = this.getDeclaredMethod(targetClass, fallbackMethodName, newParameterTypes);
    if (fallbackMethod == null) {
        // 如果没有查找到,则查找不带异常的方法,注意这里要把参数变回来,即去掉 SdsException
        newArgs = args;
        fallbackMethod = this.getDeclaredMethod(targetClass, fallbackMethodName, parameterTypes);
    }
    if (fallbackMethod == null) {
        logger.warn("找不到 {} 对应的降级方法,请检查您的注解配置", fallbackMethodName);
        return null;
    }
    try {
        return fallbackMethod.invoke(pjp.getThis(), newArgs);
    } catch (Exception e) {
        logger.error("fallbackMethod 处理失败", e);
    }
    return null;
}
 
Example #29
Source File: BaseAbstractXRayInterceptor.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
protected Object processXRayTrace(ProceedingJoinPoint pjp) throws Throwable {
    try {
        Subsegment subsegment = AWSXRay.beginSubsegment(pjp.getSignature().getName());
        if (subsegment != null) {
            subsegment.setMetadata(generateMetadata(pjp, subsegment));
        }
        return XRayInterceptorUtils.conditionalProceed(pjp);
    } catch (Exception e) {
        AWSXRay.getCurrentSegmentOptional().ifPresent(x -> x.addException(e));
        throw e;
    } finally {
        logger.trace("Ending Subsegment");
        AWSXRay.endSubsegment();
    }
}
 
Example #30
Source File: ResourceCrnPermissionChecker.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public <T extends Annotation> void checkPermissions(T rawMethodAnnotation, String userCrn, ProceedingJoinPoint proceedingJoinPoint,
        MethodSignature methodSignature, long startTime) {
    CheckPermissionByResourceCrn methodAnnotation = (CheckPermissionByResourceCrn) rawMethodAnnotation;
    String resourceCrn = commonPermissionCheckingUtils.getParameter(proceedingJoinPoint, methodSignature, ResourceCrn.class, String.class);
    AuthorizationResourceAction action = methodAnnotation.action();
    commonPermissionCheckingUtils.checkPermissionForUserOnResource(action, userCrn, resourceCrn);
}