Java Code Examples for org.aspectj.lang.annotation.Before

The following examples show how to use org.aspectj.lang.annotation.Before. These examples are extracted from open source projects. 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: sophia_scaffolding   Source File: ApiLogAspect.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <方法执行前>
 *
 * @param point  [参数说明]
 * @param sysLog sysLog
 * @return void [返回类型说明]
 * @see [类、类#方法、类#成员]
 */
@Before(value = "log()")
public void before(JoinPoint point) throws Throwable {
    ApiLogger apiLogger = new ApiLogger();
    //将当前实体保存到threadLocal
    log.info("日志开始记录");
    logThreadLocal.set(apiLogger);
    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();
    String operation = request.getMethod();
    apiLogger.setId(UuidUtil.getUuid());
    apiLogger.setCreateTime(LocalDateTime.now());
    if (!request.getRequestURI().contains(GlobalsConstants.LOGIN)) {
        apiLogger.setUserName(getUsername());
        apiLogger.setParams(Arrays.toString(point.getArgs()));
    }
    apiLogger.setMethodName(getMethodDescription(point) + ":" + point.getSignature().getName());
    apiLogger.setClassName(point.getTarget().getClass().getName());
    apiLogger.setMethod(operation);
    apiLogger.setUri(URLUtil.getPath(request.getRequestURI()));
    apiLogger.setIp(getIpAddr(request));
    apiLogger.setServiceId(getClientId());
    log.info("结束日志记录");
}
 
Example 2
Source Project: scaffold-cloud   Source File: PreInsertAspect.java    License: MIT License 6 votes vote down vote up
@Before("   execution(* com.cms.scaffold.micro.*.dao.*.insert*(..)) " +
        "|| execution( * com.cms.scaffold.common.base.BaseMapper.insert*(..))")
public void insert(JoinPoint joinPoint){

    BaseEntity baseEntity = null;
    try {
        //获取目标方法的参数信息
        Object[] obj = joinPoint.getArgs();
        if(obj!=null && obj.length > 0 && obj[0] instanceof BaseEntity){
            baseEntity = (BaseEntity)obj[0];
            if (baseEntity.getAddTime() == null){
                baseEntity.preInsert();
            }
        }
    }catch (Exception ex){
        logger.info(ex.getMessage(),ex);
    }

}
 
Example 3
Source Project: yue-library   Source File: HttpAspect.java    License: Apache License 2.0 6 votes vote down vote up
@Before("pointcut()")
public void doVerifyBefore(JoinPoint joinPoint) {
	// 1. 登录校验
	MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
	String uri = request.getRequestURI();
       Long user_id = null;
	if (!uri.startsWith("/open") && !uri.equals("/")) {
		user_id = user.getUserId();
	}
	
	// 2. 开发环境-打印日志
	String ip = request.getRemoteHost();
       log.info("ip={}", ip);
	log.info("uri={}", uri);
	log.info("user_id={}", user_id);
	log.info("method={}", request.getMethod());
	log.info("class_method={}", methodSignature.getDeclaringTypeName() + "." + methodSignature.getName() + "()");
}
 
Example 4
Source Project: runscore   Source File: ParamValidAspect.java    License: Apache License 2.0 6 votes vote down vote up
@Before("paramValidAspect()")
public void before(JoinPoint joinPoint) {
	// 获取入参
	Object[] args = joinPoint.getArgs();
	for (Object arg : args) {
		if (arg == null) {
			throw new ParamValidException(BizError.参数异常.getCode(), "入参为空");
		}
		Set<ConstraintViolation<Object>> violations = validator.validate(arg);
		Iterator<ConstraintViolation<Object>> iterator = violations.iterator();
		// 参数校验不通过,直接抛出异常
		if (iterator.hasNext()) {
			ConstraintViolation<Object> violation = iterator.next();
			throw new ParamValidException(BizError.参数异常.getCode(),
					violation.getPropertyPath() + ":" + violation.getMessage());
		}
	}

}
 
Example 5
Source Project: xechat   Source File: ChatRecordAspect.java    License: MIT License 6 votes vote down vote up
@Before("chatRecordPointcut()")
public void doBefore(JoinPoint joinPoint) {
    log.debug("before -> {}", joinPoint);

    MessageVO messageVO = null;
    Object[] args = joinPoint.getArgs();
    for (Object obj : args) {
        if (obj instanceof MessageVO) {
            messageVO = (MessageVO) obj;
            break;
        }
    }

    Assert.notNull(messageVO, "方法必需以MessageVO类或该类的子类作为参数");

    if (messageVO.getType() == MessageTypeEnum.USER) {
        // 对于User类型的消息做敏感词处理
        messageVO.setMessage(SensitiveWordUtils.loveChina(messageVO.getMessage()));
    }

    log.debug("添加聊天记录 -> {}", messageVO);
    chatRecordService.addRecord(ChatRecordDTO.toChatRecordDTO(messageVO));
}
 
Example 6
Source Project: Spring-Boot-Book   Source File: LoggerAdvice.java    License: Apache License 2.0 5 votes vote down vote up
@Before("within(com.hua..*) && @annotation(loggerManage)")
//切入点
public void addBeforeLogger(JoinPoint joinPoint, LoggerManage loggerManage) {
	logger.info("执行 " + loggerManage.description() + " 开始");
	logger.info(joinPoint.getSignature().toString());
	logger.info(parseParames(joinPoint.getArgs()));
}
 
Example 7
@SuppressWarnings("unchecked")
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());

	counterAspect = (CounterAspect) ctx.getBean("counterAspect");
	counterAspect.reset();

	testBean = (GenericInterface<String>) ctx.getBean("testBean");
}
 
