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:org.activiti.designer.property.extension.field.CustomPropertyDataGridField.java

private void recreateDataGridControl() {

    if (dataGridControl != null) {
        dataGridControl.dispose();//from  w  w w . j  a  v  a 2  s. c o m
    }

    dataGridControl = factory.createFlatFormComposite(parent);

    if (gridFields == null && List.class.isAssignableFrom(getField().getType())) {

        gridFields = new ArrayList<FieldInfo>();

        dataGridAnnotation = getField().getAnnotation(DataGridProperty.class);
        if (dataGridAnnotation != null) {

            final Class<? extends Object> itemClass = dataGridAnnotation.itemClass();

            final Field[] itemClassDeclaredFields = itemClass.getDeclaredFields();

            for (final Field itemClassField : itemClassDeclaredFields) {
                if (itemClassField.isAnnotationPresent(Property.class)) {
                    try {
                        final FieldInfo info = new FieldInfo(itemClassField);
                        gridFields.add(info);
                    } catch (IllegalArgumentException e) {
                        // fail silently, field doesn't contain required info.
                    }
                }
            }

            // Sort the list
            Collections.sort(gridFields);
        }
    }

    // Set the layout for the contents of the listParent to a
    // grid
    int additionalColumns = DEFAULT_ADDITIONAL_COLUMNS;
    if (dataGridAnnotation.orderable()) {
        additionalColumns += ORDERABLE_ADDITIONAL_COLUMNS;
    }
    final GridLayout layout = new GridLayout(gridFields.size() + additionalColumns, false);
    dataGridControl.setLayout(layout);

    FormData dataGridData = new FormData();
    dataGridData.left = new FormAttachment();
    dataGridData.right = new FormAttachment(100);
    dataGridControl.setLayoutData(dataGridData);

}

From source file:at.alladin.rmbt.shared.hstoreparser.HstoreParser.java

