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

The following examples show how to use org.aspectj.lang.JoinPoint#getSignature() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: 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 2
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. 登录校验
	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 3
Source File: LogAspect.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 是否存在注解,如果存在就获取
 */
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
{
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    if (method != null)
    {
        return method.getAnnotation(Log.class);
    }
    return null;
}
 
Example 4
Source File: ControllerLogContextAspects.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before("com.sequenceiq.cloudbreak.logger.ControllerLogContextAspects.interceptControllerMethodCalls()")
public void buildLogContextForControllerCalls(JoinPoint joinPoint) {
    try {
        Object[] args = joinPoint.getArgs();
        CodeSignature sig = (CodeSignature) joinPoint.getSignature();
        String[] paramNames = sig.getParameterNames();
        logContextService.buildMDCParams(joinPoint.getTarget(), paramNames, args);
        MDCBuilder.addRequestId(MDCBuilder.getMdcContextMap().get(LoggerContextKey.REQUEST_ID.toString()));
        LOGGER.debug("A controller method has been intercepted: {} with params {}, {}, MDC logger context is built.", joinPoint.toShortString(),
                sig.getParameterNames(), AnonymizerUtil.anonymize(Arrays.toString(args)));
    } catch (Exception any) {
        LOGGER.warn("MDCContext build failed: ", any);
    }
}
 
Example 5
Source File: LogAspect.java    From ruoyiplus with MIT License 5 votes vote down vote up
/**
 * 是否存在注解,如果存在就获取
 */
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
{
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    if (method != null)
    {
        return method.getAnnotation(Log.class);
    }
    return null;
}
 
Example 6
Source File: AnnotationAop.java    From SpringBoot2.0 with Apache License 2.0 5 votes vote down vote up
@Before("@annotation(com.jiuxian.annotation.Log)")
public void before(JoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    Log log = method.getAnnotation(Log.class);
    System.out.println("注解式拦截 " + log.value());
}
 
Example 7
Source File: Allure1TestCaseAspects.java    From allure-java with Apache License 2.0 5 votes vote down vote up
private void updateTestCase(final JoinPoint joinPoint) {
    final MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    final Object[] args = joinPoint.getArgs();
    final Allure1Annotations annotations = new Allure1Annotations(signature, args);
    getLifecycle().getCurrentTestCase().ifPresent(uuid -> {
        getLifecycle().updateTestCase(uuid, annotations::updateTitle);
        getLifecycle().updateTestCase(uuid, annotations::updateDescription);
        getLifecycle().updateTestCase(uuid, annotations::updateParameters);
        getLifecycle().updateTestCase(uuid, annotations::updateLabels);
        getLifecycle().updateTestCase(uuid, annotations::updateLinks);
    });
}
 
Example 8
Source File: LogAspect.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 是否存在注解,如果存在就获取
 */
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
{
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    if (method != null)
    {
        return method.getAnnotation(Log.class);
    }
    return null;
}
 
Example 9
Source File: ProfilingAspect.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected static StringBuilder getMessage(JoinPoint joinPoint) {
    final StringBuilder messageSB = new StringBuilder();
    if (joinPoint.getTarget() != null) {
        messageSB.append(joinPoint.getTarget().getClass().getSimpleName());
    } else {
        messageSB.append(joinPoint.getSignature().getDeclaringType().getSimpleName());
    }
    if (joinPoint.getSignature() != null) {
        messageSB.append('.');
        String name = joinPoint.getSignature().getName();
        if (joinPoint.getSignature() instanceof MethodSignature) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method targetMethod = methodSignature.getMethod();
            Measured measured = targetMethod.getAnnotation(Measured.class);
            if (measured != null && measured.value() != null && measured.value().trim().length() > 0) {
                name = measured.value();
            } else {
                Counted counted = targetMethod.getAnnotation(Counted.class);
                if (counted != null && counted.value() != null && counted.value().trim().length() > 0) {
                    name = counted.value();
                }
            }
        }
        messageSB.append(name);
    }
    return messageSB;
}
 
Example 10
Source File: AopUtils.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public static String getMethodBody(JoinPoint pjp) {
    StringBuilder methodName = new StringBuilder(pjp.getSignature().getName()).append("(");
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    String[] names = signature.getParameterNames();
    Class[] args = signature.getParameterTypes();
    for (int i = 0, len = args.length; i < len; i++) {
        if (i != 0) {
            methodName.append(",");
        }
        methodName.append(args[i].getSimpleName()).append(" ").append(names[i]);
    }
    return methodName.append(")").toString();
}
 
Example 11
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];
    }
}
 
Example 12
Source File: SmartOperateLogAspect.java    From smart-admin with MIT License 5 votes vote down vote up
private OperateLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    OperateLog classAnnotation = AnnotationUtils.findAnnotation(method.getDeclaringClass(), OperateLog.class);

    if (method != null) {
        return classAnnotation;
    }
    return null;
}
 
