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:org.kaleidofoundry.core.context.AnnotationContexInjectorAspect.java

License:Apache License

/**
 * @param jp/*  www. j a v  a2 s  .  c  om*/
 * @param esjp
 * @param thisJoinPoint
 * @param annotation
 * @return <code>true / false</code> if join point have been processed
 * @throws Throwable
 */
// track field with ProceedingJoinPoint and annotation information with @annotation(annotation)
@Around("trackAgregatedRuntimeContextField(jp, esjp) && @annotation(annotation)")
@Task(comment = "check and handle reflection exception ", labels = TaskLabel.Enhancement)
public Object trackAgregatedRuntimeContextFieldToInject(final JoinPoint jp,
        final JoinPoint.EnclosingStaticPart esjp, final ProceedingJoinPoint thisJoinPoint,
        final Context annotation) throws Throwable {

    debugJoinPoint(LOGGER, jp);

    if (thisJoinPoint.getSignature() instanceof FieldSignature) {
        final FieldSignature annotatedFieldSignature = (FieldSignature) thisJoinPoint.getSignature();
        final Field annotatedField = annotatedFieldSignature.getField();
        final Boolean annotatedFieldInjected = _$injectedFieldMap.get(annotatedField);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("\t<joinpoint.field.{}.injected>\t{}", annotatedField.getName(),
                    annotatedFieldInjected == null ? Boolean.FALSE : annotatedFieldInjected.booleanValue());
        }

        // does the field to inject have already been injected
        if (annotatedFieldInjected == null || !annotatedFieldInjected.booleanValue()) {
            // we need to access to its fields, in order to lookup for a RuntimeContext field
            annotatedField.setAccessible(true);
            final Object targetInstance = thisJoinPoint.getTarget();
            Object fieldValue = targetInstance != null ? annotatedField.get(targetInstance) : null;

            // process field initialize if null
            if (targetInstance != null && fieldValue == null) {

                // does the plugin interface have a provider specify
                if (annotatedField.getType().isAnnotationPresent(Provider.class)) {

                    // create provider using annotation meta-information
                    final Provider providerInfo = annotatedField.getType().getAnnotation(Provider.class);
                    final Constructor<? extends ProviderService<?>> providerConstructor = providerInfo.value()
                            .getConstructor(Class.class);
                    final ProviderService<?> fieldProviderInstance = providerConstructor
                            .newInstance(annotatedField.getType());

                    // invoke provides method with Context annotation meta-informations
                    final Method providesMethod = providerInfo.value().getMethod(
                            ProviderService.PROVIDES_METHOD, Context.class, String.class, Class.class);

                    try {
                        fieldValue = providesMethod.invoke(fieldProviderInstance, annotation,
                                annotatedField.getName(), annotatedField.getType());
                    } catch (final InvocationTargetException ite) {
                        // direct runtime exception like ContextException...
                        throw ite.getCause() != null ? ite.getCause()
                                : (ite.getTargetException() != null ? ite.getTargetException() : ite);
                    }
                    // set the field that was not yet injected
                    annotatedField.set(targetInstance, fieldValue);
                }

            }

            // if field instance have RuntimeContext not annotated @Context, that have not yet been initialize
            if (targetInstance != null && fieldValue != null) {

                // does a RuntimeContext field have been found
                boolean targetRuntimeContextFieldFound = false;

                // scan accessible field (private, protected, public)
                final Set<Field> contextFields = ReflectionHelper.getAllDeclaredFields(fieldValue.getClass(),
                        Modifier.PRIVATE, Modifier.PROTECTED, Modifier.PUBLIC);

                // for each RuntimeContext field, that are not annotated by @Context (to skip direct injection aspect)
                for (final Field cfield : contextFields) {

                    if (cfield.getType().isAssignableFrom(RuntimeContext.class)
                            && !cfield.isAnnotationPresent(Context.class)) {

                        RuntimeContext<?> currentRuntimeContext = null;
                        targetRuntimeContextFieldFound = true;
                        cfield.setAccessible(true);

                        currentRuntimeContext = (RuntimeContext<?>) cfield.get(fieldValue);

                        // if runtime context field have not yet been set
                        if (currentRuntimeContext == null
                                || !currentRuntimeContext.hasBeenInjectedByAnnotationProcessing()) {

                            // does the implementation is a declare plugin
                            final Plugin<?> interfacePlugin = PluginHelper.getInterfacePlugin(fieldValue);

                            // create a new instance of RuntimeContext<?>, using annotation information
                            final RuntimeContext<?> newRuntimeContext = RuntimeContext.createFrom(annotation,
                                    annotatedField.getName(),
                                    interfacePlugin != null ? interfacePlugin.getAnnotatedClass() : null);

                            // inject new RuntimeContext<?> field instance to the target instance
                            if (!Modifier.isFinal(cfield.getModifiers())) {
                                cfield.set(fieldValue, newRuntimeContext);
                            }
                            // re-copy runtimeContext information to the existing one
                            else {
                                if (currentRuntimeContext != null) {
                                    RuntimeContext.copyFrom(newRuntimeContext, currentRuntimeContext);
                                } else {
                                    // RuntimeContext field is final && null
                                    throw new ContextException("context.annotation.illegalfield",
                                            fieldValue.getClass().getName(), cfield.getName());
                                }
                            }

                            // mark instance has injected
                            _$injectedFieldMap.put(annotatedField, Boolean.TRUE);
                        }
                    }
                }

                // coherence checks
                if (!targetRuntimeContextFieldFound) {
                    throw new ContextException("context.annotation.illegaluse.noRuntimeContextField",
                            annotatedFieldSignature.getFieldType().getName() + "#" + annotatedField.getName(),
                            Context.class.getName());
                }

            }
        }

        return thisJoinPoint.proceed();

    } else {
        throw new IllegalStateException("aspect advise handle only field, please check your pointcut");
    }

}

