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.gridgain.grid.test.aop.aspectj.GridifyJunitAspectJAspect.java

License:GNU General Public License

/**
 * Executes JUnit4 tests annotated with {@link GridifyTest @GridifyTest} annotation
 * on the grid.//from w  w w  .ja  v a  2  s.c o  m
 *
 * @param joinPoint Join point provided by AspectJ AOP.
 * @return Method execution result.
 * @throws Throwable If execution failed.
 */
@Around("execution(public void (org.junit.runners.Suite).run(org.junit.runner.notification.RunNotifier))"
        + "&& !cflow(target(org.gridgain.grid.test.junit4.GridJunit4Suite))")
public Object gridifyJunit4(ProceedingJoinPoint joinPoint) throws Throwable {
    Describable suite = (Describable) joinPoint.getTarget();

    // We create class with caller class loader,
    // thus JUnit 4 task will pick up proper class loader.
    ClassLoader clsLdr = joinPoint.getSignature().getDeclaringType().getClassLoader();

    Class<?> cls = Class.forName(suite.getDescription().getDisplayName(), true, clsLdr);

    if (cls.getAnnotation(GridifyTest.class) != null) {
        new GridJunit4Suite(cls, clsLdr).run((RunNotifier) joinPoint.getArgs()[0]);

        return null;
    }

    return joinPoint.proceed();
}

From source file:org.jbb.lib.properties.encrypt.PropertiesEncryptionAspect.java

License:Apache License

@Around("execution(* org.jbb.lib.properties.ModuleProperties.setProperty(..)) && args(key, value)")
public void decryptIfApplicable(ProceedingJoinPoint joinPoint, String key, String value) throws Throwable {
    ModuleProperties properties = (ModuleProperties) joinPoint.getTarget();
    String currentProperty = properties.getProperty(key);
    if (isInDecPlaceholder(currentProperty)) {
        String newEncryptedValue = propertiesEncryption.encryptIfNeeded(surroundWithEncPlaceholder(value));
        joinPoint.proceed(new Object[] { key, newEncryptedValue });
    } else {// w ww.  ja  v  a 2s.  co  m
        joinPoint.proceed();
    }
}

From source file:org.jbb.lib.properties.SafeBlankPropertyAspect.java

License:Apache License

@Around("execution(* org.jbb.lib.properties.ModuleProperties.getProperty(..)) && args(key)")
public Object makeSafeBlankProperty(ProceedingJoinPoint joinPoint, String key) {
    ModuleProperties properties = (ModuleProperties) joinPoint.getTarget();
    String currentProperty = properties.getProperty(key);
    return StringUtils.defaultIfBlank(currentProperty, null);
}

From source file:org.jdal.audit.Auditor.java

License:Apache License

/**
 * Around advice to audit auditable models
 * /*from  ww w  .jav  a  2  s. c  om*/
 * @param pjp to pjp
 * @return object result
 * @throws Throwable Exception
 */
public Object audit(ProceedingJoinPoint pjp) throws Throwable {
    LOG.debug("Auditing on method: " + pjp.toShortString());
    Object result = pjp.proceed();
    if (pjp.getTarget() instanceof Auditable) {
        Auditable auditable = (Auditable) (pjp.getTarget());
        audit(auditable);
    } else {
        LOG.warn("Tried to audit a non-auditable object. Check your "
                + "AOP configuration on applicationContext.xml");
    }
    return result;
}

From source file:org.kaleidofoundry.core.context.AnnotationContexInjectorAspect.java

License:Apache License

/**
 * @param jp//  w  w w.java  2s .  com
 * @param esjp
 * @param thisJoinPoint
 * @param annotation
 * @return <code>true / false</code> to enable poincut
 * @throws Throwable
 */
// track field with ProceedingJoinPoint and annotation information with @annotation(annotation)
@SuppressWarnings("unchecked")
@Around("trackRuntimeContextField(jp, esjp) && @annotation(annotation)")
public Object trackRuntimeContextFieldToInject(final JoinPoint jp, final JoinPoint.EnclosingStaticPart esjp,
        final ProceedingJoinPoint thisJoinPoint, final Context annotation) throws Throwable {
    if (thisJoinPoint.getSignature() instanceof FieldSignature) {
        final FieldSignature fs = (FieldSignature) thisJoinPoint.getSignature();
        final Object target = thisJoinPoint.getTarget();
        final Field field = fs.getField();
        field.setAccessible(true);
        final Object currentValue = field.get(target);
        if (currentValue == null) {
            final RuntimeContext<?> runtimeContext = RuntimeContext.createFrom(annotation, fs.getName(),
                    fs.getFieldType());
            field.set(target, runtimeContext);
            return runtimeContext;
        } else {
            return thisJoinPoint.proceed();
        }
    } else {
        throw new IllegalStateException("aspect advise handle only field, please check your pointcut");
    }
}

From source file:org.kaleidofoundry.core.context.AnnotationContexInjectorAspect.java

License:Apache License

/**
 * @param jp/*from w w w.ja  va 2  s . c o m*/
 * @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  .ja  v  a  2s . c  o  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);/*from w w w .j  a  va 2  s.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.lcmanager.gdb.base.health.HealthAspect.java

License:Apache License

/**
 * Wraps around all public methods of {@link HealthRelevant health-relevant}
 * classes that are not marked with {@link NoHealthTrace}.
 * /*from  w  w  w. ja v a2s . co  m*/
 * <p>
 * This increments {@link #total} and {@link #error}.
 * </p>
 *
 * @param joinPoint
 *            The proceeding join point.
 * @return The result object of the join point.
 * @throws Throwable
 *             If the join point throws an error.
 */
@Around("within(org.lcmanager.gdb.base.health.HealthRelevant+) " //
        + "&& execution(public * *(..)) " //
        + "&& !execution(@org.lcmanager.gdb.base.health.NoHealthTrace * *(..))")
public Object aroundHealthRelevant(final ProceedingJoinPoint joinPoint) throws Throwable {
    final Class<?> clazz = joinPoint.getTarget().getClass();

    this.incrementTotal(clazz);

    try {
        return joinPoint.proceed();
    } catch (final Throwable error) {
        this.incrementError(clazz);

        throw error;
    }
}

From source file:org.lcmanager.gdb.base.health.HealthAspect.java

License:Apache License

/**
 * Wraps around the {@link HealthRelevant#health()} method and provides its
 * implementation.// w  ww  .java  2  s .  co  m
 *
 * @param joinPoint
 *            The join point that is only used to retrieve the implementing
 *            class.
 * @return The resulting health depending on the total invocations and the
 *         failed invocations.
 */
@Around("execution(* org.lcmanager.gdb.base.health.HealthRelevant+ .health())")
public Health aroundHealth(final ProceedingJoinPoint joinPoint) {
    final Class<?> clazz = joinPoint.getTarget().getClass();
    final int totalCount = this.nullOrZero(this.total.get(this.makeCountKey(clazz)));
    final int errorCount = this.nullOrZero(this.error.get(this.makeCountKey(clazz)));
    final Health.Builder healthBuilder;
    if (MathUtil.calulatePercentage(totalCount, errorCount) < this.unstableThreshold) {
        healthBuilder = Health.up();
    } else {
        healthBuilder = Health.status(HealthAspect.UNSTABLE);
    }
    healthBuilder.withDetail("total", totalCount);
    healthBuilder.withDetail("error", errorCount);
    return healthBuilder.build();
}