Example usage for org.aspectj.lang.reflect FieldSignature getField

List of usage examples for org.aspectj.lang.reflect FieldSignature getField

Introduction

In this page you can find the example usage for org.aspectj.lang.reflect FieldSignature getField.

Prototype

public Field getField();

Source Link

Usage

From source file:at.ac.tuwien.infosys.jcloudscale.aspects.CloudObjectAspect.java

License:Apache License

@Around("target(object) && "
        + "(get(!@at.ac.tuwien.infosys.jcloudscale.annotations.Local * @at.ac.tuwien.infosys.jcloudscale.annotations.CloudObject *.*) || "
        + " get(!@at.ac.tuwien.infosys.jcloudscale.annotations.Local * @at.ac.tuwien.infosys.jcloudscale.annotations.CloudObjectParent *.*))")
public Object getCloudObjectField(Object object, ProceedingJoinPoint pjp) throws Throwable {

    // //w ww.ja  v  a  2  s  .  c  o  m

    if (JCloudScaleConfiguration.isServerContext())
        return pjp.proceed();

    UUID id = CloudObjects.getId(object);

    if (id == null) {
        // maybe we are just working on a cloudobjectparent that is not actually a cloud object
        return pjp.proceed();
    }

    FieldSignature sig = (FieldSignature) pjp.getSignature();
    Field field = sig.getField();

    return getFieldValue(id, field);

}

From source file:at.ac.tuwien.infosys.jcloudscale.aspects.CloudObjectAspect.java

License:Apache License

@Around("target(object) && args(val) && "
        + "(set(!@at.ac.tuwien.infosys.jcloudscale.annotations.Local * @at.ac.tuwien.infosys.jcloudscale.annotations.CloudObject *.*) || "
        + " set(!@at.ac.tuwien.infosys.jcloudscale.annotations.Local * @at.ac.tuwien.infosys.jcloudscale.annotations.CloudObjectParent *.*))")
public void setCloudObjectField(Object object, Object val, ProceedingJoinPoint pjp) throws Throwable {

    if (JCloudScaleConfiguration.isServerContext()) {
        pjp.proceed();/*from  www . j  a  va2 s.c  o m*/
        return;
    }

    UUID id = CloudObjects.getId(object);

    if (id == null) {
        // maybe we are just working on a cloudobjectparent that is not actually a cloud object
        pjp.proceed();
        return;
    }

    if (CloudObjects.isDestroyed(id)) {
        // throw new JCloudScaleException("Field access on already destroyed CloudObject!");
        // this case happens during regular object construction - just proceed
        pjp.proceed();
        return;
    }

    FieldSignature sig = (FieldSignature) pjp.getSignature();
    Field field = sig.getField();

    setFieldValue(id, field, val);

}

From source file:at.ac.tuwien.infosys.jcloudscale.server.aspects.StaticFieldAspect.java

License:Apache License

@Around("args(newval) && set(@at.ac.tuwien.infosys.jcloudscale.annotations.CloudGlobal static * *.*)")
public void writeStaticValueToClient(ProceedingJoinPoint pjp, Object newval) throws Throwable {

    if (!JCloudScaleConfiguration.isServerContext()) {
        pjp.proceed();//from   w  ww . j a  v a2s  .  co  m
        return;
    }

    try (IMQWrapper mq = JCloudScaleConfiguration.createMQWrapper()) {
        UUID corrId = UUID.randomUUID();

        FieldSignature sig = (FieldSignature) pjp.getSignature();
        Field field = sig.getField();

        Object newValProcessed = JCloudScaleReferenceManager.getInstance().processField(field, newval);
        byte[] serialzed = SerializationUtil.serializeToByteArray(newValProcessed);

        SetStaticValueRequest req = new SetStaticValueRequest();
        req.setField(field.getName());
        req.setClassName(field.getDeclaringClass().getCanonicalName());
        req.setValue(serialzed);

        mq.createQueueProducer(
                JCloudScaleConfiguration.getConfiguration().server().getStaticFieldWriteRequestQueueName());
        mq.createTopicConsumer(
                JCloudScaleConfiguration.getConfiguration().server().getStaticFieldWriteResponseTopicName(),
                "JMSCorrelationID = '" + corrId.toString() + "'");

        // we send request and wait for response to ensure that we in fact 
        // changed the value before continuing. 
        mq.requestResponse(req, corrId);

    } catch (JMSException | NamingException | IOException e) {
        e.printStackTrace();
        log.severe("Could not write static field: " + e.getMessage());
    }

}