Example 8
Source Project: MyCommunity   Source File: ServiceLogAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
    // 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (attributes == null) {
        return;
    }
    HttpServletRequest request = attributes.getRequest();
    String ip = request.getRemoteHost();
    String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
}
 
Example 9
Source Project: SENS   Source File: SystemLogAspect.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 前置通知 (在方法执行之前返回)用于拦截Controller层记录用户的操作的开始时间
 *
 * @param joinPoint 切点
 * @throws InterruptedException
 */
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) throws InterruptedException {

    //线程绑定变量(该数据只有当前请求的线程可见)
    Date beginTime = new Date();
    beginTimeThreadLocal.set(beginTime);
}
 
Example 10
@Before(value="execution(void set*(*)) && this(mixin)", argNames="mixin")
public void checkNotLocked( Lockable mixin) {
	// Can also obtain the mixin (this) this way
	//Lockable mixin = (Lockable) jp.getThis();
	if (mixin.locked()) {
		throw new IllegalStateException();
	}
}
 
Example 11
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	counterAspect = (CounterAspect) ctx.getBean("counterAspect");
	testBean1 = (ITestBean) ctx.getBean("testBean1");
	testBean3 = (ITestBean) ctx.getBean("testBean3");
}
 
Example 12
@SuppressWarnings("unchecked")
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());

	counterAspect = (GenericCounterAspect) ctx.getBean("counterAspect");
	counterAspect.count = 0;

	testBean = (DerivedInterface<String>) ctx.getBean("testBean");
}
 
Example 13
@SuppressWarnings("unchecked")
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass());

	counterAspect = (CounterAspect) ctx.getBean("counterAspect");
	counterAspect.reset();

	testBean = (GenericInterface<String>) ctx.getBean("testBean");
}
 
Example 14
@Before(value="execution(void set*(*)) && this(modifiable) && args(newValue)", argNames="modifiable,newValue")
public void recordModificationIfSetterArgumentDiffersFromOldValue(
		JoinPoint jp, MutableModifiable mixin, Object newValue) {

	/*
	 * We use the mixin to check and, if necessary, change,
	 * modification status. We need the JoinPoint to get the
	 * setter method. We use newValue for comparison.
	 * We try to invoke the getter if possible.
	 */

	if (mixin.isModified()) {
		// Already changed, don't need to change again
		//System.out.println("changed");
		return;
	}

	// Find the current raw value, by invoking the corresponding setter
	Method correspondingGetter = getGetterFromSetter(((MethodSignature) jp.getSignature()).getMethod());
	boolean modified = true;
	if (correspondingGetter != null) {
		try {
			Object oldValue = correspondingGetter.invoke(jp.getTarget());
			//System.out.println("Old value=" + oldValue + "; new=" + newValue);
			modified = !ObjectUtils.nullSafeEquals(oldValue, newValue);
		}
		catch (Exception ex) {
			ex.printStackTrace();
			// Don't sweat on exceptions; assume value was modified
		}
	}
	else {
		//System.out.println("cannot get getter for " + jp);
	}
	if (modified) {
		mixin.markDirty();
	}
}
 
