Example usage for org.aspectj.lang ProceedingJoinPoint getTarget

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

Introduction

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

Prototype

Object getTarget();

Source Link

Document

Returns the target object.

Usage

From source file:org.springframework.metrics.instrument.scheduling.MetricsSchedulingAspect.java

License:Apache License

@Around("execution (@org.springframework.scheduling.annotation.Scheduled  * *.*(..))")
public Object timeScheduledOperation(ProceedingJoinPoint pjp) throws Throwable {
    Method method = ((MethodSignature) pjp.getSignature()).getMethod();
    String signature = pjp.getSignature().toShortString();

    if (method.getDeclaringClass().isInterface()) {
        try {/*from   w w w.j  a v a  2  s . co m*/
            method = pjp.getTarget().getClass().getDeclaredMethod(pjp.getSignature().getName(),
                    method.getParameterTypes());
        } catch (final SecurityException | NoSuchMethodException e) {
            logger.warn("Unable to perform metrics timing on " + signature, e);
            return pjp.proceed();
        }
    }

    Timer shortTaskTimer = null;
    LongTaskTimer longTaskTimer = null;

    for (Timed timed : TimedUtils.findTimed(method).toArray(Timed[]::new)) {
        if (timed.longTask())
            longTaskTimer = registry.longTaskTimer(timed.value(), Tags.tagList(timed.extraTags()));
        else {
            Timer.Builder timerBuilder = registry.timerBuilder(timed.value())
                    .tags(Tags.tagList(timed.extraTags()));
            if (timed.quantiles().length > 0) {
                timerBuilder = timerBuilder
                        .quantiles(WindowSketchQuantiles.build().quantile(timed.quantiles()).create());
            }
            shortTaskTimer = timerBuilder.create();
        }
    }

    if (shortTaskTimer != null && longTaskTimer != null) {
        final Timer finalTimer = shortTaskTimer;
        return recordThrowable(longTaskTimer, () -> recordThrowable(finalTimer, pjp::proceed));
    } else if (shortTaskTimer != null) {
        return recordThrowable(shortTaskTimer, pjp::proceed);
    } else if (longTaskTimer != null) {
        return recordThrowable(longTaskTimer, pjp::proceed);
    }

    return pjp.proceed();
}

From source file:org.xaloon.core.api.interceptor.AbstractInterceptor.java

License:Apache License

/**
 * @param pjp//from   w ww  .j av a2 s .  c  om
 * @return
 * @throws Throwable
 */
public Object aroundInvokeAspectJ(ProceedingJoinPoint pjp) throws Throwable {
    org.aspectj.lang.Signature s = pjp.getSignature();
    final MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();
    if (method.getDeclaringClass().isInterface()) {
        method = ClassUtil.getMethodIfAvailable(pjp.getTarget().getClass(), method.getName(),
                method.getParameterTypes());
    }
    if (method == null) {
        throw new RuntimeException("Method not found!");
    }
    Signature signature = new Signature().setMethodName(s.getName()).setDeclaringType(s.getDeclaringType())
            .setDeclaringTypeName(s.getDeclaringTypeName()).setParameters(pjp.getArgs());
    beforeProceed(signature, method.getAnnotation(getAnnotationClass()));
    return pjp.proceed();
}

From source file:sernet.gs.server.RuntimeLogger.java

License:Open Source License

public Object logRuntime(final ProceedingJoinPoint call) throws Throwable {
    Object returnValue;/*from w ww. j av a  2s .  co  m*/
    if (LOG.isDebugEnabled()) {
        final String targetClassName = call.getTarget().getClass().getName();
        final String simpleTargetClassName = call.getTarget().getClass().getSimpleName();
        final String targetMethodName = call.getSignature().getName();
        final Logger targetLog = Logger.getLogger(targetClassName);
        if (targetLog.isDebugEnabled()) {
            final StopWatch clock = new StopWatch(getClass().getName());
            try {
                clock.start(call.toShortString());
                returnValue = call.proceed();
            } finally {
                clock.stop();
                final StringBuffer sb = new StringBuffer("Laufzeit ");
                sb.append(simpleTargetClassName).append(".").append(targetMethodName).append(": ");
                sb.append(clock.getTotalTimeMillis());
                targetLog.debug(sb.toString());
            }
        } else {
            returnValue = call.proceed();
        }
    } else {
        returnValue = call.proceed();
    }
    return returnValue;
}