/**
 * //from   w w w.  j a  v a  2s  .  c o m
 * @param hstore
 * @return
 * @throws HstoreParseException 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public T fromJson(JSONObject json) throws HstoreParseException {
    T object;
    try {
        object = constructor.newInstance();
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        throw new HstoreParseException(HstoreParseException.HSTORE_PARSE_EXCEPTION + e.getLocalizedMessage(),
                e);
    }

    if (object == null) {
        throw new HstoreParseException(
                HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName());
    }

    //iterate through all json entries:
    Iterator<String> jsonKeys = json.keys();
    while (jsonKeys.hasNext()) {
        String key = jsonKeys.next();

        //if fieldsWithKeys contain a key (=it was annotated with @HstoreKey) then try to set the value of the field in T object
        if (fieldsWithKeys.containsKey(key)) {
            final Field field = fieldsWithKeys.get(key);
            try {
                Object value = getFromJsonByField(json, key, field);
                field.setAccessible(true);
                //cast / new instance needed?
                if (field.isAnnotationPresent(HstoreCollection.class)) {
                    Class<?> fieldClazz = field.getType();
                    //System.out.println("FieldClazz: " + fieldClazz + " -> " + fieldClazz.isAssignableFrom(Collection.class));
                    if (Collection.class.isAssignableFrom(fieldClazz)) {
                        //get collection and instantiate if necessary
                        Collection collection = (Collection) field.get(object);
                        if (collection == null) {
                            collection = (Collection) fieldClazz.newInstance();
                        }

                        ParameterizedType fieldType = (ParameterizedType) field.getGenericType();
                        Class<?> genericClazz = (Class<?>) fieldType.getActualTypeArguments()[0];
                        //System.out.println("genericClazz: " + genericClazz);

                        //Object jsonObject = hstore.toJson((String) value, genericClazz);
                        Object jsonObject = null;
                        //System.out.println(value);
                        if (!value.equals(JSONObject.NULL)) {
                            if (value instanceof JSONArray || value instanceof JSONObject) {
                                jsonObject = hstore.toJson(value.toString(), genericClazz);
                            } else {
                                jsonObject = hstore.toJson((String) value, genericClazz);
                            }
                        } else {
                            jsonObject = hstore.toJson(null, genericClazz);
                        }

                        if (jsonObject != null) {
                            if (jsonObject instanceof JSONArray) {
                                //System.out.println(jsonObject);
                                Object[] array = hstore.fromJSONArray((JSONArray) jsonObject, genericClazz);
                                for (int i = 0; i < array.length; i++) {
                                    //System.out.println("Created element: " + array[i]);
                                    collection.add(array[i]);
                                }
                            } else {
                                Object element = hstore.fromString((String) value, genericClazz);
                                //System.out.println("Created element: " + element);
                                collection.add(element);
                            }
                        }

                        value = collection;
                    } else {
                        throw new HstoreParseException(HstoreParseException.HSTORE_MUST_BE_A_COLLECTION + field
                                + " - " + clazz.getCanonicalName());
                    }
                }

                if (field.isAnnotationPresent(HstoreCast.class)) {
                    HstoreCast castDef = field.getAnnotation(HstoreCast.class);
                    if (castDef.simpleCast()) {
                        //simple cast
                        field.set(object, castDef.clazz().cast(value));
                    } else {
                        //new instance
                        field.set(object, castDef.clazz().getConstructor(castDef.constructorParamClazz())
                                .newInstance(value));
                    }
                } else {
                    if (JSONObject.NULL.equals(value)) {
                        field.set(object, null);
                    } else {
                        field.set(object, parseFieldValue(field, value));
                    }
                }

            } catch (IllegalAccessException | IllegalArgumentException | JSONException e) {
                throw new HstoreParseException(
                        HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName(), e);
            } catch (InstantiationException e) {
                throw new HstoreParseException(
                        HstoreParseException.HSTORE_COULD_NOT_INSTANTIATE + clazz.getCanonicalName(), e);
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassCastException e) {
                System.out.println("field: " + field.toString() + ", key: " + key);
                e.printStackTrace();
            }
        }
    }

    return object;
}

From source file:com.quangphuong.crawler.dbutil.DBWrapper.java

public List<Object> getEntitiesByCondition(Object entity) {
    String sql = selectAll.concat(entity.getClass().getSimpleName());
    if (!"".equals(customWhereClause)) {
        sql = sql.concat(customWhereClause);
    } else {/*from   ww w . j a  v a  2  s  . c  o m*/
        sql = sql.concat(whereClause);
    }
    Connection con = null;
    if (this.isDisconnect) {
        con = DBHandler.openConnection();
    }
    List<Object> result = new ArrayList<Object>();
    try {
        Statement statement;
        if (this.isDisconnect) {
            statement = con.createStatement();
        } else {
            statement = connection.createStatement();
        }
        Field[] attributes = entity.getClass().getDeclaredFields();
        if ("".equals(customWhereClause)) {
            //                Field[] attributes = entity.getClass().getDeclaredFields();
            int count = 0;
            for (Field attribute : attributes) {
                attribute.setAccessible(true);
                if (!attribute.isAnnotationPresent(Ignore.class)
                        && !attribute.isAnnotationPresent(AutoIncrement.class)
                        && attribute.get(entity) != null) {
                    String value = attribute.get(entity).toString();

                    if (count == 0) {
                        sql = sql.concat(attribute.getName() + "=" + "\'" + value + "\'");
                    } else {
                        sql = sql.concat(" AND " + attribute.getName() + "=" + "\'" + value + "\'");
                    }
                    count++;
                }
            }
        }
        if (useDistinct) {
            sql = sql.concat(groupByClause.replace("@", distinctField));
        }
        System.out.println(sql);
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            List<Object> listFields = new ArrayList();
            List<Class<?>> listFieldTypes = new ArrayList();
            for (Field attribute : attributes) {
                attribute.setAccessible(true);
                if (!attribute.isAnnotationPresent(Ignore.class)) {
                    Object obj = resultSet.getObject(attribute.getName());
                    listFields.add(obj);
                    listFieldTypes.add(attribute.getType());
                }
            }
            Object obj = entity.getClass().getConstructor((Class<?>[]) listFieldTypes.toArray(new Class[0]))
                    .newInstance(listFields.toArray());
            result.add(obj);
        }
    } catch (Exception ex) {
        Logger.getLogger(DBWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (this.isDisconnect && con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:com.impetus.kundera.metadata.processor.relation.OneToManyRelationMetadataProcessor.java

@Override
public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata) {

    OneToMany ann = relationField.getAnnotation(OneToMany.class);
    Class<?> targetEntity = PropertyAccessorHelper.getGenericClass(relationField);

    // now, check annotations
    if (null != ann.targetEntity() && !ann.targetEntity().getSimpleName().equals("void")) {
        targetEntity = ann.targetEntity();
    }//w  w  w .j  a va 2  s .c o m

    Relation relation = new Relation(relationField, targetEntity, relationField.getType(), ann.fetch(),
            Arrays.asList(ann.cascade()), Boolean.TRUE, ann.mappedBy(), Relation.ForeignKey.ONE_TO_MANY);

    boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);

    if (isJoinedByFK) {
        JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);
        relation.setJoinColumnName(
                StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName() : joinColumnAnn.name());
    }

    else {
        String joinColumnName = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();
        if (relation.getMappedBy() != null) {
            try {
                Field mappedField = metadata.getEntityClazz().getDeclaredField(relation.getMappedBy());
                if (mappedField != null && mappedField.isAnnotationPresent(JoinColumn.class)) {
                    joinColumnName = mappedField.getAnnotation(JoinColumn.class).name();
                }
            } catch (NoSuchFieldException e) {
                // do nothing, it means not a case of self association
            } catch (SecurityException e) {
                // do nothing, it means not a case of self association
            }
        }
        relation.setJoinColumnName(joinColumnName);
    }

    relation.setBiDirectionalField(metadata.getEntityClazz());
    metadata.addRelation(relationField.getName(), relation);
    metadata.setParent(true);
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java

private List<String> getPropOrderUncached(Class<? extends Object> beanClass) {
    List<String> propOrder;

    // Superclass first!
    Class superclass = beanClass.getSuperclass();
    if (superclass.equals(Object.class) || superclass.getAnnotation(XmlType.class) == null) {
        propOrder = new ArrayList<>();
    } else {//from   ww  w.ja  va2s .c  om
        propOrder = new ArrayList<>(getPropOrder(superclass));
    }

    XmlType xmlType = beanClass.getAnnotation(XmlType.class);
    if (xmlType == null) {
        throw new IllegalArgumentException(
                "Cannot marshall " + beanClass + " it does not have @XmlType annotation");
    }

    String[] myPropOrder = xmlType.propOrder();
    if (myPropOrder != null) {
        for (String myProp : myPropOrder) {
            if (StringUtils.isNotBlank(myProp)) {
                // some properties starts with underscore..we don't want to serialize them with underscore, so remove it..
                if (myProp.startsWith("_")) {
                    myProp = myProp.replace("_", "");
                }
                propOrder.add(myProp);
            }
        }
    }

    Field[] fields = beanClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (field.isAnnotationPresent(XmlAttribute.class)) {
            propOrder.add(field.getName());
        }
    }

    Method[] methods = beanClass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.isAnnotationPresent(XmlAttribute.class)) {
            //            System.out.println("methodName: " + method.getName());
            String propname = getPropertyNameFromGetter(method.getName());
            //StringUtils.uncapitalize(StringUtils.removeStart("get", method.getName()))
            propOrder.add(propname);
        }
    }

    return propOrder;
}

