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 Project: openregistry   Author: Jasig   File: FirstNameAspect.java    License: 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 #2
Source Project: mumu   Author: babymm   File: SysLogRecoderAspect.java    License: 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 #3
Source Project: jhipster-microservices-example   Author: oktadeveloper   File: LoggingAspect.java    License: 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 #4
Source Project: GyJdbc   Author: hope-for   File: BindPointAspect.java    License: 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 #5
Source Project: jhipster-registry   Author: jhipster   File: LoggingAspect.java    License: 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 #6
Source Project: layui-admin   Author: gameloft9   File: CheckUtil.java    License: 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 #7
Source Project: Sentinel-Dashboard-Nacos   Author: eacdy   File: AbstractSentinelAspectSupport.java    License: 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 #8
Source Project: youkefu   Author: zhangyanbo2007   File: SyncDatabaseExt.java    License: 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 #9
Source Project: microservices-platform   Author: zlt2000   File: OauthAuthorizeAspect.java    License: 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 #10
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractAspectJAdvice.java    License: 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 #11
Source Project: cas4.0.x-server-wechat   Author: luotuo   File: LogAspect.java    License: 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 #12
Source Project: java-microservice   Author: apssouza22   File: CallMonitoringAspect.java    License: 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 #13
Source Project: bdt   Author: Stratio   File: BrowsersDataProviderAspect.java    License: 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 #14
Source Project: sanshanblog   Author: SanShanYouJiu   File: ControllerAop.java    License: 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 #15
Source Project: freehealth-connector   Author: taktik   File: KmehrHelper.java    License: 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 #16
@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 #17
@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 #18
Source Project: flender   Author: jd-alexander   File: FlenderAspect.java    License: 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 #19
Source Project: HIS   Author: ZainZhao   File: BindingResultAspect.java    License: 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 #20
Source Project: Full-Stack-Development-with-JHipster   Author: PacktPublishing   File: LoggingAspect.java    License: 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 #21
Source Project: localization_nifi   Author: wangrenlei   File: NiFiServiceFacadeLock.java    License: Apache License 2.0 5 votes vote down vote up
@Around("within(org.apache.nifi.web.NiFiServiceFacade+) && "
        + "execution(* update*(..))")
public Object updateLock(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    writeLock.lock();
    try {
        return proceedingJoinPoint.proceed();
    } finally {
        writeLock.unlock();
    }
}
 
Example #22
Source Project: nifi   Author: apache   File: ComponentStateAuditor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Audits clearing of state from a Controller Service.
 *
 * @param proceedingJoinPoint join point
 * @param controllerService the controller service
 * @throws java.lang.Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.ComponentStateDAO+) && "
    + "execution(void clearState(org.apache.nifi.controller.service.ControllerServiceNode)) && "
    + "args(controllerService)")
public StateMap clearControllerServiceStateAdvice(ProceedingJoinPoint proceedingJoinPoint, ControllerServiceNode controllerService) throws Throwable {

    // update the controller service state
    final StateMap stateMap = (StateMap) proceedingJoinPoint.proceed();

    // if no exception were thrown, add the clear action...

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

    // ensure the user was found
    if (user != null) {
        Collection<Action> actions = new ArrayList<>();

        // create the controller service details
        FlowChangeExtensionDetails controllerServiceDetails = new FlowChangeExtensionDetails();
        controllerServiceDetails.setType(controllerService.getComponentType());

        // create the clear action
        FlowChangeAction configAction = new FlowChangeAction();
        configAction.setUserIdentity(user.getIdentity());
        configAction.setOperation(Operation.ClearState);
        configAction.setTimestamp(new Date());
        configAction.setSourceId(controllerService.getIdentifier());
        configAction.setSourceName(controllerService.getName());
        configAction.setSourceType(Component.ControllerService);
        configAction.setComponentDetails(controllerServiceDetails);
        actions.add(configAction);

        // record the action
        saveActions(actions, logger);
    }

    return stateMap;
}
 
