Example usage for org.aspectj.lang.reflect MethodSignature getMethod

List of usage examples for org.aspectj.lang.reflect MethodSignature getMethod

Introduction

In this page you can find the example usage for org.aspectj.lang.reflect MethodSignature getMethod.

Prototype

Method getMethod();

Source Link

Usage

From source file:com.liferay.util.aspectj.AspectJUtil.java

License:Open Source License

public static Method getMethod(MethodSignature methodSignature) throws NoSuchMethodException {

    Method method = null;//  www. j  a v a 2 s.  c om

    if (ServerDetector.isWebSphere()) {
        Class<?> declaringType = methodSignature.getDeclaringType();
        String name = methodSignature.getName();
        Class<?>[] parameterTypes = methodSignature.getParameterTypes();

        method = declaringType.getMethod(name, parameterTypes);
    } else {
        method = methodSignature.getMethod();
    }

    return method;
}

From source file:com.migo.aop.SysLogAspect.java

License:Apache License

@Before("logPointCut()")
public void saveSysLog(JoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();

    SysLogEntity sysLog = new SysLogEntity();
    SysLog syslog = method.getAnnotation(SysLog.class);
    if (syslog != null) {
        //??//from  w  ww . ja v a2s  . c om
        sysLog.setOperation(syslog.value());
    }

    //??
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = signature.getName();
    sysLog.setMethod(className + "." + methodName + "()");

    //?
    Object[] args = joinPoint.getArgs();
    String params = JSON.toJSONString(args[0]);
    sysLog.setParams(params);

    //?request
    HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
    //IP?
    sysLog.setIp(IPUtils.getIpAddr(request));

    //??
    String username = ShiroUtils.getUserEntity().getUsername();
    sysLog.setUsername(username);

    sysLog.setCreateDate(new Date());
    //?
    sysLogService.save(sysLog);
}

From source file:com.mycom.products.mywebsite.backend.aspect.LoggingAspect.java

License:Open Source License

@Before(value = "classAnnotatedWithLoggable(loggable) && publicMethod() && !initBinderMethod()")
public void beforeMethod(JoinPoint joinPoint, Loggable loggable) throws Throwable {
    // get RequestMapping annotation of target class
    Object[] arguments = joinPoint.getArgs();
    applicationLogger.info(LOG_BREAKER_OPEN);
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    // get RequestMapping annotation of target class
    RequestMapping rootMapper = joinPoint.getTarget().getClass().getAnnotation(RequestMapping.class);
    RequestMapping methodMapper = method.getAnnotation(RequestMapping.class);
    // skip for non-servlet request methods.
    if (rootMapper == null || methodMapper == null) {
        return;/*  ww  w  . j  av a2s  .c o m*/
    }
    // get class level request mapping URL
    String rootMappingURL = rootMapper.value()[0];
    // get Class Name
    String className = joinPoint.getTarget().getClass().getSimpleName();

    String mappingURL = rootMappingURL;
    if (methodMapper.value().length > 0) {
        mappingURL += methodMapper.value()[0];
    }
    // set the request method
    String requestMethod = "";
    if (methodMapper.method().length == 0) {
        requestMethod = RequestMethod.GET.name();
    } else {
        requestMethod = methodMapper.method()[0].name();
    }
    // create for method String
    String methodName = joinPoint.getSignature().getName();
    StringBuffer sbMethod = new StringBuffer();
    sbMethod.append(" '" + methodName + "'");
    sbMethod.append(" Method [");
    sbMethod.append("mappingURL ('" + mappingURL + "') ,");
    sbMethod.append("requestMethod ('" + requestMethod + "') ");
    sbMethod.append("] ");
    applicationLogger.info(LOG_PREFIX + "Client request for" + sbMethod.toString() + " of '" + className
            + "' class." + LOG_SUFFIX);
    if (applicationLogger.isDebugEnabled()) {
        applicationLogger.debug("==================== Request parameters ===========================");
        if (arguments.length > 0) {
            for (Object arg : arguments) {
                if (arg != null) {
                    applicationLogger.debug(LOG_PREFIX + arg.toString() + LOG_SUFFIX);
                }
            }
        } else {
            applicationLogger.debug(LOG_PREFIX + "[EMPTY Request parameters]" + LOG_SUFFIX);
        }
        applicationLogger.debug("===================================================================");
    }
}

From source file:com.mycom.products.mywebsite.backend.aspect.LoggingAspect.java

License:Open Source License

