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:jdao.JDAO.java

public static <T> Map<String, Object> extractColsFromBean(Object _bean, Class<T> _beanClazz,
        boolean _inclIdField) {
    Map<String, Object> _ret = new HashMap();
    List<Field> fields = FieldUtils.getFieldsListWithAnnotation(_beanClazz, IBeanField.class);
    for (Field field : fields) {
        try {/*from w  w  w. ja v  a2s.  c  o m*/
            if (_inclIdField || (!field.isAnnotationPresent(IBeanID.class))) {
                String _key = field.getAnnotation(IBeanField.class).value();
                Object _val = FieldUtils.readField(field, _bean, true);
                _ret.put(_key, _val);
            }
        } catch (IllegalAccessException e) {
            // IGNORE
        }
    }
    return _ret;
}

From source file:com.sxj.mybatis.orm.builder.GenericStatementBuilder.java

private SqlNode getUpdateColumns() {
    List<SqlNode> contents = new ArrayList<SqlNode>();
    for (Field field : columnFields) {
        List<SqlNode> sqlNodes = new ArrayList<SqlNode>();

        if (Date.class.isAssignableFrom(field.getType()) && field.getAnnotation(Column.class) != null
                && field.getAnnotation(Column.class).sysdate() == true) {
            sqlNodes.add(new TextSqlNode(getColumnNameByField(field) + " = now(),"));
        } else if (!field.isAnnotationPresent(Version.class)) {
            sqlNodes.add(new TextSqlNode(getColumnNameByField(field) + " = #{" + field.getName() + "},"));
        }//from  ww w  .  j  av a2  s  .  com

        contents.add(new IfSqlNode(new MixedSqlNode(sqlNodes), getTestByField(null, field)));
    }
    if (versionField != null) {
        contents.add(new TextSqlNode(
                getColumnNameByField(versionField) + "=" + getColumnNameByField(versionField) + "+1"));
    }

    return new SetSqlNode(configuration, new MixedSqlNode(contents));
}

From source file:py.una.pol.karaku.reports.DynamicUtils.java

/**
 * Verifica el pattern que se debe aplicar a la columna
 * //  w ww.  j  ava2  s.co  m
 * <li>Si es del tipo {@link Date} se verifica el tipo que se encuentra
 * asociada a la anotacion {@link Time} para establecer el pattern a
 * utilizar.
 * 
 * @param field
 */
protected String getPattern(Field field) {

    if (Date.class.isAssignableFrom(field.getType())) {
        if (field.isAnnotationPresent(Time.class)) {
            switch (field.getAnnotation(Time.class).type()) {
            case DATE:
                return fp.getDateFormat();
            case DATETIME:
                return fp.getDateTimeFormat();
            case TIME:
                return fp.getTimeFormat();
            default:
                break;
            }
        } else {
            return fp.getDateFormat();
        }
    }
    return null;
}

From source file:net.kamhon.ieagle.dao.HibernateDao.java

private QueryParams translateExampleToQueryParams(Object example, String... orderBy) {
    Object newObj = example;//w  w w.  jav a  2  s. co m
    Entity className = ((Entity) newObj.getClass().getAnnotation(Entity.class));
    if (className == null)
        throw new DataException(newObj.getClass().getSimpleName() + " class is not valid JPA annotated bean");
    String aliasName = StringUtils.isBlank(className.name()) ? "obj" : className.name();

    String hql = "SELECT " + aliasName + " FROM ";
    List<Object> params = new ArrayList<Object>();

    BeanWrapper beanO1 = new BeanWrapperImpl(newObj);
    PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors();
    int propertyLength = proDescriptorsO1.length;

    if (newObj != null) {
        hql += aliasName;
        hql += " IN " + example.getClass();
    }

    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getJoinTables().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " JOIN " + key + " " + voBase.getJoinTables().get(key);
            }
        }
    }

    hql += " WHERE 1=1";

    for (int i = 0; i < propertyLength; i++) {
        try {
            Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName());

            if ((propertyValueO1 instanceof String && StringUtils.isNotBlank((String) propertyValueO1))
                    || propertyValueO1 instanceof Long || propertyValueO1 instanceof Double
                    || propertyValueO1 instanceof Integer || propertyValueO1 instanceof Boolean
                    || propertyValueO1 instanceof Date || propertyValueO1.getClass().isPrimitive()) {
                Field field = null;
                try {
                    field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                } catch (NoSuchFieldException e) {
                    if (propertyValueO1 instanceof Boolean || propertyValueO1.getClass().isPrimitive()) {
                        String fieldName = "is"
                                + StringUtils.upperCase(proDescriptorsO1[i].getName().substring(0, 1))
                                + proDescriptorsO1[i].getName().substring(1);
                        field = example.getClass().getDeclaredField(fieldName);
                    }
                }

                if (proDescriptorsO1[i].getName() != null && field != null
                        && !field.isAnnotationPresent(Transient.class)) {
                    if (!Arrays.asList(VoBase.propertiesVer).contains(proDescriptorsO1[i].getName())) {
                        hql += " AND " + aliasName + "." + field.getName() + " = ?";
                        params.add(propertyValueO1);
                    }
                }
            } else if (propertyValueO1 != null) {
                Field field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                if (field.isAnnotationPresent(javax.persistence.Id.class)
                        || field.isAnnotationPresent(javax.persistence.EmbeddedId.class)) {

                    BeanWrapper bean = new BeanWrapperImpl(propertyValueO1);
                    PropertyDescriptor[] proDescriptors = bean.getPropertyDescriptors();

                    for (PropertyDescriptor propertyDescriptor : proDescriptors) {
                        Object propertyValueId = bean.getPropertyValue(propertyDescriptor.getName());

                        if (propertyValueId != null && ReflectionUtil.isJavaDataType(propertyValueId)) {
                            hql += " AND " + aliasName + "." + proDescriptorsO1[i].getName() + "."
                                    + propertyDescriptor.getName() + " = ?";
                            params.add(bean.getPropertyValue(propertyDescriptor.getName()));
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
    }

    // not condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getNotConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + "!=? ";
                params.add(voBase.getNotConditions().get(key));
            }
        }
    }

    // like condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getLikeConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + " LIKE ? ";
                params.add(voBase.getLikeConditions().get(key));
            }
        }
    }

    if (orderBy != null && orderBy.length != 0) {
        hql += " ORDER BY ";
        long count = 1;
        for (String orderByStr : orderBy) {
            if (count != 1)
                hql += ",";
            hql += aliasName + "." + orderByStr;
            count += 1;
        }
    }

    log.debug("hql = " + hql);

    return new QueryParams(hql, params);
}