Example 15
@org.junit.Before
public void setup() {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());
	testBean = (TestInterface) ctx.getBean("testBean");
	testAnnotatedClassBean = (TestInterface) ctx.getBean("testAnnotatedClassBean");
	testAnnotatedMethodBean = (TestInterface) ctx.getBean("testAnnotatedMethodBean");
	counter = (Counter) ctx.getBean("counter");
	counter.reset();
}
 
Example 16
Source Project: kvf-admin   Source File: ActionAspect.java    License: MIT License 5 votes vote down vote up
@Before("logPointCut()")
public void before(JoinPoint joinPoint) {
	MethodSignature signature = (MethodSignature) joinPoint.getSignature();
	Method method = signature.getMethod();
	// 如果是退出登录请求。侧使用前置通知
	if ("logout".equals(method.getName())) {
		// 保存日志
		saveActionLog(joinPoint, 0, false);
	}
}
 
Example 17
@Before(value = "@annotation(annotation) && args(model, ..)")
   public void validate(Validate annotation, Object model) throws ValidatorException {
   	if(log.isDebugEnabled()) {
   		log.debug("formName:"+annotation.value()+", model:"+model.getClass().getName());
   	}

   	validateInternal(annotation, model);
}
 
Example 18
@Before(value = "@annotation(annotation) && args(model, username, companyId, ..)")
public void validate(Validate annotation, Object model, String username, int companyId) throws ValidatorException {
   	if(log.isDebugEnabled()) {
   		log.debug("formName:"+annotation.value()+", model:"+model.getClass().getName() + ", username: " + username);
   	}

   	validateInternal(annotation, model);
}
 
Example 19
@Before(value = "@annotation(annotation) && args(companyId, modelId)")
public void validate(Validate annotation, int companyId, int modelId) throws ValidatorException {
	if(log.isDebugEnabled()) {
		log.debug("formName: " + annotation.value() + ", companyId: " + companyId);
	}

	Validator validator = new Validator(resources, annotation.value());
	validator.setParameter(Validator.BEAN_PARAM, companyId);
	validator.setParameter(Validator.BEAN_PARAM, modelId);

	validateInternal(validator);
}
 
Example 20
@Before(value = "@annotation(annotation) && args(companyId, customerID, custParameters)", argNames = "annotation,companyId,customerID,custParameters")
public void validate(Validate annotation, int companyId, int customerID, Map<?, ?> custParameters) throws ValidatorException {
   	if(log.isDebugEnabled()) {
   		log.debug("formName:"+annotation.value());
   	}

       Validator validator = new Validator(resources, annotation.value());
       validator.setParameter(Validator.BEAN_PARAM, custParameters);
       validateInternal(validator);

}
 
Example 21
Source Project: spring-microservice-exam   Source File: ValidateTenantAspect.java    License: MIT License 5 votes vote down vote up
@Before("execution(* com.github.tangyi.auth.security.CustomUserDetailsServiceImpl.load*(..)) && args(tenantCode,..)")
public void validateTenantCode(String tenantCode) throws TenantNotFoundException {
	// 获取tenantCode
	if (StringUtils.isBlank(tenantCode))
		throw new TenantNotFoundException("tenantCode cant not be null");
	// 先获取租户信息
	ResponseBean<Tenant> tenantResponseBean = userServiceClient.findTenantByTenantCode(tenantCode);
	if (!ResponseUtil.isSuccess(tenantResponseBean))
		throw new ServiceException("get tenant info failed: " + tenantResponseBean.getMsg());
	Tenant tenant = tenantResponseBean.getData();
	if (tenant == null)
		throw new TenantNotFoundException("tenant does not exist");
}
 