@AfterReturning(value = "classAnnotatedWithLoggable(loggable) && publicMethod() && !initBinderMethod()", returning = "serverResponse")
public void afterReturnMethod(JoinPoint joinPoint, Loggable loggable, Object serverResponse) throws Throwable {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    // get RequestMapping annotation of target class
    RequestMapping rootMapper = joinPoint.getTarget().getClass().getAnnotation(RequestMapping.class);
    RequestMapping methodMapper = method.getAnnotation(RequestMapping.class);
    // skip for non-servlet request methods.
    if (rootMapper == null || methodMapper == null) {
        return;/*from ww  w  . j a  va  2s.  c om*/
    }
    // get class level request mapping URL
    String rootMappingURL = rootMapper.value()[0];
    // get Class Name
    String className = joinPoint.getTarget().getClass().getSimpleName();

    String mappingURL = rootMappingURL;
    if (methodMapper.value().length > 0) {
        mappingURL += methodMapper.value()[0];
    }
    // set the request method
    String requestMethod = "";
    if (methodMapper.method().length == 0) {
        requestMethod = RequestMethod.GET.name();
    } else {
        requestMethod = methodMapper.method()[0].name();
    }
    // create for method String
    String methodName = joinPoint.getSignature().getName();
    StringBuffer sbMethod = new StringBuffer();
    sbMethod.append(" '" + methodName + "'");
    sbMethod.append(" Method [");
    sbMethod.append("mappingURL ('" + mappingURL + "') ,");
    sbMethod.append("requestMethod ('" + requestMethod + "') ");
    sbMethod.append("] ");
    ResponseBody responeBodyAnnotation = method.getAnnotation(ResponseBody.class);
    if (responeBodyAnnotation != null || mappingURL.contains("api/")) {
        applicationLogger.info(LOG_PREFIX + "Ajax Request : ==> " + sbMethod.toString() + " of '" + className
                + "' class has been done." + LOG_SUFFIX);
        if (applicationLogger.isDebugEnabled()) {
            applicationLogger.debug("==================== Ajax Response from server ====================");
            applicationLogger.debug(serverResponse);
            applicationLogger.debug("===================================================================");
        }
    } else {
        applicationLogger.info(LOG_PREFIX + "Servlet Request : ==> " + sbMethod.toString() + " of '" + className
                + "' class has been successfully initiated from server and navigate to new Tiles view ["
                + serverResponse + "]" + LOG_SUFFIX);
    }
    applicationLogger.info(LOG_BREAKER_CLOSE);
}

From source file:com.mycom.products.mywebsite.backend.aspect.ServletExceptionHandlerAspect.java

License:Open Source License