From source file:fr.juanwolf.mysqlbinlogreplicator.service.MySQLEventListener.java

Object getObjectFromRows(Serializable[] rows, String tableName)
        throws ReflectiveOperationException, ParseException {
    Object[] columns = columnMap.get(tableName);
    Object object = domainClassAnalyzer.generateInstanceFromName(tableName);
    DomainClass domainClass = domainClassAnalyzer.getDomainClassMap().get(tableName);

    // Setting up the list of foreign keys
    Map<String, SQLRequester> foreignKeysSQLRequesterMap = new HashMap();
    for (String nestedField : domainClass.getSqlRequesters().keySet()) {
        SQLRequester sqlRequester = domainClass.getSqlRequesters().get(nestedField);
        foreignKeysSQLRequesterMap.put(sqlRequester.getForeignKey(), sqlRequester);
    }//from w ww  . j av a 2  s  .  co m

    String debugLogObject = "";
    byte[] columnsType = columnsTypes.get(tableName);
    for (int i = 0; i < rows.length; i++) {
        if (rows[i] != null) {
            try {
                Field field;
                if (foreignKeysSQLRequesterMap.keySet().contains(columns[i].toString())) {
                    String columnsName = columns[i].toString();
                    field = foreignKeysSQLRequesterMap.get(columnsName).getAssociatedField();
                } else {
                    field = object.getClass().getDeclaredField(columns[i].toString());
                }
                domainClassAnalyzer.instantiateField(object, field, rows[i].toString(), columnsType[i],
                        tableName);
                if (log.isDebugEnabled()) {
                    debugLogObject += columns[i] + "=" + rows[i].toString() + ", ";
                }
            } catch (NoSuchFieldException exception) {
                log.warn("No field found for {}", columns[i].toString());
            }
        }
    }
    for (Field field : object.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        Object fieldValue = field.get(object);
        if (fieldValue == null) {
            if (field.isAnnotationPresent(NestedMapping.class)) {
                NestedMapping nestedMapping = field.getAnnotation(NestedMapping.class);
                if (nestedMapping.sqlAssociaton() == SQLRelationship.ONE_TO_MANY) {
                    Field primaryKeyField = object.getClass().getField(nestedMapping.primaryKey());
                    primaryKeyField.setAccessible(true);
                    Object primaryKeyValue = primaryKeyField.get(object);
                    domainClassAnalyzer.instantiateField(object, field, primaryKeyValue.toString(),
                            ColumnType.STRING.getCode(), tableName);
                    primaryKeyField.setAccessible(false);
                }
            }
        }
        field.setAccessible(false);
    }
    log.debug("Object generated :  {{}}", debugLogObject);
    return object;
}

From source file:net.kamhon.ieagle.dao.Jpa2Dao.java

