Example usage for java.lang.reflect Field isAnnotationPresent

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

Introduction

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

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.jsmartframework.web.manager.BeanHelper.java

void setAuthAccess(Class<?> clazz) {
    if (!authAccess.containsKey(clazz)) {
        List<Field> fields = new ArrayList<>();

        for (Field field : getBeanFields(clazz)) {
            if (!field.isAnnotationPresent(AuthAccess.class)) {
                continue;
            }//from   ww  w .  j  ava2s  .  co m
            fields.add(field);
        }
        authAccess.put(clazz, fields.toArray(new Field[fields.size()]));
    }
}

From source file:com.impetus.kundera.validation.rules.RelationAttributeRule.java

/**
 * @param relationField/*from w w  w  . j ava 2 s .  c om*/
 * @param annotate
 * @return
 * @throws RuleValidationException
 */
private Boolean validateManyToMany(Field relationField, Annotation annotate) throws RuleValidationException {
    ManyToMany m2mAnnotation = (ManyToMany) annotate;

    boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);
    boolean isJoinedByTable = relationField.isAnnotationPresent(JoinTable.class);
    boolean isJoinedByMap = false;
    if (m2mAnnotation != null && relationField.getType().isAssignableFrom(Map.class)) {
        isJoinedByMap = true;
    }

    Class<?> targetEntity = null;
    Class<?> mapKeyClass = null;

    if (!isJoinedByMap) {

        targetEntity = PropertyAccessorHelper.getGenericClass(relationField);
    } else {
        List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses(relationField);

        if (!genericClasses.isEmpty() && genericClasses.size() == 2) {
            mapKeyClass = genericClasses.get(0);
            targetEntity = genericClasses.get(1);
        }

        MapKeyClass mapKeyClassAnn = relationField.getAnnotation(MapKeyClass.class);

        // Check for Map key class specified at annotation
        if (mapKeyClass == null && mapKeyClassAnn != null && mapKeyClassAnn.value() != null
                && !mapKeyClassAnn.value().getSimpleName().equals("void")) {
            mapKeyClass = mapKeyClassAnn.value();
        }

        if (mapKeyClass == null) {
            throw new InvalidEntityDefinitionException("For a Map relationship field,"
                    + " it is mandatory to specify Map key class either using @MapKeyClass annotation or through generics");
        }

    }

    // Check for target class specified at annotation
    if (targetEntity == null && null != m2mAnnotation.targetEntity()
            && !m2mAnnotation.targetEntity().getSimpleName().equals("void")) {
        targetEntity = m2mAnnotation.targetEntity();
    }
    //check if target entity is null
    if (targetEntity == null) {
        throw new InvalidEntityDefinitionException("Could not determine target entity class for relationship."
                + " It should either be specified using targetEntity attribute of @ManyToMany or through generics");
    }
    //check if joined by foreign key
    if (isJoinedByFK) {
        throw new InvalidEntityDefinitionException(
                "@JoinColumn not allowed for ManyToMany relationship. Use @JoinTable instead");

    }
    //check if joined by foreign key and join column name is set
    if (isJoinedByMap) {

        MapKeyJoinColumn mapKeyJoinColumnAnn = relationField.getAnnotation(MapKeyJoinColumn.class);
        if (mapKeyJoinColumnAnn != null) {
            String mapKeyJoinColumnName = mapKeyJoinColumnAnn.name();
            if (StringUtils.isEmpty(mapKeyJoinColumnName)) {
                throw new InvalidEntityDefinitionException(
                        "It's mandatory to specify name attribute with @MapKeyJoinColumn annotation");
            }
        }

    }
    //check if not joined by table in many to many
    if (!isJoinedByTable && !isJoinedByMap
            && (m2mAnnotation.mappedBy() == null || m2mAnnotation.mappedBy().isEmpty())) {
        throw new InvalidEntityDefinitionException(
                "It's manadatory to use @JoinTable with parent side of ManyToMany relationship.");
    }
    return true;
}

From source file:net.minecraftforge.common.config.FieldWrapper.java