Example 22
@Before(value="execution(void set*(*)) && this(mixin)", argNames="mixin")
public void checkNotLocked( Lockable mixin) {
	// Can also obtain the mixin (this) this way
	//Lockable mixin = (Lockable) jp.getThis();
	if (mixin.locked()) {
		throw new IllegalStateException();
	}
}
 
Example 23
Source Project: open-cloud   Source File: DynamicDataSourceAspect.java    License: MIT License 5 votes vote down vote up
/**
 * 选择数据源 DataSource
 *
 * @param point the point
 */
@Before("daoAspect()")
public void switchDataSource(JoinPoint point) {
    if (openSaasProperties.getTenantId() != null) {
        DynamicDataSourceContextHolder.setDataSourceKey(openSaasProperties.getTenantId());
        logger.info("==> Switch DataSource to [{}] in Method [{}] tenant is [{}]", DynamicDataSourceContextHolder.getDataSourceKey(), point.getSignature(),openSaasProperties.getTenantId());
    }else{
        DynamicDataSourceContextHolder.setDataSourceKey("master");
    }
}
 
Example 24
Source Project: code   Source File: AdviceAspectConfig.java    License: Apache License 2.0 5 votes vote down vote up
/******advice********/

    //@After("matchAnno()") //方法执行完成之后(不论是否有异常)
    //@After("matchException()") //方法执行完成之后(不论是否有异常)
    //@AfterThrowing("matchException()") //抛出异常之后执行
    //@AfterThrowing("matchAnno()") //不抛异常不执行
    //public void after(){
    //    System.out.println("###after");
    //}

    //@AfterReturning(value ="matchReturn()",returning = "result") // 获取方法的返回值
    //public void after(Object result){
    //    System.out.println("###after returning:"+result);
    //}

    //@Around("matchAnno()") //测试@Around正常情况
    //@Around("matchException()")// 测试@Around出现异常
    //public Object after(ProceedingJoinPoint pjp) {
    //    System.out.println("###before");
    //    Object result = null;
    //    try {
    //        result = pjp.proceed(pjp.getArgs());
    //        System.out.println("###after returning:" + result);
    //    } catch (Throwable e) {
    //        System.out.println("###catch ex");
    //        //throw
    //        e.printStackTrace();
    //    } finally {
    //        System.out.println("###finally");
    //    }
    //    return result;
    //}

    // 使用@Before校验参数
    @Before("matchLongArg() && args(productId)")
    public void before(Long productId){
        System.out.println("###before,get args:"+productId);
    }
 
Example 25
Source Project: supplierShop   Source File: DataScopeAspect.java    License: MIT License 4 votes vote down vote up
@Before("dataScopePointCut()")
public void doBefore(JoinPoint point) throws Throwable
{
    handleDataScope(point);
}
 
Example 26
Source Project: spring-cloud-huawei   Source File: ApiModelReaderAop.java    License: Apache License 2.0 4 votes vote down vote up
@Before(value = "execution(* springfox.documentation.spring.web.scanners.ApiListingScanner.scan(..)) && args(args)", argNames = "args")
public void beforeParseSchema(ApiListingScanningContext args) {
  args.getRequestMappingsByResourceGroup().keySet().forEach(k ->
      DefinitionCache.setSchemaClassName(k.getGroupName(), k.getControllerClass().get().getName()));

}
 
Example 27
Source Project: ZTuoExchange_framework   Source File: GeeTestAspect.java    License: MIT License 4 votes vote down vote up
@Before("geeTest()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    log.info("❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤");
    gee(joinPoint);
}
 
Example 28
@Before("GenericInterfaceGenericCollectionArgExecution()")
public void incrementGenericInterfaceGenericCollectionArgExecution() {
	genericInterfaceGenericCollectionArgExecutionCount++;
}
 
Example 29
@Before("execution(void *.set*(int))")
public void countSetter() {
	++count;
}
 
Example 30
@Before("execution(void *.set*(int))")
public void countSetter() {
	++count;
}