Example #23
Source Project: DBus   Author: BriData   File: PermissionAspect.java    License: Apache License 2.0 5 votes vote down vote up
private Integer getProjectId(ProceedingJoinPoint pJointPoint) throws Exception {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    //如果在param中有projectId字段,取该字段
    String projectStr = request.getParameter("projectId");
    if (StringUtils.isNotEmpty(projectStr)) {
        return Integer.valueOf(projectStr);
    } else {
        /*param中没有的话,就从路径中取,会有以下三种情况
        1. /delete/{projectId} 只有一个参数,这个参数就是projectId
        2./update/{projectId}/{tableId}   多个int参数,第一个int值
        3./update/{name}/{projectId}  多个非int参数,第一个int值

        总结:
        对于情况1,直接获取这个路径参数即可,此时唯一的路径参数对应唯一的函数参数,直接取函数参数即可。
        对于情况2、3,取路径参数中第一个int值为projectId
        */
        Object[] args = pJointPoint.getArgs();
        if (args.length < 1) {
            throw new Exception("projectId not found");
        } else if (args.length == 1) {
            return Integer.valueOf(args[0].toString());
        } else {
            String uri = request.getRequestURI();
            String[] pathVariables = uri.split("/");
            Integer proId = null;
            for (String pathVar : pathVariables) {
                try {
                    proId = Integer.valueOf(pathVar);
                    break;
                } catch (Exception e) {
                    continue;
                }
            }
            return proId;
        }
    }

}
 
Example #24
Source Project: AspectJDemo   Author: David-Kuper   File: TraceAspect.java    License: Apache License 2.0 5 votes vote down vote up
/**
     *  截获原方法,并替换
     * @param joinPoint
     * @return
     * @throws Throwable
     */
  @Around("methodAnnotated()")
  public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {

    if (currentObject == null){
        currentObject = joinPoint.getTarget();
    }
      //初始化计时器
    final StopWatch stopWatch = new StopWatch();
      //开始监听
      stopWatch.start();
      //调用原方法的执行。
    Object result = joinPoint.proceed();
      //监听结束
    stopWatch.stop();
      //获取方法信息对象
      MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
      String className;
      //获取当前对象,通过反射获取类别详细信息
      className = joinPoint.getThis().getClass().getName();

      String methodName = methodSignature.getName();
      String msg =  buildLogMessage(methodName, stopWatch.getTotalTime(1));
    if (currentObject != null && currentObject.equals(joinPoint.getTarget())){
        DebugLog.log(new MethodMsg(className,msg,stopWatch.getTotalTime(1)));
    }else if(currentObject != null && !currentObject.equals(joinPoint.getTarget())){
        DebugLog.log(new MethodMsg(className, msg,stopWatch.getTotalTime(1)));
        Log.e(className,msg);
        currentObject = joinPoint.getTarget();
//        DebugLog.outPut(new Path());    //日志存储
//        DebugLog.ReadIn(new Path());    //日志读取
    }
    return result;
  }
 
Example #25
Source Project: cuba   Author: cuba-platform   File: AuthenticationInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private Object aroundInvoke(ProceedingJoinPoint ctx) throws Throwable {
    if (log.isTraceEnabled())
        log.trace("Authenticating: ", ctx.getSignature());

    try {
        authentication.begin();
        Object res = ctx.proceed();
        return res;
    } finally {
        authentication.end();
    }
}
 
Example #26
Source Project: tcc-transaction   Author: Duttor   File: TXAspectProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Around("pointcutTXConfirm()")
public Object doTXConfirm(ProceedingJoinPoint pjp) throws Throwable {

    TXContext ctx= TXContextHolder.getTXContext();
    if(ctx ==null && pjp.getArgs().length> 0){
        //规定第一个参数为TXContext里面传递txId等信息
        Object firstValue= pjp.getArgs()[0];
        if(firstValue instanceof TXContext){
            ctx= (TXContext) firstValue;
        }
    }
    if(ctx== null){
        if(logger.isInfoEnabled()){
            logger.info("TXContext is empty ,confirm="+pjp.getSignature());
        }
        return pjp.proceed();
    }
    //验证事务是否为空
    assertTransactional();

    Object result= pjp.proceed();
    //更改TX表的状态为CONFIRMED
    serviceIntercepter.confirmService(ctx);

    if (logger.isInfoEnabled()) {
        Method method= ((MethodSignature) pjp.getSignature()).getMethod();
        method= pjp.getTarget().getClass().getDeclaredMethod(method.getName(),method.getParameterTypes());
        logger.info("Child transaction 'confirm' succeed and save 'cancelled' status to db, TXContext:" + ctx+", confirmMethod: "
                + method.getDeclaringClass().getName()+"."+method.getName());
    }
    return result;
}
 