From source file:org.kaleidofoundry.core.persistence.PersistenceContextAspect.java

License:Apache License

@Around("trackEntityManagerFactoryField(jp, esjp) && @annotation(annotation)")
public Object trackEntityManagerFactoryToInject(final JoinPoint jp, final JoinPoint.EnclosingStaticPart esjp,
        final ProceedingJoinPoint thisJoinPoint, final PersistenceUnit annotation) throws Throwable {

    if (thisJoinPoint.getSignature() instanceof FieldSignature) {
        FieldSignature fs = (FieldSignature) thisJoinPoint.getSignature();
        Object target = thisJoinPoint.getTarget();
        Field field = fs.getField();
        field.setAccessible(true);/*from w w  w . java2 s  .  co  m*/
        Object currentValue = field.get(target);

        if (currentValue == null && !_$injectedObjects.contains(target)) {
            _$injectedObjects.add(target);
            String persistenceUnit = annotation.unitName();
            EntityManagerFactory entityManagerFactory = UnmanagedEntityManagerFactory
                    .getEntityManagerFactory(persistenceUnit);
            field.set(target, entityManagerFactory);
            return entityManagerFactory;
        } else {
            return thisJoinPoint.proceed();
        }
    } else {
        throw new IllegalStateException("aspect advise handle only field, please check your pointcut");
    }
}

From source file:org.kaleidofoundry.core.persistence.PersistenceContextAspect.java

License:Apache License

@Around("trackEntityManagerField(jp, esjp) && @annotation(annotation)")
public Object trackEntityManagerToInject(final JoinPoint jp, final JoinPoint.EnclosingStaticPart esjp,
        final ProceedingJoinPoint thisJoinPoint, final PersistenceContext annotation) throws Throwable {

    if (thisJoinPoint.getSignature() instanceof FieldSignature) {
        FieldSignature fs = (FieldSignature) thisJoinPoint.getSignature();
        Object target = thisJoinPoint.getTarget();
        Field field = fs.getField();
        field.setAccessible(true);/*www . j  a v  a2s .c o m*/
        Object currentValue = field.get(target);

        if (currentValue == null && !_$injectedObjects.contains(target)) {
            _$injectedObjects.add(target);
            String persistenceContext = annotation.unitName();
            EntityManager entityManager = UnmanagedEntityManagerFactory
                    .currentEntityManager(persistenceContext);
            field.set(target, entityManager);
            return entityManager;
        } else {
            return thisJoinPoint.proceed();
        }
    } else {
        throw new IllegalStateException("aspect advise handle only field, please check your pointcut");
    }
}