From source file:com.quangphuong.crawler.dbutil.DBWrapper.java

public boolean updateEntity(Object entity) {
    String sql = updateClause.concat(entity.getClass().getSimpleName());
    Connection con = null;//from w w w  .  j  a v  a2  s . c  o m
    if (this.isDisconnect) {
        con = DBHandler.openConnection();
    }
    try {
        Statement statement;
        if (this.isDisconnect) {
            statement = con.createStatement();
        } else {
            statement = connection.createStatement();
        }
        String set = setClause;
        String where = whereClause;
        Field[] attributes = entity.getClass().getDeclaredFields();
        int count = 0;
        int idCount = 0;
        for (Field attribute : attributes) {
            attribute.setAccessible(true);
            if (attribute.get(entity) != null && !attribute.isAnnotationPresent(
                    Ignore.class)/* && !attribute.isAnnotationPresent(AutoIncrement.class) */) {
                String value = attribute.get(entity).toString();
                if (attribute.isAnnotationPresent(Id.class) /*|| attribute.isAnnotationPresent(Mark.class) */) {
                    if (idCount == 0) {
                        where = where.concat(attribute.getName() + "=" + "\'" + value + "\'");
                    } else {
                        where = where.concat(" AND " + attribute.getName() + "=" + "\'" + value + "\'");
                    }
                    idCount++;
                } else {
                    if (count == 0) {
                        set = set.concat(attribute.getName() + "=" + "\'" + value + "\'");
                    } else {
                        set = set.concat("," + attribute.getName() + "=" + "\'" + value + "\'");
                    }
                    count++;
                }
            }
        }

        sql = sql.concat(set + where);
        System.out.println(sql);
        int result = statement.executeUpdate(sql);
        if (result > 0) {
            return true;
        }
    } catch (Exception ex) {
        Logger.getLogger(DBWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (this.isDisconnect && con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

private void loadAllFields(Object object, Class<?> type) {
    for (Field field : type.getDeclaredFields()) {
        if (!field.isAnnotationPresent(Acomponent.class)) {
            continue;
        }//from   w  w  w  .  j a  v  a 2 s. c o  m

        field.setAccessible(true);

        Acomponent ac = field.getDeclaredAnnotation(Acomponent.class);

        if (field.getClass().getDeclaredFields().length > 0) {
            Object value;

            try {
                value = field.get(object);
                if (ac.type().equals(EnumComponentType.PANEL)) {
                    addTargets(value);
                    loadAllFields(value, field.getType());
                }

                mudarReferencia(field);
                addField(field);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                infoError(e);
                LogServer.getInstance().error(null,
                        "O <field> [{0}] est nulo!\nDialog foi iniciado de forma incompleta com falhas!",
                        field);
            }
        }
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

private boolean isAttributeUncached(Field field, Method getter) {
    if (field == null && getter == null) {
        return false;
    } else {/*from  w  ww.  j av  a2s .  co m*/
        return field != null && field.isAnnotationPresent(XmlAttribute.class)
                || getter != null && getter.isAnnotationPresent(XmlAttribute.class);
    }
}

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

protected void populateUserFieldMap() {

    Class<? extends AbstractFoundationLoggingMarker> clazz = this.getClass();
    Multiset<Field> fieldList = markerClassFields.get(clazz);

    if (fieldList == null) {

        fieldList = ConcurrentHashMultiset.create();

        Class<?> cls = clazz;

        while (AbstractFoundationLoggingMarker.class.isAssignableFrom(cls)) {
            Field[] declaredFields = cls.getDeclaredFields();

            for (Field field : declaredFields) {

                if (field.isAnnotationPresent(UserField.class)) {
                    field.setAccessible(true);
                    fieldList.add(field);
                }//from  w  w w .j  av  a 2  s  .  c  o  m
            }
            markerClassFields.put(clazz, fieldList);
            cls = cls.getSuperclass();
        }

    }

    for (Field field : fieldList) {

        try {

            Object value = field.get(this);

            UserField userField = field.getAnnotation(UserField.class);
            if (value == null && userField.suppressNull()) {
                value = FoundationLoggingMarker.NO_OPERATION;
            }
            userFields.put(field.getName(), value == null ? "null" : value);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }

}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java

private boolean isAttributeUncached(Field field, Method getter) {
    if (field == null && getter == null) {
        return false;
    }//from  w  w  w .j  a  v a 2 s  .  c o  m

    if (field != null && field.isAnnotationPresent(XmlAttribute.class)) {
        return true;
    }

    if (getter != null && getter.isAnnotationPresent(XmlAttribute.class)) {
        return true;
    }

    return false;
}