public FieldWrapper(String category, Field field, Object instance) {
    this.instance = instance;
    this.field = field;
    this.category = category;
    this.name = field.getName();

    if (field.isAnnotationPresent(Config.Name.class))
        this.name = field.getAnnotation(Config.Name.class).value();

    this.field.setAccessible(true); // Just in case
}

From source file:com.ibm.amc.data.validation.ValidationEngine.java

private void validate(Field field, Object resource) throws InvalidDataException {
    boolean validated = false;

    // Call the getter to get the value to validate.
    Object value = invoke(field, resource);

    if (field.isAnnotationPresent(ValidateNotBlank.class)) {
        boolean valid = new ValidateNotBlank.NotBlankValidator().validate(value, null);

        // Note we don't set validated as true for this - non-blank isn't enough to ensure
        // safety.

        if (!valid)
            throw new InvalidDataException(field.getName());
    }//from   ww  w.j a  va2 s .c  om

    if (field.isAnnotationPresent(ValidateNotNull.class)) {
        boolean valid = new ValidateNotNull.NotNullValidator().validate(value, null);

        // Note we don't set validated as true for this - non-null isn't enough to ensure
        // safety.

        if (!valid)
            throw new InvalidDataException(field.getName());
    }

    /* only perform further validation if the value isn't null */
    if (value != null) {
        if (field.isAnnotationPresent(ValidCharacters.class)) {
            ValidCharacters constraints = field.getAnnotation(ValidCharacters.class);
            boolean valid = new ValidCharacters.ValidCharacterValidator().validate(value, constraints);
            validated = true;

            if (!valid)
                throw new InvalidDataException(field.getName());
        }

        if (field.isAnnotationPresent(ValidNumber.class)) {
            ValidNumber constraints = field.getAnnotation(ValidNumber.class);
            boolean valid = new ValidNumber.NumberValidator().validate(value, constraints);
            validated = true;

            if (!valid)
                throw new InvalidDataException(field.getName());
        }

        if (field.isAnnotationPresent(ValidLength.class)) {
            ValidLength constraints = field.getAnnotation(ValidLength.class);
            boolean valid = new ValidLength.ValidLengthValidator().validate(value, constraints);
            validated = true;

            if (!valid)
                throw new InvalidDataException(field.getName());
        }

        if (field.isAnnotationPresent(ValidRegex.class)) {
            ValidRegex constraints = field.getAnnotation(ValidRegex.class);
            boolean valid = new ValidRegex.RegexValidator().validate(value, constraints);
            validated = true;

            if (!valid)
                throw new InvalidDataException(field.getName());
        }

        if (field.isAnnotationPresent(ValidUri.class)) {
            ValidUri constraints = field.getAnnotation(ValidUri.class);
            boolean valid = new ValidUri.ValidUriValidator().validate(value, constraints);
            validated = true;

            if (!valid)
                throw new InvalidDataException(field.getName());
        }

        if (field.isAnnotationPresent(ValidUrl.class)) {
            ValidUrl constraints = field.getAnnotation(ValidUrl.class);
            boolean valid = new ValidUrl.ValidUrlValidator().validate(value, constraints);
            validated = true;

            if (!valid)
                throw new InvalidDataException(field.getName());
        }

        if (field.isAnnotationPresent(ValidatedAs.class)) {
            boolean valid = false;
            Class<? extends Validator> validatorClass = field.getAnnotation(ValidatedAs.class).value();
            try {
                valid = validatorClass.newInstance().validate(value, null);
                validated = true;
            } catch (IllegalAccessException e) {
                // Should never happen, unless we start using complex access control stuff in
                // which case proper handling should be added.
                logger.debug("invoke", "IllegalAccessException instantiating a validator", e);
                // Fall through and treat the data as invalid.
            } catch (InstantiationException e) {
                // Should never happen, because we only instantiate Validators, which aren't
                // susceptible to this.
                logger.debug("invoke", "InstantiationException instantiating a validator", e);
                // Fall through and treat the data as invalid.
            }

            if (!valid)
                throw new InvalidDataException(field.getName());
        }

        if (!validated) {
            doGenericValidation(value, field.getName());
        }
    }
}

From source file:net.redwarp.library.database.TableInfo.java

