Example usage for org.aspectj.lang ProceedingJoinPoint getSignature

List of usage examples for org.aspectj.lang ProceedingJoinPoint getSignature

Introduction

In this page you can find the example usage for org.aspectj.lang ProceedingJoinPoint getSignature.

Prototype

Signature getSignature();

Source Link

Document

getStaticPart().getSignature() returns the same object

Usage

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  . ja  v a 2s . c o  m*/
    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.mycompany.aspect.InterceptorLog.java

@Around("execution(* execution(*com.mycompany.dao.SobaDaoImp.addStudentAround (..))")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("logAround() metoda je pozvana!");
    System.out.println("presretanje metode : " + joinPoint.getSignature().getName());
    System.out.println("presretanje : " + Arrays.toString(joinPoint.getArgs()));
    System.out.println("Around before metoda jepozvana");
    joinPoint.proceed();/*w  w w  .  j a va 2  s .c  o m*/
    System.out.println("Around metoda je pozvana!");
    System.out.println("******");
}

From source file:com.mycompany.floormaster.aop.TimerAspect.java

public Object timeMethod(ProceedingJoinPoint jp) {

    Object o = null;/*from  w  w  w . j a  v a2  s  .  c om*/

    long start = System.nanoTime();

    try {
        o = jp.proceed();
    } catch (Throwable ex) {
        Logger.getLogger(TimerAspect.class.getName()).log(Level.SEVERE, null, ex);
    }

    long end = System.nanoTime();

    System.out.println("\n" + jp.getSignature().getName() + " took " + (end - start) + " nanoseconds");

    return o;
}

From source file:com.netflix.bdp.s3mper.listing.ConsistentListingAspect.java

License:Apache License

/**
 * Updates the metastore when a FileSystem.create(...) method is called.
 * //  w  ww .j  ava  2 s.c  om
 * @param pjp
 * @return
 * @throws Throwable 
 */
@Around("create() && !within(ConsistentListingAspect)")
public Object metastoreUpdate(final ProceedingJoinPoint pjp) throws Throwable {
    if (disabled) {
        return pjp.proceed();
    }

    Configuration conf = ((FileSystem) pjp.getTarget()).getConf();
    updateConfig(conf);

    Object result = pjp.proceed();

    Path path = null;

    if (result instanceof Boolean && !((Boolean) result)) {
        return result;
    }

    try {
        //Locate the path parameter in the arguments
        for (Object arg : pjp.getArgs()) {
            if (arg instanceof Path) {
                path = (Path) arg;
                break;
            }
        }

        metastore.add(path, trackDirectories && pjp.getSignature().getName().contains("mkdir"));
    } catch (TimeoutException t) {
        log.error("Timeout occurred adding path to metastore: " + path, t);

        alertDispatcher.timeout("metastoreUpdate", Collections.singletonList(path));

        if (failOnTimeout) {
            throw t;
        }
    } catch (Exception e) {
        log.error("Failed to add path to metastore: " + path, e);

        if (shouldFail(conf)) {
            throw e;
        }
    }

    return result;
}

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);

    /**//  w w  w . j  av a 2 s . co  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();
    }//from w w w.j a  va  2  s. c o m
    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));
}

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

License:Apache License

@Around(AspectConstants.LOGIC_SERVICE_PACKAGE)
public Object logicServiceProcess(ProceedingJoinPoint pjp)
        throws AuthorityException, ServiceException, Throwable {
    Annotation[] annotations = pjp.getTarget().getClass().getAnnotations();
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    if (annotations == null || annotations.length < 1) {
        return pjp.proceed();
    }/*from   ww w. ja  va  2 s. c o m*/
    String beanId = AspectConstants.getServiceId(annotations);

    /**
     * Hession proxy ?,  remote-server ?, client??, ???, remote-server, client
     */
    if (GreenStepHessianUtils.isEnableCallRemote() && GreenStepHessianUtils.isProxyServiceId(beanId)) {
        return pjp.proceed();
    }

    if (StringUtils.isBlank(beanId)) {
        return pjp.proceed();
    }
    if (!ServiceScriptExpressionUtils.needProcess(beanId, signature.getMethod().getName(),
            Constants.getSystem())) {
        return pjp.proceed();
    }
    Method method = signature.getMethod();
    ServiceScriptExpressionUtils.processBefore(beanId, signature.getMethod(), Constants.getSystem(), pjp);
    Object obj = pjp.proceed();
    ServiceScriptExpressionUtils.processAfter(beanId, method, Constants.getSystem(), obj, pjp);
    return obj;
}

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

License:Apache License

@Around(ServiceAspectConstants.AROUND_VALUE)
public Object aroundMethod(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable {

    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Annotation[] annotations = pjp.getTarget().getClass().getAnnotations();
    String serviceId = this.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  w  w.  j  av  a  2s  . c  om
    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));
}

From source file:com.netsteadfast.greenstep.service.aspect.ServiceScriptExpressionProcessAspect.java

License:Apache License

@Around(ServiceAspectConstants.AROUND_VALUE)
public Object aroundMethod(ProceedingJoinPoint pjp) throws AuthorityException, ServiceException, Throwable {
    Annotation[] annotations = pjp.getTarget().getClass().getAnnotations();
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    if (annotations == null || annotations.length < 1) {
        return pjp.proceed();
    }/*from w  w w  . j av a  2s  . c  o  m*/
    String beanId = "";
    for (int i = 0; i < annotations.length; i++) {
        if (annotations[i] instanceof Service) {
            beanId = ((Service) annotations[i]).value();
        }
    }
    if (StringUtils.isBlank(beanId)) {
        return pjp.proceed();
    }
    if (!ServiceScriptExpressionUtils.needProcess(beanId, signature.getMethod().getName(),
            Constants.getSystem())) {
        return pjp.proceed();
    }
    Method method = signature.getMethod();
    ServiceScriptExpressionUtils.processBefore(beanId, signature.getMethod(), Constants.getSystem(), pjp);
    Object obj = pjp.proceed();
    ServiceScriptExpressionUtils.processAfter(beanId, method, Constants.getSystem(), obj, pjp);
    return obj;
}

From source file:com.newtranx.util.monitoring.MonitorAspect.java

License:Apache License

@Around("@annotation(com.newtranx.util.monitoring.Monitoring)")
public Object around(final ProceedingJoinPoint pjp) throws Throwable {
    final MethodSignature signature = (MethodSignature) pjp.getSignature();
    final Method method = getMethod(signature, pjp);
    final long begin = System.currentTimeMillis();
    MonitorContext monitorContext = new MonitorContext() {

        @Override/*from  ww  w  . j  a  v a  2  s  . c om*/
        public void doReport() {
            long end = System.currentTimeMillis();
            String name = method.getAnnotation(Monitoring.class).value().trim();
            Optional<String> optName = StringUtils.isEmpty(name) ? Optional.empty() : Optional.of(name);
            for (Reporter r : reporters) {
                try {
                    r.report(method, end - begin, optName);
                } catch (Throwable t) {
                    t.printStackTrace(System.err);
                }
            }
        }

    };
    Object[] args = pjp.getArgs();
    AsyncHandler asyncHandler = null;
    for (AsyncHandler a : getAsyncHandlers()) {
        Object[] processedArgs = a.preProcess(method, args, monitorContext);
        if (monitorContext.isAsync()) {
            args = processedArgs;
            asyncHandler = a;
            break;
        }
    }
    Object result = pjp.proceed(args);
    if (monitorContext.isAsync()) {
        return asyncHandler.postProcess(result, monitorContext);
    } else {
        monitorContext.doReport();
        return result;
    }
}