Example #27
Source Project: eladmin   Author: elunez   File: LimitAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    HttpServletRequest request = RequestHolder.getHttpServletRequest();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method signatureMethod = signature.getMethod();
    Limit limit = signatureMethod.getAnnotation(Limit.class);
    LimitType limitType = limit.limitType();
    String key = limit.key();
    if (StringUtils.isEmpty(key)) {
        if (limitType == LimitType.IP) {
            key = StringUtils.getIp(request);
        } else {
            key = signatureMethod.getName();
        }
    }

    ImmutableList<Object> keys = ImmutableList.of(StringUtils.join(limit.prefix(), "_", key, "_", request.getRequestURI().replaceAll("/","_")));

    String luaScript = buildLuaScript();
    RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class);
    Number count = redisTemplate.execute(redisScript, keys, limit.count(), limit.period());
    if (null != count && count.intValue() <= limit.count()) {
        logger.info("第{}次访问key为 {},描述为 [{}] 的接口", count, keys, limit.name());
        return joinPoint.proceed();
    } else {
        throw new BadRequestException("访问次数受限制");
    }
}
 
Example #28
Source Project: nifi   Author: apache   File: ProcessGroupAuditor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Audits the update of process group variable registry.
 *
 * @param proceedingJoinPoint join point
 * @param variableRegistry variable registry
 * @throws Throwable ex
 */
@Around("within(org.apache.nifi.web.dao.ProcessGroupDAO+) && "
    + "execution(org.apache.nifi.groups.ProcessGroup updateVariableRegistry(org.apache.nifi.web.api.dto.VariableRegistryDTO)) && "
    + "args(variableRegistry)")
public ProcessGroup updateVariableRegistryAdvice(final ProceedingJoinPoint proceedingJoinPoint, final VariableRegistryDTO variableRegistry) throws Throwable {
    final ProcessGroup updatedProcessGroup = (ProcessGroup) proceedingJoinPoint.proceed();

    saveUpdateAction(variableRegistry.getProcessGroupId(), Operation.Configure);

    return updatedProcessGroup;
}
 
Example #29
Source Project: agile-service-old   Author: choerodon   File: DataLogAspect.java    License: Apache License 2.0 5 votes vote down vote up
private Object createLabelDataLog(Long issueId, Long projectId, ProceedingJoinPoint pjp) {
    List<IssueLabelDTO> originLabels = issueMapper.selectLabelNameByIssueId(issueId);
    Object result = null;
    try {
        result = pjp.proceed();
        List<IssueLabelDTO> curLabels = issueMapper.selectLabelNameByIssueId(issueId);
        createDataLog(projectId, issueId, FIELD_LABELS, getOriginLabelNames(originLabels),
                getOriginLabelNames(curLabels), null, null);
    } catch (Throwable e) {
        throw new CommonException(ERROR_METHOD_EXECUTE, e);
    }
    return result;
}
 
Example #30
Source Project: pybbs   Author: tomoya92   File: CommentLayerPlugin.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Around("co.yiiu.pybbs.hook.CommentServiceHook.selectByTopicId()")
public Object selectByTopicId(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    List<CommentsByTopic> newComments =
            (List<CommentsByTopic>) proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
    if (systemConfigService.selectAllConfig().get("comment_layer").equals("1")) {
        // 盖楼显示评论
        return this.sortByLayer(newComments);
    }
    return newComments;
}