Example usage for org.aspectj.lang ProceedingJoinPoint proceed

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

Introduction

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

Prototype

public Object proceed() throws Throwable;

Source Link

Document

Proceed with the next advice or target method invocation

Usage

From source file:br.com.itw.commons.aop.OnSuccessAdvice.java

License:Apache License

@Around("execution(public * br.com.itw.qopsearch.api.**.*.*(..)) && @annotation(requestMapping)")
public HttpEntity onSuccess(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {

    int length = requestMapping.method().length;
    if (length == 0) {
        throw new IllegalArgumentException(ERRO_SEM_METODO_DEFINIDO);
    }/*from   www.ja  va2  s.co  m*/

    boolean containsGet = Arrays.asList(requestMapping.method()).contains(RequestMethod.GET);
    if (containsGet && length > 1) {
        throw new IllegalArgumentException(ERRO_GET);
    }

    Object object = null;
    Object objectBody = null;
    HttpStatus httpStatus = HttpStatus.OK;

    String methodName = pjp.getSignature().getName();

    if (!containsGet && !methodName.startsWith("find") && !methodName.startsWith("search")) {

        object = pjp.proceed();

        HttpEntity httpEntity;
        ResponseEntity responseEntity;

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        String prefixCode = ON_SUCCESS + pjp.getTarget().getClass().getSimpleName() + "." + methodName;

        String titleCode = prefixCode + "." + TITLE;
        String messageCode = prefixCode + "." + MESSAGE;

        if (!pjp.getSignature().toString().startsWith("void")) {

            if (object instanceof ResponseEntity) {
                responseEntity = (ResponseEntity) object;
                httpStatus = responseEntity.getStatusCode();
                objectBody = responseEntity.getBody();
            } else if (object instanceof HttpEntity) {
                httpEntity = (HttpEntity) object;

                httpStatus = httpEntity == null ? HttpStatus.NO_CONTENT : HttpStatus.CREATED;
                if (HttpStatus.CREATED.equals(httpStatus))
                    objectBody = httpEntity.getBody();
            }

            String title = messageSource.getMessage(titleCode, null, SUCESSO_TITLE, Locale.getDefault());
            headers.add(TITLE, title);

            String sucessoDefault = messageSource.getMessage(SUCESSO_MSG, null, Locale.getDefault());
            String message = messageSource.getMessage(messageCode, null, sucessoDefault, Locale.getDefault());
            headers.add(MESSAGE, message);

            return new ResponseEntity(objectBody, headers, httpStatus);
        } else {
            //Mtodos do tipo void, no tem como fazer nada, o desenvolvedor decidiu retornar 200
            return null;
        }

    }

    return httpGetEntity(pjp, objectBody, httpStatus);

}

From source file:br.com.itw.commons.aop.OnSuccessAdvice.java

License:Apache License

/**
 * Para mtodos do tipo GET, eu verifico se o retorno  nulo ou vazio (no caso de lista)
 * retorna um status NOT_FOUND que pode ser tratado na tela
 *
 * @param pjp//from   w ww  . ja v a2  s. c o m
 * @param objectBody
 * @param httpStatus
 * @return
 * @throws Throwable
 */
private HttpEntity httpGetEntity(ProceedingJoinPoint pjp, Object objectBody, HttpStatus httpStatus)
        throws Throwable {
    HttpEntity returnObject;

    returnObject = (HttpEntity) pjp.proceed();
    boolean found = false;
    if (returnObject != null) {
        objectBody = returnObject.getBody();
        if (objectBody != null) {
            if (objectBody instanceof List) {
                List objectList = (List) objectBody;
                found = !objectList.isEmpty();
            } else if (objectBody instanceof Page) {
                found = ((Page) objectBody).getTotalElements() != 0;
            } else {
                found = true;
            }
        }
    }

    ResponseEntity responseEntity = null;
    if (returnObject instanceof ResponseEntity) {
        responseEntity = (ResponseEntity) returnObject;
        httpStatus = responseEntity.getStatusCode();
    }

    if (!found && responseEntity == null)
        httpStatus = HttpStatus.NOT_FOUND;
    return new ResponseEntity(objectBody, httpStatus);
}

From source file:br.com.reindex.suri.framework.controller.interceptor.BusinessExceptionInterceptor.java

License:Open Source License

@Around("@within(br.com.suricattus.surispring.framework.controller.annotation.AppendBusinessMessages)")
public Object appendMessages(ProceedingJoinPoint pjp) throws Throwable {
    try {//w w  w  .  j  av a2s . c  om
        return pjp.proceed();
    } catch (BusinessException be) {
        for (Message error : be.getErrors()) {
            if (error.getComponentId() != null) {
                FacesUtils.addMsgToComponent(error.getComponentId(), error.getSeverity(), error.getMessage(),
                        error.getParams());
            } else {
                FacesUtils.addMsg(error.getSeverity(), error.getMessage(), error.getParams());
            }
        }
        return null;
    }
}

From source file:br.fucks.initial.config.data.ExceptionPointCut.java

/**
 *
 * @param joinPoint/*w  w  w  . ja  v  a 2 s. c  o m*/
 * @return
 * @throws Throwable
 */
@Around("execution(* br.org.pti.credential.service.*.insert*(..)) || "
        + "execution(* br.org.pti.credential.service.*.update*(..)) || "
        + "execution(* br.org.pti.credential.service.*.save*(..)) || "
        + "execution(* br.org.pti.credential.service.*.remove*(..)) || "
        + "execution(* br.org.pti.credential.service.*.delete*(..))")
public Object doHandleDataIntegrityViolationException(ProceedingJoinPoint joinPoint) throws Throwable {
    try {
        return joinPoint.proceed();
    } catch (DataIntegrityViolationException exception) {
        if (exception.getMostSpecificCause() instanceof PSQLException) {
            PSQLException currentException = (PSQLException) exception.getMostSpecificCause();

            if (currentException.getSQLState().equals(this.DUPLICATED_REGISTER_ERROR)) {
                //manipula a string de exception para pegar o nome do campo duplicado e 
                //gerar uma exception com uma mensagem mais amigavel ao usurio final.
                int start = currentException.getServerErrorMessage().getDetail().indexOf("Key (") + 5;
                int end = currentException.getServerErrorMessage().getDetail().indexOf(")=(");

                String fieldError = currentException.getServerErrorMessage().getDetail().substring(start, end);

                throw new DataIntegrityViolationException(
                        "O campo " + fieldsMessageSource.getMessage(fieldError, null, Locale.getDefault())
                                + " j existe.");
            }
            if (currentException.getSQLState().equals(this.FOREING_KEY_REFERENCED_ERROR)) {
                //manipula a string de exception para pegar o nome do campo duplicado e 
                //gerar uma exception com uma mensagem mais amigavel ao usurio final.
                int start = currentException.getServerErrorMessage().getDetail().indexOf("table ") + 7;
                int end = currentException.getServerErrorMessage().getDetail().indexOf("\".");

                String fieldReference = currentException.getServerErrorMessage().getMessage().substring(
                        currentException.getServerErrorMessage().getMessage().indexOf("on table \"") + 10,
                        currentException.getServerErrorMessage().getMessage().indexOf("\" violates"));
                String fieldReferenceOn = currentException.getServerErrorMessage().getDetail().substring(start,
                        end);

                throw new DataIntegrityViolationException("No  possvel excluir o <b>"
                        + fieldsMessageSource.getMessage(fieldReference, null, Locale.getDefault())
                        + "</b> pois o registro ainda  referenciado em <b>'"
                        + fieldsMessageSource.getMessage(fieldReferenceOn, null, Locale.getDefault())
                        + "'</b>.");
            }
        }
    } catch (AccessDeniedException exception) {
        throw new AccessDeniedException(
                fieldsMessageSource.getMessage(ACCESS_DENIED_EXCEPTION_MESSAGE, null, Locale.getDefault()));
    } catch (Exception exception) {
        return exception;
    }
    return null;
}

From source file:br.uff.ic.tpa.smartpet.aspect.LoggerAspect.java

@Around("execution(* br.uff.ic.tpa.smartpet.service.*.*(..))")
public Object exceptionAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Logger log = Logger.getLogger(joinPoint.getClass().getName());
    try {/*from www.j a  va2 s .c  o m*/
        return joinPoint.proceed();
    } catch (ApplicationException e) {
        throw e;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

From source file:callcount.lib.probe.AbstractStartEndAspect.java

License:Apache License

@Around("monitoredOperation() && notWithinKieker()")
public Object operation(final ProceedingJoinPoint thisJoinPoint) throws Throwable { // NOCS (Throwable)
    final String signature = thisJoinPoint.getSignature().toLongString();
    if (!CTRLINST.isProbeActivated(signature)) {
        return thisJoinPoint.proceed();
    }/* www  . j a v a  2  s  . c  o m*/
    // collect data
    final boolean entrypoint;
    final String hostname = VMNAME;
    final String sessionId = SESSIONREGISTRY.recallThreadLocalSessionId();
    final int eoi; // this is executionOrderIndex-th execution in this trace
    final int ess; // this is the height in the dynamic call tree of this execution
    long traceId = CFREGISTRY.recallThreadLocalTraceId(); // traceId, -1 if entry point
    if (traceId == -1) {
        entrypoint = true;
        traceId = CFREGISTRY.getAndStoreUniqueThreadLocalTraceId();
        CFREGISTRY.storeThreadLocalEOI(0);
        CFREGISTRY.storeThreadLocalESS(1); // next operation is ess + 1
        eoi = 0;
        ess = 0;
    } else {
        entrypoint = false;
        eoi = CFREGISTRY.incrementAndRecallThreadLocalEOI(); // ess > 1
        ess = CFREGISTRY.recallAndIncrementThreadLocalESS(); // ess >= 0
        if ((eoi == -1) || (ess == -1)) {
            LOG.error("eoi and/or ess have invalid values:" + " eoi == " + eoi + " ess == " + ess);
            CTRLINST.terminateMonitoring();
        }
    }
    // measure before
    final long tin = TIME.getTime();
    CTRLINST.newMonitoringRecord(
            new OperationExecutionStartRecord(signature, sessionId, traceId, tin, hostname, eoi, ess));
    // execution of the called method
    final Object retval;
    try {
        retval = thisJoinPoint.proceed();
    } finally {
        // measure after
        final long tout = TIME.getTime();
        CTRLINST.newMonitoringRecord(
                new OperationExecutionStopRecord(sessionId, traceId, tout, hostname, eoi, ess));
        // cleanup
        if (entrypoint) {
            CFREGISTRY.unsetThreadLocalTraceId();
            CFREGISTRY.unsetThreadLocalEOI();
            CFREGISTRY.unsetThreadLocalESS();
        } else {
            CFREGISTRY.storeThreadLocalESS(ess); // next operation is ess
        }
    }
    return retval;
}

From source file:ch.ledcom.tomcat.valves.allocation.AllocationAdvice.java

License:Apache License

public Object traceAllocation(ProceedingJoinPoint pjp) throws Throwable {
    ThreadAllocationTracer tracer = tracerFactory.create();
    tracer.mark();/*from w  w w  .j a v  a2 s . c  o  m*/
    Object retVal = pjp.proceed();
    long allocatedMemory = tracer.allocatedSinceMark();
    for (AllocationReporter reporter : reporters) {
        reporter.report(pjp.toShortString(), allocatedMemory);
    }
    return retVal;
}

From source file:cn.com.esrichina.gcloud.commons.LicenseLevelCheckAspect.java

@Around("execution(* cn.com.esrichina.gcloud.*.web.resources.*.*(..))")
public Object doCheck(ProceedingJoinPoint pjp) throws Throwable {
    Object target = pjp.getTarget();
    String methodName = pjp.getSignature().getName();
    Class[] parameterTypes = ((MethodSignature) pjp.getSignature()).getMethod().getParameterTypes();
    Method method = target.getClass().getMethod(methodName, parameterTypes);
    LicenseLevelCheck licenseLevelCheck = null;
    if (method != null) {
        licenseLevelCheck = method.getAnnotation(LicenseLevelCheck.class);
    }//from  w w w.j  a va2 s  .c o m

    if (licenseLevelCheck == null) {
        try {
            return pjp.proceed();
        } catch (Exception e) {
            throw e;
        }
    } else {
        String needLevel = licenseLevelCheck.level();
        GCloudLicense license = LicenseContext.getInstance().getLicense();
        // if (license == null || license.getLicenseLevel() == null) {
        // throw new
        // RuntimeException(Messages.getMessage("license_not_load"));
        // }

        if (needLevel.equals(GCloudLicense.LEVEL_ADVANCED) && !license.isAdvanced()) {
            throw new RuntimeException(Messages.getMessage("license_level_adv_limit"));
        } else if (needLevel.equals(GCloudLicense.LEVEL_STANDARD) && license.isBasic()) {
            throw new RuntimeException(Messages.getMessage("license_level_adv_limit"));
        }
        try {
            return pjp.proceed();
        } catch (Exception e) {
            throw e;
        }
    }
}

From source file:cn.com.xl.core.aop.BeforeAop.java

License:Apache License

@Around("cutBefore()")
public Object doBefore(ProceedingJoinPoint point) throws Throwable {
    HttpServletRequest request = HttpKit.getRequest();
    MethodSignature ms = (MethodSignature) point.getSignature();
    Method method = ms.getMethod();
    Object[] args = point.getArgs();
    Class<?> clazz = point.getTarget().getClass();
    Before before = method.getAnnotation(Before.class);
    Interceptor ic = before.value().newInstance();
    Object result = ic.intercept(new Invocation(clazz, method, args, request));
    if (null == result) {
        return point.proceed();
    } else {/*from   www. j  a va  2 s . c o m*/
        return result;
    }
}

From source file:cn.com.xl.core.aop.JsonTokenAop.java

License:Apache License

@Around("cutBefore()")
public Object doBefore(ProceedingJoinPoint point) throws Throwable {
    HttpServletRequest request = HttpKit.getRequest();
    Map<String, Object> headMap = new HashMap<String, Object>();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = headerNames.nextElement();
        String value = request.getHeader(key);
        headMap.put(key, value);/*w w w  .j a  va2  s  .  com*/
    }
    String nonce = Convert.toStr(headMap.get("nonce"), "");
    String timestamp = Convert.toStr(headMap.get("timestamp"), "");
    String signature = Convert.toStr(headMap.get("signature"), "");
    String _signature = HashKit.sha1(nonce + timestamp);
    if (!StrKit.equals(_signature, signature)) {
        throw new RuntimeException("????,?!");
    } else {
        return point.proceed();
    }
}