From source file:org.kiji.mapreduce.util.MRLogTimerAspect.java

License:Apache License

/**
 * Advice around functions that match PointCut "profile".
 *
 * @param thisJoinPoint The JoinPoint that matched the pointcut.
 * @return Object returned by function which matched PointCut "profile".
 * @throws Throwable if there is an exception in the function the advice surrounds.
 *///from w w  w . ja v  a2 s  .c  o  m
@Around("execution(* org.kiji.mapreduce.impl.HFileWriterContext.put(..)) || "
        + "execution(* org.kiji.mapreduce.framework.KijiTableInputFormat.KijiTableRecordReader.nextKeyValue(..))")
public Object aroundProfileMethods(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
    final long start, end;
    start = System.nanoTime();
    Object returnanswer = thisJoinPoint.proceed();
    end = System.nanoTime();
    String funcSig = thisJoinPoint.getSignature().toLongString();
    if (!mSignatureTimeMap.containsKey(funcSig)) {
        mSignatureTimeMap.put(funcSig, new LoggingInfo(end - start, 1));
    } else {
        mSignatureTimeMap.get(funcSig).increment(end - start);
    }
    return returnanswer;
}

From source file:org.kiji.schema.util.LogTimerAspect.java

License:Apache License

/**
 * Advice around functions that match PointCut "profile".
 *
 * @param thisJoinPoint The JoinPoint that matched the pointcut.
 * @return Object returned by function which matched PointCut "profile".
 * @throws Throwable if there is an exception in the function the advice surrounds.
 *//*w w  w .  j  a  v a  2s.c om*/
@Around("execution(* org.kiji.schema.KijiCellDecoder.*(..)) || "
        + "execution(* org.kiji.schema.KijiCellEncoder.*(..)) || "
        + "execution(* org.kiji.schema.KijiMetaTable.*(..)) || "
        + "execution(* org.kiji.schema.KijiSchemaTable.*(..)) || "
        + "execution(* org.kiji.schema.KijiPutter.put(..))")
public Object aroundProfileMethods(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
    final long start, end;
    start = System.nanoTime();
    Object returnanswer = thisJoinPoint.proceed();
    end = System.nanoTime();
    String funcSig = thisJoinPoint.getSignature().toLongString();
    if (!mSignatureTimeMap.containsKey(funcSig)) {
        mSignatureTimeMap.put(funcSig, new LoggingInfo(end - start, 1));
    } else {
        mSignatureTimeMap.get(funcSig).increment(end - start);
    }
    return returnanswer;
}

From source file:org.kuali.student.common.util.spring.MethodArgsToObjectEhcacheAdvice.java

License:Educational Community License

private MultiKey getCacheKey(ProceedingJoinPoint pjp) {
    List<Object> keyList = new ArrayList<Object>();
    keyList.add(pjp.getSignature().getName());
    for (Object arg : pjp.getArgs()) {
        if (arg == null) {
            keyList.add("_null_");
        } else {/*from  ww w.  jav a2 s .  c  o  m*/
            keyList.add(arg.toString());
        }
    }
    return new MultiKey(keyList.toArray());
}

From source file:org.lcmanager.gdb.appl.aspect.LoggingAspect.java

License:Apache License

/**
 * Logs the execution of the given {@link ProceedingJoinPoint}.
 *
 * <p>//ww  w .java2 s .c o  m
 * This method intercepts all classes in the GDB but {@link LoggingAspect}.
 * </p>
 *
 * @param joinPoint
 *            The {@link ProceedingJoinPoint} to log.
 * @return The return of the {@link ProceedingJoinPoint}.
 * @throws Throwable
 *             If the {@link ProceedingJoinPoint} throws it.
 */