Example 13
Source File: ControllerLogContextAspects.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before("com.sequenceiq.datalake.logger.ControllerLogContextAspects.interceptControllerMethodCalls()")
public void buildLogContextForControllerCalls(JoinPoint joinPoint) {
    try {
        Object[] args = joinPoint.getArgs();
        CodeSignature sig = (CodeSignature) joinPoint.getSignature();
        String[] paramNames = sig.getParameterNames();
        logContextService.buildMDCParams(joinPoint.getTarget(), paramNames, args);
        MDCBuilder.addRequestId(MDCBuilder.getMdcContextMap().get(LoggerContextKey.REQUEST_ID.toString()));
        LOGGER.debug("A controller method has been intercepted: {} with params {}, {}, MDC logger context is built.", joinPoint.toShortString(),
                sig.getParameterNames(), AnonymizerUtil.anonymize(Arrays.toString(args)));
    } catch (Exception any) {
        LOGGER.warn("MDCContext build failed: ", any);
    }
}
 
Example 14
Source File: DataScopeAspect.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 是否存在注解,如果存在就获取
 */
private DataScope getAnnotationLog(JoinPoint joinPoint)
{
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    if (method != null)
    {
        return method.getAnnotation(DataScope.class);
    }
    return null;
}
 
Example 15
Source File: TestAnnotationAspect.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
@Before("myAnnotationPointCut()")
public void before(JoinPoint joinPoint) throws Throwable {
    MethodSignature sign = (MethodSignature) joinPoint.getSignature();
    Method method = sign.getMethod();
    MyTestAnnotation annotation = method.getAnnotation(MyTestAnnotation.class);
    //获取注解参数
    System.out.print("打印TestAnnotation 参数:" + annotation.value());

}
 
Example 16
Source File: NamespaceSecurityAdvice.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Check permission on the service methods before the execution. The method is expected to throw AccessDeniedException if current user does not have the
 * permissions.
 * 
 * @param joinPoint The join point
 */
@Before("serviceMethods()")
public void checkPermission(JoinPoint joinPoint)
{

    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = methodSignature.getMethod();

    List<NamespacePermission> namespacePermissions = new ArrayList<>();
    if (method.isAnnotationPresent(NamespacePermissions.class))
    {
        namespacePermissions.addAll(Arrays.asList(method.getAnnotation(NamespacePermissions.class).value()));
    }
    else if (method.isAnnotationPresent(NamespacePermission.class))
    {
        namespacePermissions.add(method.getAnnotation(NamespacePermission.class));
    }

    if (!namespacePermissions.isEmpty())
    {
        String[] parameterNames = methodSignature.getParameterNames();
        Object[] args = joinPoint.getArgs();

        Map<String, Object> variables = new HashMap<>();
        for (int i = 0; i < parameterNames.length; i++)
        {
            variables.put(parameterNames[i], args[i]);
        }

        List<AccessDeniedException> accessDeniedExceptions = new ArrayList<>();
        for (NamespacePermission namespacePermission : namespacePermissions)
        {
            for (String field : namespacePermission.fields())
            {
                try
                {
                    namespaceSecurityHelper.checkPermission(spelExpressionHelper.evaluate(field, Object.class, variables), namespacePermission
                        .permissions());
                }
                catch (AccessDeniedException accessDeniedException)
                {
                    accessDeniedExceptions.add(accessDeniedException);
                }
            }
        }
        if (!accessDeniedExceptions.isEmpty())
        {
            throw namespaceSecurityHelper.getAccessDeniedException(accessDeniedExceptions);
        }
    }
}
 
