Example usage for java.lang.reflect Field getDeclaredAnnotations

List of usage examples for java.lang.reflect Field getDeclaredAnnotations

Introduction

In this page you can find the example usage for java.lang.reflect Field getDeclaredAnnotations.

Prototype

public Annotation[] getDeclaredAnnotations() 

Source Link

Usage

From source file:com.odoo.core.orm.OModel.java

private boolean compatibleField(Field field) {
    if (mOdooVersion != null) {
        Annotation[] annotations = field.getDeclaredAnnotations();
        if (annotations.length > 0) {
            int version = 0;
            for (Annotation annotation : annotations) {
                // Check for odoo api annotation
                Class<? extends Annotation> type = annotation.annotationType();
                if (type.getDeclaringClass().isAssignableFrom(Odoo.api.class)) {
                    switch (mOdooVersion.getVersion_number()) {
                    case 9:
                        if (type.isAssignableFrom(Odoo.api.v9alpha.class)) {
                            version++;/*  www  .  j a  va 2  s.c o m*/
                        }
                        break;
                    case 8:
                        if (type.isAssignableFrom(Odoo.api.v8.class)) {
                            version++;
                        }
                        break;
                    case 7:
                        if (type.isAssignableFrom(Odoo.api.v7.class)) {
                            version++;
                        }
                        break;
                    }
                }
                // Check for functional annotation
                if (type.isAssignableFrom(Odoo.Functional.class) || type.isAssignableFrom(Odoo.onChange.class)
                        || type.isAssignableFrom(Odoo.hasDomainFilter.class)) {
                    version++;
                }
            }
            return (version > 0) ? true : false;
        }
        return true;
    }
    return false;
}

From source file:org.kuali.rice.krad.data.provider.annotation.impl.AnnotationMetadataProviderImpl.java

/**
 * Handle annotations made at the field level and add their data to the given metadata object.
  *//from   w  w  w  .j  a  v a2  s  .  co  m
 * @param clazz the class to process.
  * @param metadata the metadata for the class.
 * @return <b>true</b> if any annotations are found.
 */
protected boolean processFieldLevelAnnotations(Class<?> clazz, DataObjectMetadataImpl metadata) {
    boolean fieldAnnotationsFound = false;
    boolean additionalClassAnnotationsFound = false;
    List<DataObjectAttribute> attributes = new ArrayList<DataObjectAttribute>();
    for (Field f : clazz.getDeclaredFields()) {
        boolean fieldAnnotationFound = false;
        String propertyName = f.getName();
        DataObjectAttributeImpl attr = (DataObjectAttributeImpl) metadata.getAttribute(propertyName);
        boolean existingAttribute = attr != null;
        if (!existingAttribute) {
            attr = new DataObjectAttributeImpl();
            attr.setName(propertyName);
            attr.setType(f.getType());
            DataType dataType = DataType.getDataTypeFromClass(f.getType());
            if (dataType == null) {
                dataType = DataType.STRING;
            }
            attr.setDataType(dataType);
            attr.setOwningType(metadata.getType());
        }
        Annotation[] fieldAnnotations = f.getDeclaredAnnotations();
        if (LOG.isDebugEnabled()) {
            LOG.debug(f.getDeclaringClass() + "." + f.getName() + " Field-level annotations: "
                    + Arrays.asList(fieldAnnotations));
        }
        for (Annotation a : fieldAnnotations) {
            // check if it's one we can handle then do something with it
            fieldAnnotationFound |= processAnnotationForAttribute(a, attr, metadata);
            if (!fieldAnnotationFound) {
                if (a instanceof BusinessKey) {
                    ArrayList<String> businessKeys = new ArrayList<String>(
                            metadata.getBusinessKeyAttributeNames());
                    businessKeys.add(f.getName());
                    metadata.setBusinessKeyAttributeNames(businessKeys);
                    // We are not altering the field definition, so dont set the flag
                    // fieldAnnotationFound = true;
                    additionalClassAnnotationsFound = true;
                    continue;
                }
                if (a instanceof Relationship) {
                    addDataObjectRelationship(metadata, f, (Relationship) a);

                    additionalClassAnnotationsFound = true;
                    continue;
                }
                if (a instanceof CollectionRelationship) {
                    addDataObjectCollection(metadata, f, (CollectionRelationship) a);

                    additionalClassAnnotationsFound = true;
                    continue;
                }
            }
        }
        if (fieldAnnotationFound) {
            attributes.add(attr);
            fieldAnnotationsFound = true;
        }
    }
    if (fieldAnnotationsFound) {
        metadata.setAttributes(attributes);
    }
    return fieldAnnotationsFound || additionalClassAnnotationsFound;
}

From source file:com.adaptris.core.runtime.AdapterRegistry.java