private QueryParams translateExampleToQueryParams(Object example, String... orderBy) {
    Object newObj = example;//w  w w .ja va 2  s .c om
    Entity entity = ((Entity) newObj.getClass().getAnnotation(Entity.class));
    if (entity == null)
        throw new DataException(newObj.getClass().getSimpleName() + " class is not valid JPA annotated bean");

    String entityName = StringUtils.isBlank(entity.name()) ? example.getClass().getSimpleName() : entity.name();
    String aliasName = StringUtils.isBlank(entity.name()) ? "obj" : entity.name();

    String hql = "SELECT " + aliasName + " FROM ";
    List<Object> params = new ArrayList<Object>();

    BeanWrapper beanO1 = new BeanWrapperImpl(newObj);
    PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors();
    int propertyLength = proDescriptorsO1.length;

    if (newObj != null) {
        hql += entityName + " " + aliasName;
    }

    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getJoinTables().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " JOIN " + key + " " + voBase.getJoinTables().get(key);
            }
        }
    }

    hql += " WHERE 1=1";

    int paramCount = 0;
    for (int i = 0; i < propertyLength; i++) {
        try {
            Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName());

            if ((propertyValueO1 instanceof String && StringUtils.isNotBlank((String) propertyValueO1))
                    || propertyValueO1 instanceof Long || propertyValueO1 instanceof Double
                    || propertyValueO1 instanceof Integer || propertyValueO1 instanceof Boolean
                    || propertyValueO1 instanceof Date || propertyValueO1.getClass().isPrimitive()) {

                Field field = null;
                try {
                    field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                } catch (NoSuchFieldException e) {
                    if (propertyValueO1 instanceof Boolean || propertyValueO1.getClass().isPrimitive()) {
                        String fieldName = "is"
                                + StringUtils.upperCase(proDescriptorsO1[i].getName().substring(0, 1))
                                + proDescriptorsO1[i].getName().substring(1);
                        field = example.getClass().getDeclaredField(fieldName);
                    }
                }

                if (proDescriptorsO1[i].getName() != null && field != null
                        && !field.isAnnotationPresent(Transient.class)) {
                    if (!Arrays.asList(VoBase.propertiesVer).contains(proDescriptorsO1[i].getName())) {
                        hql += " AND " + aliasName + "." + field.getName() + " = ?" + (++paramCount);
                        params.add(propertyValueO1);
                    }
                }
            } else if (propertyValueO1 != null) {
                Field field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                if (field.isAnnotationPresent(javax.persistence.Id.class)
                        || field.isAnnotationPresent(javax.persistence.EmbeddedId.class)) {

                    BeanWrapper bean = new BeanWrapperImpl(propertyValueO1);
                    PropertyDescriptor[] proDescriptors = bean.getPropertyDescriptors();

                    for (PropertyDescriptor propertyDescriptor : proDescriptors) {
                        Object propertyValueId = bean.getPropertyValue(propertyDescriptor.getName());

                        if (propertyValueId != null && ReflectionUtil.isJavaDataType(propertyValueId)) {
                            hql += " AND " + aliasName + "." + proDescriptorsO1[i].getName() + "."
                                    + propertyDescriptor.getName() + " = ?" + (++paramCount);
                            params.add(bean.getPropertyValue(propertyDescriptor.getName()));
                        }
                    }
                }
            }

        } catch (Exception e) {
        }
    }

    // not condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getNotConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + "!= ?" + (++paramCount);
                params.add(voBase.getNotConditions().get(key));
            }
        }
    }

    // like condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getLikeConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + " LIKE ?" + (++paramCount);
                params.add(voBase.getLikeConditions().get(key));
            }
        }
    }

    if (orderBy != null && orderBy.length != 0) {
        hql += " ORDER BY ";
        long count = 1;
        for (String orderByStr : orderBy) {
            if (count != 1)
                hql += ",";
            hql += aliasName + "." + orderByStr;
            count += 1;
        }
    }

    log.debug("hql = " + hql);

    return new QueryParams(hql, params);
}

From source file:org.apache.pulsar.broker.service.BrokerService.java