From source file:springfox.documentation.spring.web.caching.CachingAspect.java

License:Apache License

@Around("(operationRead() || propertiesFor()) && @annotation(cacheable)")
public Object operationsAndProperties(ProceedingJoinPoint joinPoint, Cacheable cacheable) throws Throwable {
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    KeyGenerator keyGenerator = cacheable.keyGenerator().newInstance();
    Object key = keyGenerator.generate(joinPoint.getTarget(), method, joinPoint.getArgs());
    LOG.info("Caching aspect applied for cache {} with key {}", cacheable.value(), key);
    return cachedValue(joinPoint, cacheable.value(), key);
}

From source file:springfox.documentation.spring.web.caching.CachingAspect.java

License:Apache License

@Around("(model() || dependenciesFor()) && @annotation(cacheable)")
public Object modelsAndDependencies(ProceedingJoinPoint joinPoint, Cacheable cacheable) throws Throwable {

    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    KeyGenerator keyGenerator = cacheable.keyGenerator().getDeclaredConstructor(TypeResolver.class)
            .newInstance(typeResolver);//from  ww w .  j a  va2 s  .  co m
    Object key = keyGenerator.generate(joinPoint.getTarget(), method, joinPoint.getArgs());
    LOG.info("Caching aspect applied for cache {} with key {}", cacheable.value(), key);
    return cachedValue(joinPoint, cacheable.value(), key);
}

From source file:stroom.security.server.UserSecurityMethodInterceptor.java

License:Apache License

@SuppressWarnings("unchecked")
private Annotation getSecurityAnnotation(final ProceedingJoinPoint joinPoint) {
    Annotation overridingAnnotation = null;
    boolean annotationOnMethod = false;

    for (final Class<?> clazz : SECURITY_ANNOTATIONS) {
        final Class<Annotation> annotationClass = (Class<Annotation>) clazz;
        Annotation annotation = null;

        // Try and get an annotation from the method.
        try {/*from w  ww  . j a  v  a 2  s. com*/
            final Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            annotation = method.getAnnotation(annotationClass);
            if (annotation == null) {
                // If we didn't get the annotation from the join point
                // method then try the method on the target class.
                final Class<?> targetClass = joinPoint.getTarget().getClass();
                final Method targetMethod = targetClass.getMethod(method.getName(), method.getParameterTypes());
                annotation = targetMethod.getAnnotation(annotationClass);
            }

            // Method annotations override class level annotations so make a
            // note that the annotation was found on a method.
            if (annotation != null) {
                annotationOnMethod = true;
            }
        } catch (final NoSuchMethodException e) {
            LOGGER.error(e.getMessage(), e);
        }

        if (annotation == null && !annotationOnMethod) {
            // If we didn't get one from the method them try the class.
            final Class<?> targetClass = joinPoint.getTarget().getClass();
            annotation = targetClass.getAnnotation(annotationClass);
        }

        if (annotation != null) {
            overridingAnnotation = annotation;
        }
    }

    return overridingAnnotation;
}

From source file:uk.co.exemel.disco.core.impl.kpi.KPIAsyncTimer.java

License:Apache License

@Around("discoAsyncMethod(event, observer)")
public Object measureAsyncMethod(final ProceedingJoinPoint pjp, KPIAsyncTimedEvent event,
        ExecutionObserver observer) throws Throwable {
    final String eventValue = event.value();
    final String eventOperation = event.operation();
    final String name = eventValue.isEmpty() ? pjp.getTarget().getClass().getSimpleName() : eventValue;
    final String operation = eventOperation.isEmpty() ? pjp.getSignature().getName() : eventOperation;

    final KPITimer timer = new KPITimer();
    timer.start();//w  ww  .j  a v a  2s  .  c o m
    final PerformanceMonitoringExecutionObserver perfObserver = new PerformanceMonitoringExecutionObserver(
            observer, monitor, timer, event.catchFailures(), name, operation);

    return pjp.proceed(replaceObserver(perfObserver, pjp.getArgs()));
}

From source file:uk.gov.ofwat.fountain.aspect.audit.AuditAdvice.java

License:Open Source License