@Around(value = "methodAnnotatedWithHandleServletException(servletException) && publicMethod() && !initBinderMethod()")
public String handleExeptionforServletMethods(ProceedingJoinPoint joinPoint,
        HandleServletException servletException) throws Throwable {
    String pageSuccessReturn = null;
    String errorView = servletException.errorView();
    PageMode pageMode = servletException.pageMode();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    ValidateEntity validationMapper = method.getAnnotation(ValidateEntity.class);
    Model model = null;// w  w  w  . j  a v a 2s.c om
    Errors errors = null;
    Object validationTarget = null;
    Object[] arguments = joinPoint.getArgs();
    for (Object arg : arguments) {
        if (arg != null) {
            if (arg instanceof BindingAwareModelMap) {
                model = (Model) arg;
            }
            if (validationMapper != null && arg instanceof BeanPropertyBindingResult) {
                errors = (Errors) arg;
            }
            if (validationMapper != null && arg instanceof BaseBean) {
                validationTarget = arg;
            }
        }
    }
    try {
        if (validationMapper != null) {
            BaseValidator validator = appContext.getBean(validationMapper.validator());
            validator.setPageMode(pageMode);
            validator.validate(validationTarget, errors);
            if (errors.hasErrors()) {
                throw new ValidationFailedException(BaseBean.LOG_PREFIX + "Validation failed for '"
                        + validationTarget.getClass().getSimpleName() + "'." + BaseBean.LOG_SUFFIX);
            }
        }
        pageSuccessReturn = (String) joinPoint.proceed();
    } catch (Exception e) {
        errorLogger.error(BaseBean.LOG_BREAKER_OPEN);
        errorLogger.error(e.getMessage(), e);
        if (errorLogger.isDebugEnabled()) {
            if (e instanceof ValidationFailedException) {
                Map<String, String> validationErrors = new HashMap<>();
                List<FieldError> errorFields = errors.getFieldErrors();
                errorFields.forEach(item -> {
                    if (!validationErrors.containsKey(item.getField())) {
                        validationErrors.put(item.getField(), item.getDefaultMessage());
                    }
                });
                validationErrors.entrySet().forEach(entry -> {
                    errorLogger.debug(entry.getKey() + " ==> " + entry.getValue());
                });
            }
        }
        errorLogger.error(BaseBean.LOG_BREAKER_CLOSE);
        if (model != null) {
            model.addAttribute("pageMode", pageMode);
        }
        if (e instanceof ValidationFailedException) {
            if (errorView.length() == 0) {
                errorView = "error/500";
            } else {
                if (model != null && errors != null) {
                    model.addAttribute("pageMode", pageMode);
                    Map<String, String> validationErrors = new HashMap<>();
                    List<FieldError> errorFields = errors.getFieldErrors();
                    errorFields.forEach(item -> {
                        if (!validationErrors.containsKey(item.getField())) {
                            validationErrors.put(item.getField(), item.getDefaultMessage());
                        }
                    });
                    model.addAttribute("validationErrors", validationErrors);
                    model.addAttribute("pageMessage",
                            new PageMessage("Validation Error",
                                    messageSource.getMessage("Validation.common.Page.ValidationErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        } else if (e instanceof DuplicatedEntryException) {
            if (errorView.length() == 0) {
                errorView = "error/208";
            } else {
                if (model != null) {
                    model.addAttribute("pageMessage",
                            new PageMessage("Duplicated",
                                    messageSource
                                            .getMessage("Serverity.common.Page.DuplicatedRecordErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        } else if (e instanceof ConsistencyViolationException) {
            if (errorView.length() == 0) {
                errorView = "error/226";
            } else {
                if (model != null) {
                    model.addAttribute("pageMessage",
                            new PageMessage("Rejected",
                                    messageSource.getMessage(
                                            "Serverity.common.Page.ConsistencyViolationErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        } else if (e instanceof BusinessException) {
            if (errorView.length() == 0) {
                errorView = "error/500";
            } else {
                if (model != null) {
                    model.addAttribute("pageMessage",
                            new PageMessage("Application Error",
                                    messageSource.getMessage("Serverity.common.Page.ApplicationErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        } else {
            if (errorView.length() == 0) {
                errorView = "error/500";
            } else {
                if (model != null) {
                    model.addAttribute("pageMessage",
                            new PageMessage("Server Error",
                                    messageSource.getMessage("Serverity.common.Page.ServerErrorMessage"),
                                    PageMessageStyle.ERROR.getValue()));
                }
            }
        }
    }
    if (errorView.length() == 0) {
        errorView = "error/500";
    }
    return pageSuccessReturn == null ? errorView : pageSuccessReturn;

}

From source file:com.nestedbird.util.JoinPointToStringHelper.java

License:Open Source License

/**
 * To string string.//  ww w . j  a  v a  2s  .  com
 *
 * @param jp the jp
 * @return the string
 */
public static String toString(JoinPoint jp) {
    StringBuilder sb = new StringBuilder();
    appendType(sb, getType(jp));
    Signature signature = jp.getSignature();
    if (signature instanceof MethodSignature) {
        MethodSignature ms = (MethodSignature) signature;
        sb.append("#");
        sb.append(ms.getMethod().getName());
        sb.append("(");
        appendTypes(sb, ms.getMethod().getParameterTypes());
        sb.append(")");
    }
    return sb.toString();
}

From source file:com.netflix.hystrix.contrib.javanica.utils.ajc.AjcUtils.java

License:Apache License

public static Method getAjcMethodAroundAdvice(Class<?> target, MethodSignature signature) {
    return getAjcMethodAroundAdvice(target, signature.getMethod().getName(), signature.getParameterTypes());
}

From source file:com.netflix.hystrix.contrib.javanica.utils.AopUtils.java

License:Apache License

/**
 * Gets parameter types of the join point.
 *
 * @param joinPoint the join point//from  www  . j  a v a  2  s  .co m
 * @return the parameter types for the method this object
 *         represents
 */
public static Class[] getParameterTypes(JoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    return method.getParameterTypes();
}

From source file:com.netsteadfast.greenstep.aspect.HessianServiceProxyAspect.java

License:Apache License

private Object proxyProcess(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Annotation[] annotations = pjp.getTarget().getClass().getAnnotations();
    String serviceId = AspectConstants.getServiceId(annotations);

    /**/*from   w w w  .  j a v a  2 s . c  o  m*/
     * ???? service-bean
     */
    if (!GreenStepHessianUtils.isProxyServiceId(serviceId)) {
        //logger.info( "reject proxy service: " + serviceId );
        return pjp.proceed();
    }

    String userId = StringUtils.defaultString((String) SecurityUtils.getSubject().getPrincipal());

    if (GreenStepHessianUtils.getConfigHessianHeaderCheckValueModeEnable()) {
        /**
         * ???? service-bean
         */
        if (StringUtils.isBlank(userId)) {
            logger.warn("no userId");
            pjp.proceed();
        }

        /**
         * ???? service-bean
         */
        if (GreenStepHessianUtils.isProxyBlockedAccountId(userId)) {
            logger.warn("reject proxy service: " + serviceId + " , blocked userId: " + userId);
            return pjp.proceed();
        }
    }

    String serviceInterfacesName = "";
    Class<?> serviceInterfaces[] = pjp.getTarget().getClass().getInterfaces();
    for (Class<?> clazz : serviceInterfaces) {
        if (clazz.getName().indexOf(".service.") > -1) {
            serviceInterfacesName = clazz.getName();
        }
    }
    if (StringUtils.isBlank(serviceInterfacesName)) {
        logger.error("error no service interface: " + serviceId);
        throw new Exception("error no service interface: " + serviceId);
    }

    String url = GreenStepHessianUtils.getServiceUrl(serviceId);
    String theSystemPath = ApplicationSiteUtils.getHost(Constants.getSystem()) + "/"
            + ApplicationSiteUtils.getContextPath(Constants.getSystem());

    /**
     * ?????, ? HessianServiceProxyAspect ? (server-remote???)
     *  http://127.0.0.1:8080/
     *  hessian.enable=Y ???, ?url hessian.serverUrl=http://127.0.0.1:8080/
     * 
     */
    if (url.indexOf(theSystemPath) > -1) {
        logger.error("cannot open same-server. now system contextPath = " + theSystemPath
                + " , but proxy url = " + url);
        throw new Exception("cannot open same-server. now system contextPath = " + theSystemPath
                + " , but proxy url = " + url);
    }

    logger.info("proxy url = " + url);
    HessianProxyFactory factory = null;
    Object proxyServiceObject = null;
    if (GreenStepHessianUtils.getConfigHessianHeaderCheckValueModeEnable()) { // ?checkValue?
        factory = new GreenStepHessianProxyFactory();
        ((GreenStepHessianProxyFactory) factory)
                .setHeaderCheckValue(GreenStepHessianUtils.getEncAuthValue(userId));
        proxyServiceObject = ((GreenStepHessianProxyFactory) factory)
                .createForHeaderMode(Class.forName(serviceInterfacesName), url);
    } else { // ?checkValue?
        factory = new HessianProxyFactory();
        proxyServiceObject = factory.create(Class.forName(serviceInterfacesName), url);
    }
    Method[] proxyObjectMethods = proxyServiceObject.getClass().getMethods();
    Method proxyObjectMethod = null;
    if (null == proxyObjectMethods) {
        logger.error("error no find proxy method: " + serviceId);
        throw new Exception("error no find proxy method: " + serviceId);
    }
    for (Method m : proxyObjectMethods) {
        if (m.getName().equals(signature.getMethod().getName())
                && Arrays.equals(m.getParameterTypes(), signature.getMethod().getParameterTypes())) {
            proxyObjectMethod = m;
        }
    }

    if (null == proxyObjectMethod) {
        logger.error("error no execute proxy method: " + serviceId);
        throw new Exception("error no execute proxy method: " + serviceId);
    }

    Object resultObj = null;
    try {
        resultObj = proxyObjectMethod.invoke(proxyServiceObject, pjp.getArgs());
        this.setReCalculateSizePageOfForPageFindGridResult(resultObj, pjp.getArgs());
    } catch (InvocationTargetException e) {
        if (e.getMessage() != null) {
            throw new ServiceException(e.getMessage().toString());
        }
        if (e.getTargetException().getMessage() != null) {
            throw new ServiceException(e.getTargetException().getMessage().toString());
        }
        throw e;
    } catch (Exception e) {
        logger.error(e.getMessage().toString());
        throw e;
    }
    logger.info("proxy success: " + serviceId + " method: " + proxyObjectMethod.getName());
    return resultObj;
}

From source file:com.netsteadfast.greenstep.aspect.ServiceAuthorityCheckAspect.java

License:Apache License

@Around(AspectConstants.LOGIC_SERVICE_PACKAGE)
public Object logicServiceProcess(ProceedingJoinPoint pjp)
        throws AuthorityException, ServiceException, Throwable {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Annotation[] annotations = pjp.getTarget().getClass().getAnnotations();
    String serviceId = AspectConstants.getServiceId(annotations);
    Subject subject = SecurityUtils.getSubject();
    Method method = signature.getMethod();
    if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) {
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
                this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }/*w  ww.j  a v  a 2s.  com*/
    if (StringUtils.isBlank(serviceId)) { //  service id  
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
                this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    if (!this.isServiceAuthorityCheck(annotations)) { //  ServiceAuthority  check=false ? 
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
                this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    Annotation[] methodAnnotations = method.getAnnotations();
    if (this.isServiceMethodAuthority(serviceId, methodAnnotations, subject)) {
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
                this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    logger.warn("[decline] user[" + subject.getPrincipal() + "] " + pjp.getTarget().getClass().getName() + " - "
            + signature.getMethod().getName());
    SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
            this.getEventId(serviceId, method.getName()), false);
    throw new AuthorityException(SysMessageUtil.get(GreenStepSysMsgConstants.NO_PERMISSION));
}