@SuppressWarnings("unchecked")
private TableInfo(Class<T> c) {
    mClass = c;//from   w  w w  . j av a  2 s . c o  m

    if (c.isAnnotationPresent(Version.class)) {
        final Version version = c.getAnnotation(Version.class);
        mVersion = version.value();
    } else {
        mVersion = 1;
    }

    Field[] fields = mClass.getDeclaredFields();
    //        mFieldMap = new HashMap<>(fields.length);
    mColumns = new HashMap<>(fields.length);
    mObjectFields = new ArrayList<>();

    List<String> columnNames = new ArrayList<>(fields.length);
    List<Field> finalFields = new ArrayList<>(fields.length);
    List<Field> chainDeleteFields = new ArrayList<>(fields.length);

    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            SQLiteUtils.SQLiteType type = SQLiteUtils.getSqlLiteTypeForField(field);
            if (type != null) {
                field.setAccessible(true);
                if (field.isAnnotationPresent(PrimaryKey.class)) {
                    if (primaryKey != null) {
                        throw new RuntimeException("There can be only one primary key");
                    }
                    final PrimaryKey primaryKeyAnnotation = field.getAnnotation(PrimaryKey.class);
                    String name = primaryKeyAnnotation.name();
                    if ("".equals(name)) {
                        name = getColumnName(field);
                    }
                    columnNames.add(name);
                    primaryKey = new Column(name, field, SQLiteUtils.SQLiteType.INTEGER);
                } else {
                    final String name = getColumnName(field);
                    columnNames.add(name);
                    mColumns.put(field, new Column(name, field, type));
                }

                finalFields.add(field);
            } else {
                // Not a basic field;
                if (field.isAnnotationPresent(Chain.class)) {
                    // We must serialize/unserialize this as well
                    final Chain chainAnnotation = field.getAnnotation(Chain.class);
                    if (chainAnnotation.delete()) {
                        chainDeleteFields.add(field);
                    }
                    final String name = getColumnName(field);
                    columnNames.add(name);
                    Column column = new Column(name, field, SQLiteUtils.SQLiteType.INTEGER);
                    mColumns.put(field, column);
                    mObjectFields.add(field);
                    finalFields.add(field);
                }
            }
        }
    }
    mColumnNames = columnNames.toArray(new String[columnNames.size()]);
    mFields = finalFields.toArray(new Field[finalFields.size()]);
    mChainDeleteFields = chainDeleteFields.toArray(new Field[chainDeleteFields.size()]);
}

From source file:br.gov.frameworkdemoiselle.internal.configuration.ConfigurationLoader.java

private String getKey(final Field field, final Class<?> clazz,
        final org.apache.commons.configuration.Configuration config) {

    final String prefix = getPrefix(field, clazz);
    final StringBuffer key = new StringBuffer();

    key.append(prefix);//from w w  w  .jav a2 s. c o m

    if (field.isAnnotationPresent(Name.class)) {
        key.append(getKeyByAnnotation(field));
    } else {
        key.append(getKeyByConvention(field, prefix, config));
    }

    return key.toString();
}

From source file:com.impetus.kundera.metadata.MetadataManager.java

/**
 * Helper class to scan each @Entity class and build various relational annotation.
 * // w  ww.  j  a  v  a 2  s .  c  o  m
 * @param entity
 *            the entity
 */