From source file:at.ac.tuwien.infosys.jcloudscale.server.aspects.StaticFieldAspect.java

License:Apache License

@Around("get(@at.ac.tuwien.infosys.jcloudscale.annotations.CloudGlobal static * *.*)")
public Object readStaticValueFromClient(ProceedingJoinPoint pjp) throws Throwable {

    if (!JCloudScaleConfiguration.isServerContext())
        return pjp.proceed();

    Object returned = null;//ww  w .j  ava2s. co  m

    try (IMQWrapper mq = JCloudScaleConfiguration.createMQWrapper()) {

        FieldSignature sig = (FieldSignature) pjp.getSignature();
        Field field = sig.getField();

        GetStaticValueObject req = new GetStaticValueObject();
        req.setClassName(field.getDeclaringClass().getCanonicalName());
        req.setField(field.getName());

        mq.createQueueProducer(
                JCloudScaleConfiguration.getConfiguration().server().getStaticFieldReadRequestQueueName());
        UUID corrId = UUID.randomUUID();
        mq.createTopicConsumer(
                JCloudScaleConfiguration.getConfiguration().server().getStaticFieldReadResponsesQueueName(),
                "JMSCorrelationID = '" + corrId.toString() + "'");
        GetStaticValueReturnObject ret = (GetStaticValueReturnObject) mq.requestResponse(req, corrId);

        ClassLoader classLoader = field.getDeclaringClass().getClassLoader();
        returned = SerializationUtil.getObjectFromBytes(ret.getValue(), classLoader);
        returned = JCloudScaleReferenceManager.getInstance().processField(field, returned);
        returned = CgLibUtil.replaceRefWithProxy(returned, classLoader);

    } catch (JCloudScaleException e) {
        // this should happen if the by-ref type did not have a default constructor
        e.printStackTrace();
        throw e;
    } catch (JMSException | NamingException | TimeoutException | ClassNotFoundException | IOException e) {
        e.printStackTrace();
        log.severe("Could not write static field: " + e.getMessage());
    }

    return returned;
}

From source file:com.github.msoliter.iroh.container.aspects.IrohAspect.java

License:Apache License

/**
 * Aspect advice triggered on the access of all fields carrying an
 * {@link com.github.msoliter.iroh.container.annotations.Autowired} 
 * annotation. If the field has been marked for lazy injection, and has not 
 * been injected with an instance yet, this advice will properly initialize 
 * that field.//from  w w  w. ja v  a2  s . c  o  m
 * 
 * @param thisJoinPoint The join point carrying critical information about
 *  which field is being accessed, as well as its current contents.
 */
@Before("external() && access()")
public void lazilyInjectField(JoinPoint thisJoinPoint) {
    FieldSignature fs = (FieldSignature) thisJoinPoint.getSignature();
    Field field = fs.getField();
    Object target = thisJoinPoint.getTarget();
    injector.lazilyInject(target, field);
}

From source file:net.sourceforge.safr.core.interceptor.SecurityAspect.java

License:Apache License

private EncryptAttribute getFieldEncryptAttribute(FieldSignature signature) {
    return getSecurityAttributeSource().getFieldEncryptAttribute(signature.getField());
}

From source file:org.failearly.ajunit.internal.universe.matcher.FieldJoinPointMatcher.java

License:Open Source License

@Override
protected boolean doMatchSignature(FieldSignature signature, AjJoinPoint ajUnitJoinPoint) {
    return signature.getField().equals(ajUnitJoinPoint.getField());
}

From source file:org.failearly.ajunit.internal.universe.matcher.FieldJoinPointMatcherTest.java

License:Open Source License

private Signature createFieldSignatureMock(String fieldName) {
    final FieldSignature fieldSignature = mock(FieldSignature.class);
    when(fieldSignature.getField()).thenReturn(resolveField(fieldName));

    LOGGER.debug("FieldSignature Mock - getField() = {}", fieldSignature.getField());

    return fieldSignature;
}

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

License:Apache License

/**
 * @param jp/*from ww  w.  j  a va2  s  .  co m*/
 * @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 ww w.java  2s .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");
    }

}