@Around("gdb() && !me()")
public Object log(final ProceedingJoinPoint joinPoint) throws Throwable {
    assert joinPoint != null;

    final Signature signature = joinPoint.getSignature();
    final Logger logger = LoggerFactory.getLogger(signature.getDeclaringType());
    Object result = null;
    if (logger.isTraceEnabled()) {
        final StopWatch stopWatch = new StopWatch();

        Throwable throwable = null;

        stopWatch.start();
        try {
            result = joinPoint.proceed();
        } catch (final Throwable t) {
            throwable = t;
        }
        stopWatch.stop();

        this.log(signature, stopWatch, throwable);

        if (throwable != null) {
            throw throwable;
        }
    } else {
        result = joinPoint.proceed();
    }
    return result;
}

From source file:org.lcmanager.gdb.web.control.status.StatusAspect.java

License:Apache License

/**
 * The actual pointcut for intercepting the methods with status generation.
 * //from w  ww. j  a  v  a 2 s  .  c o  m
 * <p>
 * This wraps all all public controller methods within the GDB that are
 * within a generate-status class or are generate-status methods.
 * </p>
 *
 * @param joinPoint
 *            The join point.
 * @return The result object with the appropriate status.
 * @throws Throwable
 *             If any error occurs during the join point invocation.
 */
@Around("gdb() && publicMethod() && requestMethod() && ( generateStatusClass() || generateStatusMethod() )")
public ResponseEntity around(final ProceedingJoinPoint joinPoint) throws Throwable {
    ResponseEntity responseEntity;
    Object body = null;
    try {
        responseEntity = (ResponseEntity) joinPoint.proceed();
        body = responseEntity.getBody();
    } catch (final NullContentException dummy) {
        responseEntity = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    final Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    final StatusGenerator statusGenerator = this.extractStatusGenerator(method);
    final HttpStatus generatedStatus = statusGenerator.generateStatus(method, body);

    final HttpStatus status = generatedStatus == null ? responseEntity.getStatusCode() : generatedStatus;

    return ResponseEntity.status(status).body(body);
}

From source file:org.lexevs.cache.MethodCachingProxy.java

License:Open Source License

@Override
protected Method getMethod(ProceedingJoinPoint joinPoint) {
    MethodSignature sig = (MethodSignature) joinPoint.getSignature();

    return sig.getMethod();
}

From source file:org.mifos.rest.approval.aop.AspectJRESTApprovalInterceptor.java

License:Open Source License

@Around("restMethods() && requestMapping() && excludeAPI() && exludeRestfulServices()")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
    Signature signature = pjp.getStaticPart().getSignature();
    LOG.debug(this.getClass().getSimpleName() + " staring");

    // FIXME : somehow autowiring is not working
    if (approvalService == null) {
        approvalService = ApplicationContextProvider.getBean(ApprovalService.class);
    }/*from  www.ja v  a  2 s . c om*/
    if (configurationServiceFacade == null) {
        configurationServiceFacade = ApplicationContextProvider.getBean(ConfigurationServiceFacade.class);
    }
    if (parameterNameDiscoverer == null) {
        parameterNameDiscoverer = ApplicationContextProvider.getBean(ParameterNameDiscoverer.class);
    }

    if (!RESTConfigKey.isApprovalRequired(configurationServiceFacade)) {
        LOG.debug(pjp.getSignature() + " skip approval");
        return pjp.proceed();
    }

    if (signature instanceof MethodSignature) {
        MethodSignature ms = (MethodSignature) signature;
        Method m = ms.getMethod();
        RequestMapping mapping = m.getAnnotation(RequestMapping.class);

        if (isReadOnly(mapping)) {
            LOG.debug(m.getName() + " is read only, hence returning control");
            return pjp.proceed();
        }

        Class<?> methodClassType = m.getDeclaringClass();

        if (!methodClassType.getSimpleName().endsWith("RESTController")) {
            LOG.debug(m.getName() + " is not from REST controller, hence returning control");
            return pjp.proceed();
        }

        Object[] argValues = pjp.getArgs();

        Class<?>[] argTypes = m.getParameterTypes();
        String methodName = m.getName();
        String[] names = parameterNameDiscoverer.getParameterNames(m);

        MethodArgHolder args = new MethodArgHolder(argTypes, argValues, names);
        ApprovalMethod method = new ApprovalMethod(methodName, methodClassType, args);
        approvalService.create(method);
    }
    return pjp.proceed();
}