@Override
public String getClassDefinition(String className) throws CoreException {
    final ClassDescriptor classDescriptor = new ClassDescriptor(className);
    try {/*from  w w  w. jav a 2 s .c  o  m*/
        Class<?> clazz = Class.forName(className);

        classDescriptor.setClassType(ClassDescriptor.ClassType.getTypeForClass(clazz).name().toLowerCase());

        List<String> displayOrder = new ArrayList<>();
        for (Annotation annotation : clazz.getAnnotations()) {
            if (XStreamAlias.class.isAssignableFrom(annotation.annotationType())) {
                classDescriptor.setAlias(((XStreamAlias) annotation).value());
            } else if (ComponentProfile.class.isAssignableFrom(annotation.annotationType())) {
                classDescriptor.setTags(((ComponentProfile) annotation).tag());
                classDescriptor.setSummary(((ComponentProfile) annotation).summary());
            } else if (DisplayOrder.class.isAssignableFrom(annotation.annotationType())) {
                displayOrder = Arrays.asList(((DisplayOrder) annotation).order());
            }
        }

        for (Field field : clazz.getDeclaredFields()) {
            if ((!Modifier.isStatic(field.getModifiers()))
                    && (field.getDeclaredAnnotation(Transient.class) == null)) { // if we're not transient
                ClassDescriptorProperty fieldProperty = new ClassDescriptorProperty();
                fieldProperty.setOrder(
                        displayOrder.contains(field.getName()) ? displayOrder.indexOf(field.getName()) + 1
                                : 999);
                fieldProperty.setAdvanced(false);
                fieldProperty.setClassName(field.getType().getName());
                fieldProperty.setType(field.getType().getSimpleName());
                fieldProperty.setName(field.getName());
                fieldProperty.setAutoPopulated(field.getDeclaredAnnotation(AutoPopulated.class) != null);
                fieldProperty.setNullAllowed(field.getDeclaredAnnotation(NotNull.class) != null);

                for (Annotation annotation : field.getDeclaredAnnotations()) {
                    if (AdvancedConfig.class.isAssignableFrom(annotation.annotationType())) {
                        fieldProperty.setAdvanced(true);
                    } else if (InputFieldDefault.class.isAssignableFrom(annotation.annotationType())) {
                        fieldProperty.setDefaultValue(((InputFieldDefault) annotation).value());
                    }
                }
                classDescriptor.getClassDescriptorProperties().add(fieldProperty);
            }
        }

        try (ScanResult result = new ClassGraph().enableAllInfo().blacklistPackages(FCS_BLACKLIST).scan()) {

            List<String> subclassNames = result.getSubclasses(className).getNames();

            for (String subclassName : subclassNames) {
                classDescriptor.getSubTypes().add(subclassName);
            }
        }

    } catch (ClassNotFoundException e) {
        throw new CoreException(e);
    }
    return new XStreamJsonMarshaller().marshal(classDescriptor);
}

From source file:org.dasein.persist.PersistentCache.java

protected final void initBase(@Nonnull Class<? extends CachedItem> c, @Nullable String entity,
        @Nonnull String version, @Nullable SchemaMapper[] mappers, @Nonnull Key primaryKey,
        @Nullable Key... keys) {//from   w  ww  . j a va  2 s  .c o  m
    @SuppressWarnings("unchecked")
    Class<T> cls = (Class<T>) c;

    schemaMappers = (mappers == null ? new SchemaMapper[0] : mappers);
    schemaVersion = version;
    entityName = ((entity == null || entity.length() < 1) ? null : entity);
    this.primaryKey = primaryKey;
    if (keys != null && keys.length > 0) {
        secondaryKeys = Arrays.copyOf(keys, keys.length);
    } else {
        secondaryKeys = new Key[0];
    }
    cache = new ConcurrentMultiCache<T>(cls, primaryKey.getFields()[0]);

    init(cls, keys);
    Class<?> current = cls;

    while (!current.getName().equals(Object.class.getName())) {
        for (Field field : current.getDeclaredFields()) {
            for (Annotation annotation : field.getDeclaredAnnotations()) {
                if (annotation instanceof Lookup) {
                    Class<? extends LookupDelegate> delegate = ((Lookup) annotation).delegate();

                    if (delegate != null) {
                        try {
                            lookups.put(field.getName(), delegate.newInstance());
                        } catch (Throwable t) {
                            logger.error(t.getMessage(), t);
                        }
                    }
                }
            }
        }
        current = current.getSuperclass();
    }
}

From source file:org.alfresco.po.PageElement.java

