Java Code Examples for org.aspectj.lang.reflect.MethodSignature#getParameterNames()

The following examples show how to use org.aspectj.lang.reflect.MethodSignature#getParameterNames() . 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: AopUtils.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
/**
 * 获取参数名和值
 *
 * @param joinPoint
 * @return
 */
public static Map getFieldsName(ProceedingJoinPoint joinPoint) throws ClassNotFoundException, NoSuchMethodException {
    // 参数值
    Object[] args = joinPoint.getArgs();

    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    String[] parameterNames = methodSignature.getParameterNames();

    // 通过map封装参数和参数值
    HashMap<String, Object> paramMap = new HashMap();
    for (int i = 0; i < parameterNames.length; i++) {
        paramMap.put(parameterNames[i], args[i]);
    }
    return paramMap;
}
 
Example 2
Source File: GenericControllerAspect.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void logPreExecutionData(ProceedingJoinPoint proceedingJoinPoint, RequestMapping methodRequestMapping) {
    MethodSignature methodSignature = (MethodSignature)proceedingJoinPoint.getSignature();
    String calssName = proceedingJoinPoint.getTarget().getClass().getSimpleName();
    String methodName = calssName + "." + methodSignature.getName() + "()";
    Object argValues[] = proceedingJoinPoint.getArgs();
    String argNames[] = methodSignature.getParameterNames();
    String requestContext = requestUtil.getRequestContext().toString();
    Annotation annotations[][] = methodSignature.getMethod().getParameterAnnotations();
    StringBuilder preMessage = new StringBuilder().append(methodName);
    if (argValues != null && argValues.length > 0 && argNames != null && argNames.length > 0) {
        logFunctionArguments(argNames, argValues, preMessage, annotations, methodRequestMapping);
    }
    preMessage.append(" called via ").append(requestContext);
    LOG.info(preMessage.toString());
}
 
Example 3
Source File: GenericControllerAspect.java    From controller-logger with Apache License 2.0 6 votes vote down vote up
public void logPreExecutionData(
        @Nonnull ProceedingJoinPoint proceedingJoinPoint,
        @Nullable RequestMapping methodRequestMapping) {
    MethodSignature methodSignature = (MethodSignature)proceedingJoinPoint.getSignature();

    String methodName = methodSignature.getName() + "()";
    Object argValues[] = proceedingJoinPoint.getArgs();
    String argNames[] = methodSignature.getParameterNames();
    String requestContext = requestUtil.getRequestContext().toString();
    Annotation annotations[][] = methodSignature.getMethod().getParameterAnnotations();

    StringBuilder preMessage = new StringBuilder().append(methodName);

    if (argValues.length > 0) {
        logFunctionArguments(argNames, argValues, preMessage, annotations, methodRequestMapping);
    }

    preMessage.append(" called via ").append(requestContext);
    LOG.info(preMessage.toString());
}
 