private void updateDynamicServiceConfiguration() {

    try {// ww w .  ja v a2s  . c  om
        // create dynamic-config znode if not present
        if (pulsar.getZkClient().exists(BROKER_SERVICE_CONFIGURATION_PATH, false) == null) {
            try {
                byte[] data = ObjectMapperFactory.getThreadLocal().writeValueAsBytes(Maps.newHashMap());
                ZkUtils.createFullPathOptimistic(pulsar.getZkClient(), BROKER_SERVICE_CONFIGURATION_PATH, data,
                        Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            } catch (KeeperException.NodeExistsException e) {
                // Ok
            }
        }
        Optional<Map<String, String>> data = dynamicConfigurationCache.get(BROKER_SERVICE_CONFIGURATION_PATH);
        if (data.isPresent() && data.get() != null) {
            data.get().forEach((key, value) -> {
                try {
                    Field field = ServiceConfiguration.class.getDeclaredField(key);
                    if (field != null && field.isAnnotationPresent(FieldContext.class)) {
                        field.setAccessible(true);
                        field.set(pulsar().getConfiguration(), FieldParser.value(value, field));
                        log.info("Successfully updated {}/{}", key, value);
                    }
                } catch (Exception e) {
                    log.warn("Failed to update service configuration {}/{}, {}", key, value, e.getMessage());
                }
            });
        }
    } catch (Exception e) {
        log.warn("Failed to read zookeeper path [{}]:", BROKER_SERVICE_CONFIGURATION_PATH, e);
    }
    // register a listener: it updates field value and triggers appropriate registered field-listener only if
    // field's value has been changed so, registered doesn't have to update field value in ServiceConfiguration
    dynamicConfigurationCache.registerListener(new ZooKeeperCacheListener<Map<String, String>>() {
        @SuppressWarnings("unchecked")
        @Override
        public void onUpdate(String path, Map<String, String> data, Stat stat) {
            if (BROKER_SERVICE_CONFIGURATION_PATH.equalsIgnoreCase(path) && data != null) {
                data.forEach((configKey, value) -> {
                    Field configField = dynamicConfigurationMap.get(configKey);
                    Object newValue = FieldParser.value(data.get(configKey), configField);
                    if (configField != null) {
                        Consumer listener = configRegisteredListeners.get(configKey);
                        try {
                            Object existingValue = configField.get(pulsar.getConfiguration());
                            configField.set(pulsar.getConfiguration(), newValue);
                            log.info("Successfully updated configuration {}/{}", configKey,
                                    data.get(configKey));
                            if (listener != null && !existingValue.equals(newValue)) {
                                listener.accept(newValue);
                            }
                        } catch (Exception e) {
                            log.error("Failed to update config {}/{}", configKey, newValue);
                        }
                    } else {
                        log.error("Found non-dynamic field in dynamicConfigMap {}/{}", configKey, newValue);
                    }
                });
            }
        }
    });

}

From source file:com.eucalyptus.objectstorage.pipeline.binding.ObjectStorageRESTBinding.java

protected Map<String, String> buildFieldMap(final Class targetType) {
    Map<String, String> fieldMap = new HashMap<String, String>();
    Field[] fields = targetType.getDeclaredFields();
    for (Field f : fields)
        if (Modifier.isStatic(f.getModifiers()))
            continue;
        else if (f.isAnnotationPresent(HttpParameterMapping.class)) {
            for (final String parameter : f.getAnnotation(HttpParameterMapping.class).parameter())
                fieldMap.put(parameter, f.getName());
            fieldMap.put(f.getName().substring(0, 1).toUpperCase().concat(f.getName().substring(1)),
                    f.getName());/*from   ww  w .  jav  a 2 s  .c  o  m*/
        } else
            fieldMap.put(f.getName().substring(0, 1).toUpperCase().concat(f.getName().substring(1)),
                    f.getName());
    return fieldMap;
}

From source file:com.eucalyptus.objectstorage.pipeline.WalrusRESTBinding.java

private Map<String, String> buildFieldMap(final Class targetType) {
    Map<String, String> fieldMap = new HashMap<String, String>();
    Field[] fields = targetType.getDeclaredFields();
    for (Field f : fields)
        if (Modifier.isStatic(f.getModifiers()))
            continue;
        else if (f.isAnnotationPresent(HttpParameterMapping.class)) {
            for (final String parameter : f.getAnnotation(HttpParameterMapping.class).parameter())
                fieldMap.put(parameter, f.getName());
            fieldMap.put(f.getName().substring(0, 1).toUpperCase().concat(f.getName().substring(1)),
                    f.getName());//w w  w. j a  v a 2s .  c o  m
        } else
            fieldMap.put(f.getName().substring(0, 1).toUpperCase().concat(f.getName().substring(1)),
                    f.getName());
    return fieldMap;
}

From source file:com.eucalyptus.ws.handlers.WalrusRESTBinding.java

private Map<String, String> buildFieldMap(final Class targetType) {
    Map<String, String> fieldMap = new HashMap<String, String>();
    Field[] fields = targetType.getDeclaredFields();
    for (Field f : fields)
        if (Modifier.isStatic(f.getModifiers()))
            continue;
        else if (f.isAnnotationPresent(HttpParameterMapping.class)) {
            fieldMap.put(f.getAnnotation(HttpParameterMapping.class).parameter(), f.getName());
            fieldMap.put(f.getName().substring(0, 1).toUpperCase().concat(f.getName().substring(1)),
                    f.getName());//from w  ww.  j  a v  a  2 s  .c o  m
        } else
            fieldMap.put(f.getName().substring(0, 1).toUpperCase().concat(f.getName().substring(1)),
                    f.getName());
    return fieldMap;
}