/**
 * Waits for given {@link ElementState} of all render elements when rendering a page.
 * If the given element not reach element state, it will time out and throw {@link TimeoutException}. 
 * If operation to find all elements times out a {@link PageRenderTimeException} is thrown
 * Renderable elements will be scanned from class using {@link RenderWebElement} annotation.
 *
 * @param renderTime render timer/*from w w w.j  a v a 2s  . c  om*/
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
public void webElementRender(RenderTime renderTime) {
    if (renderTime == null) {
        throw new UnsupportedOperationException("RenderTime is required");
    }
    List<RenderElement> elements = new ArrayList<RenderElement>();
    Field[] fields = this.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(RenderWebElement.class)) {
            Class<?> type = field.getType();
            field.setAccessible(true);
            Object fieldVal = null;
            try {
                fieldVal = field.get(this);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                logger.error("Unable to set field", e);
            }

            //Handle page elements, extracts the @FindBy from the component.
            if (PageElement.class.isAssignableFrom(type)) {
                Annotation a = type.getAnnotation(FindBy.class);
                if (a != null) {
                    try {
                        By by = buildFromFindBy((FindBy) a);
                        elements.add(new RenderElement(by, ElementState.VISIBLE));
                    } catch (Exception ex) {
                    }
                }
            }
            if (type.equals(By.class)) {
                /*FIXME Below is the old way which we need to remove and use the web element instead.
                 *This is kept until we refactor the sharepo to use webelement instead of
                 *By.class. 
                 * @RenderWebelement By css = By.cssSelector("div.t");
                 * to 
                 * @RenderWebelement WebElement css;
                 * 
                 */
                RenderWebElement webElement = (RenderWebElement) field.getAnnotation(RenderWebElement.class);
                elements.add(new RenderElement((By) fieldVal, webElement.state()));
            } else {
                Annotation[] list = field.getDeclaredAnnotations();
                By by = null;
                for (Annotation a : list) {
                    if (a instanceof FindBy) {
                        by = extractSelector((FindBy) a);
                    }
                }
                if (by != null) {
                    elements.add(new RenderElement(by, ElementState.VISIBLE));
                }
            }
        }
    }
    if (!elements.isEmpty()) {
        elementRender(renderTime, elements.toArray(new RenderElement[elements.size()]));
    }
}

From source file:org.finra.dm.dao.impl.DmDaoImpl.java

/**
 * Updates the audit fields if the entity is of type AuditableEntity.
 *
 * @param entity the entity/*  w  w  w  .j  a  v a2 s.c  o m*/
 * @param <T> the type of entity
 */
@SuppressWarnings("rawtypes")
private <T> void updateAuditFields(T entity) {
    if (entity instanceof AuditableEntity) {
        AuditableEntity auditableEntity = (AuditableEntity) entity;

        // Get the currently logged in username.
        String username = dmDaoSecurityHelper.getCurrentUsername();

        // Always set the updated by field, but only set the created by field when it is null (i.e. this is a new record).
        if (auditableEntity.getCreatedBy() == null) {
            auditableEntity.setCreatedBy(username);
        }
        auditableEntity.setUpdatedBy(username);

        // Always set the updated on field to the current time, but only update the created on field when it is null (i.e. the first time).
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        auditableEntity.setUpdatedOn(currentTime);
        if (auditableEntity.getCreatedOn() == null) {
            auditableEntity.setCreatedOn(currentTime);
        }
    }

    // Try to update children one-to-many cascadable auditable entities.
    // Note that this assumes that OneToMany annotations are done on the field (as opposed to the method) and that all OneToMany fields are collections.
    // This approach also assumes that there are loops where children refer back to our entity (i.e. an infinite loop).
    // If there are other scenarios, we should modify this code to handle them.

    // Loop through all the fields of this entity.
    for (Field field : entity.getClass().getDeclaredFields()) {
        // Get all the annotations for the field.
        for (Annotation annotation : field.getDeclaredAnnotations()) {
            // Only look for OneToMany that cascade with "persist" or "merge".
            if (annotation instanceof OneToMany) {
                OneToMany oneToManyAnnotation = (OneToMany) annotation;
                List<CascadeType> cascadeTypes = new ArrayList<>(Arrays.asList(oneToManyAnnotation.cascade()));
                if ((cascadeTypes.contains(CascadeType.ALL)) || (cascadeTypes.contains(CascadeType.PERSIST))
                        || cascadeTypes.contains(CascadeType.MERGE)) {
                    try {
                        // Modify the accessibility to true so we can get the field (even if it's private) and get the value of the field for our entity.
                        field.setAccessible(true);
                        Object fieldValue = field.get(entity);

                        // If the field is a collection (which OneToMany annotated fields should be), then iterate through the collection and look for
                        // child auditable entities.
                        if (fieldValue instanceof Collection) {
                            Collection collection = (Collection) fieldValue;
                            for (Object object : collection) {
                                if (object instanceof AuditableEntity) {
                                    // We found a child auditable entity so recurse to update it's audit fields as well.
                                    updateAuditFields(object);
                                }
                            }
                        }
                    } catch (IllegalAccessException ex) {
                        // Because we're setting accessible to true above, we shouldn't get here.
                        throw new IllegalStateException("Unable to get field value for field \""
                                + field.getName() + "\" due to access restriction.", ex);
                    }
                }
            }
        }
    }
}