Example 17
Source File: SystemLogAspect.java    From cms with Apache License 2.0 4 votes vote down vote up
/***
     * 拦截控制层的操作日志
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Before(value = "logPointcut()")
    public void beforeLog(JoinPoint joinPoint) throws Throwable {
        SystemLog systemLog = new SystemLog();
        currentSystemLogThreadLocal.set(systemLog);
        currentTime.set(Instant.now().toEpochMilli());
//        Object result = joinPoint.proceed();
        HttpServletRequest request = RequestHolder.getHttpServletRequest();

        systemLog.setUsername(SecurityUtils.getUsername());
        systemLog.setUrl(request.getRequestURI());
        systemLog.setStartTime(LocalDateTime.now());
        systemLog.setRequestIp(RequestHolder.getIp());
        systemLog.setBrowser(RequestHolder.getBrowser());


        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log log = method.getAnnotation(Log.class);

        // 类名
        systemLog.setName(log.value());
        systemLog.setDescription(log.descrption());
        systemLog.setMethod(joinPoint.getTarget().getClass() + "." + signature.getName() + "()");

        systemLog.setFinishTime(LocalDateTime.now());

        //访问目标方法的参数 可动态改变参数值
        Object[] args = joinPoint.getArgs();
        // 参数
        systemLog.setParams(Arrays.toString(args));

        if ("login".equals(log.value())) {
            try {
                LoginRequest loginRequest = (LoginRequest) args[0];
                systemLog.setUsername(loginRequest.getUsername());
                systemLog.setParams("");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
 
Example 18
Source File: OperationLogAspect.java    From nimrod with MIT License 4 votes vote down vote up
@Before(value = "operationLogAspect()")
public void before(JoinPoint joinpoint) throws JsonProcessingException {
    long beginTime = Instant.now().toEpochMilli();
    HttpServletRequest httpServletRequest = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    HttpServletResponse httpServletResponse = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    SimpleUser simpleUser = SimpleUserDetailsServiceImpl.getCurrentSimpleUser();
    if (simpleUser != null) {
        operationLogEntity.setUserId(simpleUser.getId());
    }
    operationLogEntity.setIpAddress(ClientUtil.getClientIp(httpServletRequest));
    String operation = "";
    MethodSignature methodSignature = (MethodSignature) joinpoint.getSignature();
    Method method = methodSignature.getMethod();
    OperationLog operationLog = method.getAnnotation(OperationLog.class);
    if (operationLog != null) {
        operationLogEntity.setOperationType(operationLog.type().value());
        operation = operationLog.value();
        if ("".equals(operation)) {
            operation = operationLog.operation();
        }
    }
    operationLogEntity.setOperation(operation);
    operationLogEntity.setHandler(joinpoint.getSignature().toLongString());
    StringBuffer requestUrl = httpServletRequest.getRequestURL();
    if (requestUrl != null) {
        operationLogEntity.setRequestUrl(requestUrl.toString());
    }
    operationLogEntity.setRequestMethod(httpServletRequest.getMethod());
    Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
    Map<String, Object> map = new HashMap<>(6);
    while (parameterNames.hasMoreElements()) {
        String name = parameterNames.nextElement();
        Object parameter = httpServletRequest.getParameter(name);
        map.put(name, parameter);
    }
    operationLogEntity.setRequestParameter(common.objectToJson(map));
    operationLogEntity.setAcceptLanguage(httpServletRequest.getHeader("Accept-Language"));
    operationLogEntity.setReferer(httpServletRequest.getHeader("Referer"));
    operationLogEntity.setUserAgent(httpServletRequest.getHeader("User-Agent"));
    HttpSession httpSession = httpServletRequest.getSession();
    if (httpSession != null) {
        operationLogEntity.setSessionId(httpSession.getId());
    }
    Cookie[] cookies = httpServletRequest.getCookies();
    map = new HashMap<>(4);
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            map.put(cookie.getName(), cookie.getValue());
        }
    }
    operationLogEntity.setCookie(common.objectToJson(map));
    operationLogEntity.setStatus(String.valueOf(httpServletResponse.getStatus()));
    operationLogEntity.setGmtCreated(new Date());
    operationLogEntity.setConsumingTime(Instant.now().toEpochMilli() - beginTime);
}
 
Example 19
Source File: FlenderAspect.java    From flender with Apache License 2.0 4 votes vote down vote up
static String getInternetAnnotationParameter(JoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    String value = signature.getMethod().getAnnotation(InternetRequired.class).value().toLowerCase();
    return value;
}
 
Example 20
Source File: OperateLogController.java    From Jpom with MIT License 4 votes vote down vote up
@Override
public void before(JoinPoint joinPoint) {
    Signature signature = joinPoint.getSignature();
    if (signature instanceof MethodSignature) {
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        UserOperateLogV1.OptType optType = null;
        OptLog optLog = method.getAnnotation(OptLog.class);
        if (optLog != null) {
            optType = optLog.value();
        }
        if (optType != null) {
            CacheInfo cacheInfo = new CacheInfo();
            cacheInfo.optType = optType;

            ServletRequestAttributes servletRequestAttributes = BaseServerController.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if (optType == UserOperateLogV1.OptType.Login) {
                // 获取登录人的信息
                String userName = request.getParameter("userName");
                UserService userService = SpringUtil.getBean(UserService.class);
                cacheInfo.userModel = userService.getItem(userName);
            }
            // 获取ip地址
            cacheInfo.ip = ServletUtil.getClientIP(request);
            // 获取节点
            cacheInfo.nodeModel = (NodeModel) request.getAttribute("node");
            //
            cacheInfo.dataId = request.getParameter("id");
            //
            cacheInfo.userAgent = ServletUtil.getHeaderIgnoreCase(request, HttpHeaders.USER_AGENT);
            //
            Map<String, String[]> map = ObjectUtil.clone(request.getParameterMap());
            // 过滤密码字段
            Set<Map.Entry<String, String[]>> entries = map.entrySet();
            for (Map.Entry<String, String[]> entry : entries) {
                String key = entry.getKey();
                if (StrUtil.containsAnyIgnoreCase(key, "pwd", "password")) {
                    entry.setValue(new String[]{"***"});
                }
            }
            cacheInfo.setReqData(JSONObject.toJSONString(map));
            CACHE_INFO_THREAD_LOCAL.set(cacheInfo);
        }
    }
}