/**
 * Interceptor to audit the request and response of a call to the Fountain methods
 * marked above and the GEt methods in the list in 'auditedGetMethods'.
 * @param pjp//from w w w. j a v a 2s .co m
 * @return
 * @throws Throwable
 */
@Around("uk.gov.ofwat.fountain.aspect.audit.AuditAdvice.all()")
public Object auditThis(ProceedingJoinPoint pjp) throws Throwable {
    log.debug("AuditAdvice ... Class: " + pjp.getTarget().getClass().getName() + " Method: "
            + pjp.getSignature().getName());

    // Check that we have a PUT POST or DELETE or GET to selected methods,
    // If not then we will ignore the audit.
    if (!servletRequest.getMethod().equals("PUT") && !servletRequest.getMethod().equals("POST")
            && !servletRequest.getMethod().equals("DELETE")
            && !auditedGetMethods.contains(pjp.getSignature().getName())) {
        return (Object) pjp.proceed();
    }

    Response response = null;
    Date startTime = new Date();
    try {
        response = (Response) pjp.proceed();
        RestAudit audit = doAudit(pjp, startTime, response);
        return response;
    } catch (WebApplicationException webEx) {
        log.error("Caught a WebApplicationException in auditAdvice: " + webEx.toString());
        RestAudit audit = doAudit(pjp, startTime, response, webEx);
        throw webEx;
    } catch (Exception e) {
        log.error("Caught an Exception in auditAdvice: " + e.toString());
        //return response;
        throw e;
    }
}

From source file:uk.gov.ofwat.fountain.aspect.audit.AuditAdvice.java

License:Open Source License