private void processRelations(Class<?> entity) {
    EntityMetadata metadata = getEntityMetadata(entity);

    for (Field f : entity.getDeclaredFields()) {

        // OneToOne
        if (f.isAnnotationPresent(OneToOne.class)) {
            // taking field's type as foreign entity, ignoring
            // "targetEntity"
            Class<?> targetEntity = f.getType();
            try {
                validate(targetEntity);
                OneToOne ann = f.getAnnotation(OneToOne.class);

                Relation relation = metadata.new Relation(f, targetEntity, null, ann.fetch(),
                        Arrays.asList(ann.cascade()), ann.optional(), ann.mappedBy(),
                        EntityMetadata.ForeignKey.ONE_TO_ONE);

                metadata.addRelation(f.getName(), relation);
            } catch (PersistenceException pe) {
                throw new PersistenceException("Error with @OneToOne in @Entity(" + entity.getName() + "."
                        + f.getName() + "), reason: " + pe.getMessage());
            }
        }

        // OneToMany
        else if (f.isAnnotationPresent(OneToMany.class)) {

            OneToMany ann = f.getAnnotation(OneToMany.class);

            Class<?> targetEntity = null;

            // resolve from generic parameters
            Type[] parameters = ReflectUtils.getTypeArguments(f);
            if (parameters != null) {
                if (parameters.length == 1) {
                    targetEntity = (Class<?>) parameters[0];
                } else {
                    throw new PersistenceException("How many parameters man?");
                }
            }
            // now, check annotations
            if (null != ann.targetEntity() && !ann.targetEntity().getSimpleName().equals("void")) {
                targetEntity = ann.targetEntity();
            }

            try {
                validate(targetEntity);
                Relation relation = metadata.new Relation(f, targetEntity, f.getType(), ann.fetch(),
                        Arrays.asList(ann.cascade()), Boolean.TRUE, ann.mappedBy(),
                        EntityMetadata.ForeignKey.ONE_TO_MANY);

                metadata.addRelation(f.getName(), relation);
            } catch (PersistenceException pe) {
                throw new PersistenceException("Error with @OneToMany in @Entity(" + entity.getName() + "."
                        + f.getName() + "), reason: " + pe.getMessage());
            }
        }

        // ManyToOne
        else if (f.isAnnotationPresent(ManyToOne.class)) {
            // taking field's type as foreign entity, ignoring
            // "targetEntity"
            Class<?> targetEntity = f.getType();
            try {
                validate(targetEntity);
                ManyToOne ann = f.getAnnotation(ManyToOne.class);

                Relation relation = metadata.new Relation(f, targetEntity, null, ann.fetch(),
                        Arrays.asList(ann.cascade()), ann.optional(), null, // mappedBy is null
                        EntityMetadata.ForeignKey.MANY_TO_ONE);

                metadata.addRelation(f.getName(), relation);
            } catch (PersistenceException pe) {
                throw new PersistenceException("Error with @OneToOne in @Entity(" + entity.getName() + "."
                        + f.getName() + "), reason: " + pe.getMessage());
            }
        }

        // ManyToMany
        else if (f.isAnnotationPresent(ManyToMany.class)) {

            ManyToMany ann = f.getAnnotation(ManyToMany.class);

            Class<?> targetEntity = null;

            // resolve from generic parameters
            Type[] parameters = ReflectUtils.getTypeArguments(f);
            if (parameters != null) {
                if (parameters.length == 1) {
                    targetEntity = (Class<?>) parameters[0];
                } else {
                    throw new PersistenceException("How many parameters man?");
                }
            }
            // now, check annotations
            if (null != ann.targetEntity() && !ann.targetEntity().getSimpleName().equals("void")) {
                targetEntity = ann.targetEntity();
            }

            try {
                validate(targetEntity);
                Relation relation = metadata.new Relation(f, targetEntity, f.getType(), ann.fetch(),
                        Arrays.asList(ann.cascade()), Boolean.TRUE, ann.mappedBy(),
                        EntityMetadata.ForeignKey.MANY_TO_MANY);

                metadata.addRelation(f.getName(), relation);
            } catch (PersistenceException pe) {
                throw new PersistenceException("Error with @OneToMany in @Entity(" + entity.getName() + "."
                        + f.getName() + "), reason: " + pe.getMessage());
            }
        }

    }
}

From source file:me.ronghai.sa.dao.impl.AbstractModelDAOWithJDBCImpl.java