Example 4
Source File: AspectUtils.java    From allure-java with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated use {@link AspectUtils#getParametersMap(JoinPoint)} instead.
 */
@Deprecated
public static Map<String, Object> getParametersMap(final MethodSignature signature, final Object... args) {
    final String[] parameterNames = signature.getParameterNames();
    final Map<String, Object> params = new HashMap<>();
    params.put("method", signature.getName());
    for (int i = 0; i < Math.max(parameterNames.length, args.length); i++) {
        params.put(parameterNames[i], args[i]);
        params.put(Integer.toString(i), args[i]);
    }
    return params;
}
 
Example 5
Source File: SPELUtil.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 5 votes vote down vote up
/**
 *  得到参数名称和值 放到 spel 上下文
 * @param pjp
 */
private void extractArgments(ProceedingJoinPoint pjp) {
    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();

    String[] names   = methodSignature.getParameterNames();
    Object[] args = pjp.getArgs();

    for (int i = 0; i < names.length; i++) {
        this.context.setVariable(names[i], args[i]);
    }
}
 
Example 6
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 7
Source File: AopUtils.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> getArgsMap(JoinPoint pjp) {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Map<String, Object> args = new LinkedHashMap<>();
    String names[] = signature.getParameterNames();
    for (int i = 0, len = names.length; i < len; i++) {
        args.put(names[i], pjp.getArgs()[i]);
    }
    return args;
}
 
Example 8
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if(MDC.get(APIConstants.CORRELATION_ID) == null) {
        if (messageContext != null) {
            Map headers =
                    (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null) {
                String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
                if (correlationId != null) {
                    MDC.put(APIConstants.CORRELATION_ID, correlationId);
                }
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 9
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if (messageContext != null) {
        Map headers = (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null) {
            String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
            if (correlationId != null) {
                MDC.put(APIConstants.CORRELATION_ID, correlationId);
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 10
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if (messageContext != null) {
        Map headers = (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null) {
            String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
            if (correlationId != null) {
                MDC.put(APIConstants.CORRELATION_ID, correlationId);
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 11
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if (messageContext != null) {
        Map headers = (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null) {
            String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
            if (correlationId != null) {
                MDC.put(APIConstants.CORRELATION_ID, correlationId);
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 12
Source File: ControllerInputValidatorAspect.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Around for pointcut defined by controllerMethodInvocation
 * @param joinPoint
 * @return
 * @throws Throwable
 */
@Around("controllerMethodInvocation()")
public Object aroundController(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
    String[] paramNames = methodSignature.getParameterNames();
    Object[] args = joinPoint.getArgs();

    for (int i = 0; i < args.length; i++) {
        if (checkAnnotations(annotations[i])) {
            validateArg(args[i], paramNames[i]);
        }
    }
    return joinPoint.proceed(args);
}
 
Example 13
Source File: TenantAwareCallAspect.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private String extractTenant(JoinPoint jp) {
    MethodSignature ms = (MethodSignature) jp.getSignature();

    String[] params = ms.getParameterNames();

    TenantCall tenantParam = ms.getMethod().getAnnotation(TenantCall.class);

    for (int i = 0; i < params.length; i++) {
        if (tenantParam.param().equals(params[i])) {
            return (String) jp.getArgs()[i];
        }
    }

    throw new IllegalStateException("Expected method parameter [" + tenantParam.param() + "] was not found");
}
 
Example 14
Source File: CometAspect.java    From Milkomeda with MIT License 4 votes vote down vote up
@SuppressWarnings("rawtypes")
private Object applyAround(CometData cometData, ThreadLocal<CometData> threadLocal, ProceedingJoinPoint joinPoint,
                           HttpServletRequest request, Date requestTime, String name, String tag,
                           Function<Object, Object> mapReturnData) throws Throwable {
    cometData.setRequest(request);
    cometData.setRequestTime(requestTime);
    cometData.setName(name);
    cometData.setTag(tag);
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    cometData.setClazzName(signature.getDeclaringTypeName());
    cometData.setExecMethod(signature.getName());
    Map<String, Object> params = new HashMap<>();
    // 获取参数名
    String[] parameterNames = signature.getParameterNames();
    Object[] args = joinPoint.getArgs();
    if (args !=  null && args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            String argName = parameterNames[i];
            Object argValue = args[i];
            if (hasFilter(argValue)) {
                continue;
            }
            params.put(argName, argValue);
        }
        cometData.setRequestData(JSONUtil.serialize(params));
    }
    try {
        String host = NetworkUtil.getHost();
        cometData.setHost(host);
    } catch (UnknownHostException ignored) {
    }
    if (milkomedaProperties.isShowLog()) {
        log.info("Comet:- before: {}", JSONUtil.serialize(cometData));
    }
    // 外部可以扩展记录自定义数据
    recorder.onRequest(cometData, cometData.getTag(), request, args);
    threadLocal.set(cometData);

    // 执行方法体
    Object returnData = joinPoint.proceed();

    long duration = new Date().getTime() - cometData.getRequestTime().getTime();
    cometData.setDuration(String.valueOf(duration));
    cometData.setStatus(cometProperties.getStatusSuccessCode());
    cometData.setResponseTime(new Date());
    if (returnData != null) {
        // returnData应用map转换类型
        if (mapReturnData != null) {
            returnData = mapReturnData.apply(returnData);
        }

        // 记录返回数据
        if (returnData instanceof ResponseEntity) {
            Object body = ((ResponseEntity) returnData).getBody();
            cometData.setResponseData(body instanceof String ? (String) body : JSONUtil.serialize(body));
        } else {
            cometData.setResponseData(returnData instanceof String ? (String) returnData : JSONUtil.serialize(returnData));
        }
    } else {
        // 读取Response
        if (CometHolder.getCollectorProps() != null && CometHolder.getCollectorProps().isEnable()) {
            CometResponseWrapper responseWrapper =
                    WebUtils.getNativeResponse(WebContext.getResponse(), CometResponseWrapper.class);
            if (responseWrapper != null) {
                cometData.setStatus(WebContext.getResponse().getStatus() == HttpStatus.OK.value() ? cometProperties.getStatusSuccessCode() : cometProperties.getStatusFailCode());
                String content = new String(responseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
                cometData.setResponseData(content);
            }
        }
    }

    // 开始回调
    Object returnObj = recorder.onReturn(cometData, returnData);
    // 修正返回值
    returnObj = returnObj == null ? returnData : returnObj;
    if (milkomedaProperties.isShowLog()) {
        log.info("Comet:- afterReturn: {}", JSONUtil.serialize(cometData));
    }
    threadLocal.remove();
    return returnObj;
}
 
Example 15
Source File: JoinPointParesUtils.java    From code with Apache License 2.0 4 votes vote down vote up
/**
 * 获取方法参数
 */
public static String getMethodInfo(JoinPoint point) {
    // 获取方法签名
    MethodSignature methodSignature = (MethodSignature) point.getSignature();

    //全限定名
    String className = methodSignature.getDeclaringType().getName();
    //方法名
    String methodName = methodSignature.getName();
    //参数名数组
    String[] parameterNames = methodSignature.getParameterNames();

    // 获取方法
    Method method = methodSignature.getMethod();
    // 获取方法上面的注解
    LogOperation logOperation = method.getAnnotation(LogOperation.class);
    String operate = "";
    if (logOperation != null) {
        operate = logOperation.value();
    }
    StringBuilder sb = null;
    if (Objects.nonNull(parameterNames)) {
        sb = new StringBuilder();
        for (int i = 0; i < parameterNames.length; i++) {
            Object arg = point.getArgs()[i];//参数值
            if (arg instanceof BindingResult) {
                continue;
            }
            // 复杂对象
            if (arg != null && !isPrimitive(arg)) {
                sb.append(parameterNames[i]).append(":").append(JSONObject.toJSON(arg)).append("; ");
            } else {
                // null值或者基础数据类型
                String parameterValue = arg != null ? arg.toString() : "null";
                sb.append(parameterNames[i]).append(":").append(parameterValue).append("; ");
            }
        }
    }
    sb = sb == null ? new StringBuilder() : sb;
    return String.format("操作名称:[%s] | 全限定名:[%s] | 方法名:[%s] | 参数列表:[%s]", operate, className, methodName, sb.toString());
}
 
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);
        }
    }
}