private RestAudit doAudit(ProceedingJoinPoint pjp, Date startTime, Response response, Exception e) {
    // Build a RestAudit object with a view to persisting.
    RestAudit restAudit = new RestAudit();
    restAudit.setHttpMethod(servletRequest.getMethod());
    restAudit.setUri(servletRequest.getRequestURI());
    restAudit.setUser(servletRequest.getUserPrincipal().getName());
    restAudit.setStartDate(startTime);//w  w  w  . j a  v a 2s  .c o  m
    restAudit.setFountainUsers(servletRequest.isUserInRole("OFWAT\\Fountain.Users"));
    restAudit.setFountainEditors(servletRequest.isUserInRole("OFWAT\\Fountain.Editors"));
    restAudit.setFountainAdmins(servletRequest.isUserInRole("OFWAT\\Fountain.Admins"));
    restAudit.setFountainRunAdmin(servletRequest.isUserInRole("OFWAT\\G Fountain Run Admin"));
    restAudit.setResourceClass("" + pjp.getTarget().getClass().getName());
    restAudit.setResourceMethod("" + pjp.getSignature().getName());

    // Get the content!
    HashMap<String, Object> postedContent = getContent(pjp);
    // Vars to keep track if we are being sent or receiving a TableDTO
    Boolean postedTableDto = false;
    Boolean responseTableDto = false;
    // Grab the passed parameters and audit.
    try {
        HashMap<String, String> params = getParams(pjp);
        //Persist the RestAudit Item to the MongoDB and get the Key.     
        Key<RestAudit> key = restAuditDao.createUpdate(restAudit);
        //Initialise GSON
        gson = getGson();
        //Turn posted content to JSON. 
        String jsonPostedContent = gson.toJson(postedContent);
        // We have to make special dispensation for tableDtos as they may be massive.
        if (params.get("tableDto") != null) {
            params.remove("tableDto"); // this is still audited as a JSON doc as the 'Content' and will only be in the params if it's a POST/PUT
            postedTableDto = true;
        }
        //If there is a tableDto, persist the posted content to GridFS then strip the tableDto.
        if (postedTableDto) {
            ObjectId contentMongoId = mongoService.persistToGridFS(jsonPostedContent,
                    servletRequest.getMethod() + ":" + pjp.getSignature().getName() + ".json",
                    "application/json", "RestAudit");
            restAudit.setAttachedGridFsContent(contentMongoId);
            restAudit.setContent((DBObject) JSON.parse("{'GridFSData':true}"));
        } else {
            DBObject contentDbo = (DBObject) JSON.parse(jsonPostedContent);
            restAudit.setContent(contentDbo);
        }
        //finish setting properties.
        restAudit.setAudits(getAudits(response));
        restAudit.setParams(params);
        restAuditDao.createUpdate(restAudit);

        //if e is not null we already have an exception, lets add it to the log.
        if ((e != null) && (e.getClass() == WebApplicationException.class)) {
            WebApplicationException webException = (WebApplicationException) e;
            response = webException.getResponse();
            restAudit.setResponseText(ExceptionUtils.getFullStackTrace(webException));
            restAudit.setResponseCode(Integer.toString(response.getStatus()));
        } else {
            if (response instanceof Response) {
                restAudit.setResponseCode(Integer.toString(((Response) response).getStatus()));

                // This entity can be a number of different DTOs, Lists or Domain Objects - we will build a JSON representation to save it.
                Object responseEntity = ((Response) response).getEntity();
                if ((responseEntity != null) && (responseEntity.getClass() != null)) {
                    Class responseEntityClass = responseEntity.getClass();
                    String responseEntityClassString = responseEntityClass.toString();
                    if (responseEntityClassString.equals("class uk.gov.ofwat.fountain.rest.dto.Report")
                            || responseEntityClassString
                                    .equals("class uk.gov.ofwat.fountain.rest.dto.TableDto")) {
                        responseTableDto = true;
                    }
                }

                String jsonResponseContent = gson.toJson(responseEntity);
                //If we are sending a large DTO back persist this too!
                if (responseTableDto) {
                    ObjectId reponseMongoId = mongoService.persistToGridFS(jsonResponseContent,
                            String.valueOf(response.getStatus()) + ":" + pjp.getSignature().getName() + ".json",
                            "application/json", "RestAudit");
                    restAudit.setAttachedGridFsResponse(reponseMongoId);
                    restAudit.setResponseEntity((DBObject) JSON.parse("{'GridFSData':true}"));
                } else {
                    HashMap<String, Object> responseEntityMap = new HashMap<String, Object>();
                    responseEntityMap.put("entity", responseEntity);
                    String jsonResponse = gson.toJson(responseEntityMap);
                    restAudit.setResponseEntity((DBObject) JSON.parse(jsonResponse));
                }
            }
        }
        restAudit.setEndDate(new Date());
        restAuditDao.createUpdate(restAudit);
    } catch (Exception e1) {
        // log the exception
        if (MongoException.class.isAssignableFrom(e1.getClass())) {
            log.error("\n\n\n*** Potentially not logged anything - caught a Mongo Exception:" + e1.toString()
                    + "\n\n\n***");
        } else {
            try {
                log.error("\n\n\n*** Caught an exception in audit advice, trying to persist a record: "
                        + e1.toString() + " ***\n\n\n");
                restAudit.setResponseText(ExceptionUtils.getFullStackTrace(e1));
                restAudit.setResponseCode("ERR");
                restAudit.setEndDate(new Date());
                restAuditDao.createUpdate(restAudit);
            } catch (Exception e2) {
                log.error(
                        "\n\n\n*** Unable to persist audit record correctly: " + e2.toString() + " ***\n\n\n");
            }
        }
    }
    return restAudit;
}

From source file:uk.gov.ofwat.fountain.aspect.cache.dao.generic.FindByCodeAspect.java

License:Open Source License

@SuppressWarnings({ "unchecked" })
@Around("uk.gov.ofwat.fountain.aspect.cache.dao.DaoCache.findByCodePC()")
public Object cacheOnFindByCode(ProceedingJoinPoint pjp) throws Throwable {
    if (!isEnabled()) {
        return pjp.proceed();
    }//from  www . j  a  va 2  s  .com
    if (null == getCache()) {
        initialiseCache(pjp.getTarget().getClass());
    }

    if (null == cacheByCode) {
        cacheByCode = Collections.synchronizedMap(new LRUMap(getCacheSize()));
    }
    Object[] args = pjp.getArgs();
    String key = (String) args[0];

    Object retVal = null;
    if (cacheByCode.containsKey(key)) {
        retVal = cacheByCode.get(key);
    } else {
        retVal = pjp.proceed();
        if (null != retVal) {
            // don't store nulls.
            cacheByCode.put(key, (Object) retVal);
            incrementCache(pjp);
        }
    }

    return retVal;
}