private List<?>[] findColumnsAndValues(boolean excludeId, E entity) {

    List<String> columnNames = new ArrayList<>();
    List<Object> values = new ArrayList<>();

    Map<String, Field> columnFields = entity.modelMeta().getColumnFields();
    Map<String, Method> field2Getter = entity.modelMeta().getField2Getter();

    for (Map.Entry<String, Field> entry : columnFields.entrySet()) {
        Field field = entry.getValue();
        if (excludeId && field.isAnnotationPresent(Id.class)) {
            continue;
        }/*from  w w  w .ja v a 2s  .c  o  m*/
        String cname = entry.getKey();
        Object value = null;
        try {
            value = field2Getter.get(field.getName()).invoke(entity);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                | NullPointerException e) {
            logger.log(Level.WARNING, "filed is {0}  ", field);
            logger.log(Level.WARNING, "{0}", e);
        }
        Column annotation = field.isAnnotationPresent(Column.class) ? (Column) field.getAnnotation(Column.class)
                : null;
        if (annotation != null && value == null && !annotation.nullable()) {
            logger.log(Level.SEVERE, "{0}", cname + " is not null. ");
            return null;
        } else if (value != null) {
            columnNames.add(cname);
            values.add(value);
        }
    }

    /*
            
     List<Field> allFieldList =  ReflectUtils.getDeclaredFields((List<Field>)null, entityClass, false);
     Map<String, PropertyDescriptor> fieldName2PropertyDescriptor =  ReflectUtils.findFieldName2PropertyDescriptor(entityClass);    
            
     for ( Field field : allFieldList) {
     if (field.isAnnotationPresent(Column.class) && !field.isAnnotationPresent(Id.class)) {
     Column annotation = field.isAnnotationPresent(Column.class) ?  (Column) field.getAnnotation(Column.class) : null;
     String cname;
     if(annotation  != null && org.apache.commons.lang.StringUtils.isNotEmpty(annotation.name())){
     cname = annotation.name();
     cname = cname.replaceAll("[\\[\\]]", "`");
     }else{
     cname = field.getName();
     }
     Method getter = ReflectUtils.findGetter(entity, field, fieldName2PropertyDescriptor, null);
     try {
     Object value =  getter.invoke(entity);
     if(value == null && annotation != null && !annotation.nullable()){
     logger.log(Level.SEVERE, "{0}",  cname + " is not null. ");
     return null;
     }else if(value != null){
     columnNames.add(cname);
     values.add(value);
     }
     }catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { 
     if(annotation != null && !annotation.nullable()){
     logger.log(Level.SEVERE, "{0}", ex);
     return null;
     }else{
     logger.log(Level.WARNING, "{0}", ex);
     }
     }
     }
     }
     */
    return new List[] { columnNames, values };
}

From source file:com.blackberry.bdp.common.versioned.ZkVersioned.java

public final void reload(ZkVersioned newVersion)
        throws IllegalArgumentException, IllegalAccessException, ComparableClassMismatchException {

    if (!this.getClass().equals(newVersion.getClass())) {
        throw new ComparableClassMismatchException(String.format("Versioned class %s cannot be compared to %s",
                this.getClass(), newVersion.getClass()));
    }//from w w  w .  j av a2 s  .c o m

    if (this.getVersion() >= newVersion.getVersion()) {
        return;
    }

    for (Field myField : this.getClass().getDeclaredFields()) {
        if (!myField.isAnnotationPresent(JsonIgnore.class)) {
            if (!myField.get(this).equals(myField.get(newVersion))) {
                // Field mis-match, inherit the new version's value                  
                LOG.info("Assigning {}.{}={} (old version: {}, old value: {}, new version {}",
                        this.getClass().getName(), myField.getName(), myField.get(newVersion),
                        this.getVersion(), myField.get(this), newVersion.getVersion());
                myField.set(this, myField.get(newVersion));
            }
        }
    }
}

From source file:org.jdbcluster.domain.DomainCheckerImpl.java

/**
 * inersect all domain values with user rights if the richts are not
 * sufficient, the values will be removed
 * /*  ww  w. j a  v  a 2s. c o  m*/
 * @param vde the list of domain values
 * @param domainId the domain id
 * @return
 */
ValidDomainEntries<String> rightsIntersection(IUser user, ValidDomainEntries<String> vde, String domainId,
        Field f) {
    if (f.isAnnotationPresent(PrivilegesDomain.class)) {
        PrivilegeChecker pc = PrivilegeCheckerImpl.getInstance();
        ArrayList<String> al = new ArrayList<String>();
        for (String value : vde) {
            if (!pc.userPrivilegeIntersectDomain(user, domainId, value))
                al.add(value);
        }
        vde.removeAll(al);
    }
    return vde;
}