Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getName.

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java

/**
 * Create new handler.//ww  w  .  j a  v  a  2 s  .  com
 *
 * @param validatorFactory Validator factory.
 * @param beanClass User input bean class.
 * @param validationGroups Validation groups to apply during bean
 * validation, or empty array to use the default group.
 *
 * @throws UnavailableException If an error happens.
 */
UserInputControllerMethodArgHandler(final ValidatorFactory validatorFactory, final Class<?> beanClass,
        final Class<?>[] validationGroups) throws UnavailableException {

    this.validatorFactory = validatorFactory;

    this.beanClass = beanClass;
    this.validationGroups = validationGroups;

    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(this.beanClass);
        final PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();
        final List<FieldDesc> beanFields = new ArrayList<>();
        for (final PropertyDescriptor propDesc : propDescs) {
            final String propName = propDesc.getName();
            final Class<?> propType = propDesc.getPropertyType();
            final Method propGetter = propDesc.getReadMethod();
            final Method propSetter = propDesc.getWriteMethod();

            if ((propGetter == null) || (propSetter == null))
                continue;

            Field propField = null;
            for (Class<?> c = this.beanClass; !c.equals(Object.class); c = c.getSuperclass()) {
                try {
                    propField = c.getDeclaredField(propName);
                    break;
                } catch (final NoSuchFieldException e) {
                    // nothing, continue the loop
                }
            }
            final boolean noTrim = (((propField != null) && propField.isAnnotationPresent(NoTrim.class))
                    || (propGetter.isAnnotationPresent(NoTrim.class)));

            Class<? extends Binder> binderClass = null;
            String format = null;
            String errorMessage = Bind.DEFAULT_MESSAGE;
            Bind bindAnno = null;
            if (propField != null)
                bindAnno = propField.getAnnotation(Bind.class);
            if (bindAnno == null)
                bindAnno = propGetter.getAnnotation(Bind.class);
            if (bindAnno != null) {
                binderClass = bindAnno.binder();
                format = bindAnno.format();
                errorMessage = bindAnno.message();
            }
            if (binderClass == null) {
                if ((String.class).isAssignableFrom(propType))
                    binderClass = StringBinder.class;
                else if ((Boolean.class).isAssignableFrom(propType) || propType.equals(Boolean.TYPE))
                    binderClass = BooleanBinder.class;
                else if ((Integer.class).isAssignableFrom(propType) || propType.equals(Integer.TYPE))
                    binderClass = IntegerBinder.class;
                else if (propType.isEnum())
                    binderClass = EnumBinder.class;
                else // TODO: add more standard binders
                    throw new UnavailableException(
                            "Unsupported user input bean field type " + propType.getName() + ".");
            }

            beanFields.add(new FieldDesc(propDesc, noTrim, binderClass.newInstance(), format, errorMessage));
        }
        this.beanFields = beanFields.toArray(new FieldDesc[beanFields.size()]);
    } catch (final IntrospectionException e) {
        this.log.error("error introspecting user input bean", e);
        throw new UnavailableException("Specified user input bean" + " class could not be introspected.");
    } catch (final IllegalAccessException | InstantiationException e) {
        this.log.error("error instatiating binder", e);
        throw new UnavailableException("Used user input bean field binder" + " could not be instantiated.");
    }

    this.beanPool = new FastPool<>(new PoolableObjectFactory<PoolableUserInput>() {

        @Override
        public PoolableUserInput makeNew(final FastPool<PoolableUserInput> pool, final int pooledObjectId) {

            try {
                return new PoolableUserInput(pool, pooledObjectId, beanClass.newInstance());
            } catch (final InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Error instatiating user input bean.", e);
            }
        }
    }, "UserInputBeansPool_" + beanClass.getSimpleName());
}

From source file:com.espertech.esperio.csv.CSVInputAdapter.java

private Map<String, Object> constructPropertyTypes(String eventTypeName, Map<String, Object> propertyTypesGiven,
        EventAdapterService eventAdapterService) {
    Map<String, Object> propertyTypes = new HashMap<String, Object>();
    EventType eventType = eventAdapterService.getExistsTypeByName(eventTypeName);
    if (eventType == null) {
        if (propertyTypesGiven != null) {
            eventAdapterService.addNestableMapType(eventTypeName,
                    new HashMap<String, Object>(propertyTypesGiven), null, true, true, true, false, false);
        }/*from   w  w w.ja  va  2s  .co m*/
        return propertyTypesGiven;
    }
    if (!eventType.getUnderlyingType().equals(Map.class)) {
        beanClass = eventType.getUnderlyingType();
    }
    if (propertyTypesGiven != null && eventType.getPropertyNames().length != propertyTypesGiven.size()) {
        // allow this scenario for beans as we may want to bring in a subset of properties
        if (beanClass != null) {
            return propertyTypesGiven;
        } else {
            throw new EPException("Event type " + eventTypeName
                    + " has already been declared with a different number of parameters");
        }
    }
    for (String property : eventType.getPropertyNames()) {
        Class type;
        try {
            type = eventType.getPropertyType(property);
        } catch (PropertyAccessException e) {
            // thrown if trying to access an invalid property on an EventBean
            throw new EPException(e);
        }
        if (propertyTypesGiven != null && propertyTypesGiven.get(property) == null) {
            throw new EPException(
                    "Event type " + eventTypeName + "has already been declared with different parameters");
        }
        if (propertyTypesGiven != null && !propertyTypesGiven.get(property).equals(type)) {
            throw new EPException("Event type " + eventTypeName
                    + "has already been declared with a different type for property " + property);
        }
        // we can't set read-only properties for bean
        if (!eventType.getUnderlyingType().equals(Map.class)) {
            PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(beanClass);
            PropertyDescriptor pd = null;
            for (PropertyDescriptor p : pds) {
                if (p.getName().equals(property))
                    pd = p;
            }
            if (pd == null) {
                continue;
            }
            if (pd.getWriteMethod() == null) {
                if (propertyTypesGiven == null) {
                    continue;
                } else {
                    throw new EPException(
                            "Event type " + eventTypeName + "property " + property + " is read only");
                }
            }
        }
        propertyTypes.put(property, type);
    }

    // flatten nested types
    Map<String, Object> flattenPropertyTypes = new HashMap<String, Object>();
    for (String p : propertyTypes.keySet()) {
        Object type = propertyTypes.get(p);
        if (type instanceof Class && ((Class) type).getName().equals("java.util.Map")
                && eventType instanceof MapEventType) {
            MapEventType mapEventType = (MapEventType) eventType;
            Map<String, Object> nested = (Map) mapEventType.getTypes().get(p);
            for (String nestedProperty : nested.keySet()) {
                flattenPropertyTypes.put(p + "." + nestedProperty, nested.get(nestedProperty));
            }
        } else if (type instanceof Class) {
            Class c = (Class) type;
            if (!c.isPrimitive() && !c.getName().startsWith("java")) {
                PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(c);
                for (PropertyDescriptor pd : pds) {
                    if (pd.getWriteMethod() != null)
                        flattenPropertyTypes.put(p + "." + pd.getName(), pd.getPropertyType());
                }
            } else {
                flattenPropertyTypes.put(p, type);
            }
        } else {
            flattenPropertyTypes.put(p, type);
        }
    }
    return flattenPropertyTypes;
}

From source file:org.ambraproject.user.service.UserServiceImpl.java

@Override
public UserProfile getProfileForDisplay(UserProfile userProfile, boolean showPrivateFields) {
    UserProfile display = new UserProfile();
    copyFields(userProfile, display);//w w w  . j  ava  2  s.c o  m
    if (!showPrivateFields) {
        log.debug("Removing private fields for display on user: {}", userProfile.getDisplayName());
        display.setOrganizationName(null);
        display.setOrganizationType(null);
        display.setPostalAddress(null);
        display.setPositionType(null);
    }

    //escape html in all string fields
    BeanWrapper wrapper = new BeanWrapperImpl(display);
    for (PropertyDescriptor property : wrapper.getPropertyDescriptors()) {
        if (String.class.isAssignableFrom(property.getPropertyType())) {
            String name = property.getName();
            wrapper.setPropertyValue(name, TextUtils.escapeHtml((String) wrapper.getPropertyValue(name)));
        }
    }

    return display;
}

From source file:org.ambraproject.article.service.IngesterImpl.java

/**
 * Update an existing article by copying properties from the new one over.  Note that we can't call saveOrUpdate,
 * since the new article is not a persistent instance, but has all the properties that we want.
 * <p/>//from  w w  w. j  a v a  2  s . co  m
 * See <a href="http://stackoverflow.com/questions/4779239/update-persistent-object-with-transient-object-using-hibernate">this
 * post on stack overflow</a> for more information
 * <p/>
 * For collections, we clear the old property and add all the new entries, relying on 'delete-orphan' to delete the
 * old objects. The downside of this approach is that it results in a delete statement for each entry in the old
 * collection, and an insert statement for each entry in the new collection.  There a couple of things we could do to
 * optimize this: <ol> <li>Write a sql statement to delete the old entries in one go</li> <li>copy over collection
 * properties recursively instead of clearing the old collection.  e.g. for {@link Article#assets}, instead of
 * clearing out the old list, we would find the matching asset by DOI and Extension, and update its properties</li>
 * </ol>
 * <p/>
 * Option number 2 is messy and a lot of code (I've done it before)
 *
 * @param article         the new article, parsed from the xml
 * @param existingArticle the article pulled up from the database
 * @throws IngestException if there's a problem copying properties or updating
 */
@SuppressWarnings("unchecked")
private void updateArticle(final Article article, final Article existingArticle) throws IngestException {
    log.debug("ReIngesting (force ingest) article: {}", existingArticle.getDoi());
    //Hibernate deletes orphans after inserting the new rows, which violates a unique constraint on (doi, extension) for assets
    //this temporary change gets around the problem, before the old assets are orphaned and deleted
    hibernateTemplate.execute(new HibernateCallback() {
        @Override
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            session.createSQLQuery("update articleAsset " + "set doi = concat('old-',doi), "
                    + "extension = concat('old-',extension) " + "where articleID = :articleID")
                    .setParameter("articleID", existingArticle.getID()).executeUpdate();
            return null;
        }
    });

    final BeanWrapper source = new BeanWrapperImpl(article);
    final BeanWrapper destination = new BeanWrapperImpl(existingArticle);

    try {
        //copy properties
        for (final PropertyDescriptor property : destination.getPropertyDescriptors()) {
            final String name = property.getName();
            if (!name.equals("ID") && !name.equals("created") && !name.equals("lastModified")
                    && !name.equals("class")) {
                //Collections shouldn't be dereferenced but have elements added
                //See http://www.onkarjoshi.com/blog/188/hibernateexception-a-collection-with-cascade-all-delete-orphan-was-no-longer-referenced-by-the-owning-entity-instance/
                if (Collection.class.isAssignableFrom(property.getPropertyType())) {
                    Collection orig = (Collection) destination.getPropertyValue(name);
                    orig.clear();
                    Collection sourcePropertyValue = (Collection) source.getPropertyValue(name);
                    if (sourcePropertyValue != null) {
                        orig.addAll((Collection) source.getPropertyValue(name));
                    }
                } else {
                    //just set the new value
                    destination.setPropertyValue(name, source.getPropertyValue(name));
                }
            }
        }
        //Circular relationship in related articles
        for (ArticleRelationship articleRelationship : existingArticle.getRelatedArticles()) {
            articleRelationship.setParentArticle(existingArticle);
        }
    } catch (Exception e) {
        throw new IngestException("Error copying properties for article " + article.getDoi(), e);
    }

    hibernateTemplate.update(existingArticle);
}

From source file:com.hengyi.japp.sap.convert.impl.SapConverts.java

private String getSapFieldName(PropertyDescriptor descriptor) {
    Method readMethod = descriptor.getReadMethod();
    SapConvertField scf = readMethod.getAnnotation(SapConvertField.class);
    if (scf != null) {
        return StringUtils.upperCase(scf.value());
    }//ww  w .j a  va  2s. c om
    if (readMethod.getAnnotation(SapTransient.class) != null) {
        return null;
    }

    String beanPropertyName = descriptor.getName();
    for (Field field : beanClass.getDeclaredFields()) {
        if (!field.getName().equals(beanPropertyName)) {
            continue;
        }

        if (field.getAnnotation(SapTransient.class) != null) {
            return null;
        }
        scf = field.getAnnotation(SapConvertField.class);
        if (scf != null) {
            return StringUtils.upperCase(scf.value());
        }
    }
    return StringUtils.upperCase(beanPropertyName);
}

From source file:net.jolm.JolmLdapTemplate.java

private boolean isAttributeApplicableInFilter(PropertyDescriptor pd) {
    String propertyName = pd.getName();
    return applicableTypesInFilter.contains(pd.getPropertyType()) && !isReservedField(propertyName);
}

From source file:gr.interamerican.bo2.utils.TestJavaBeanUtils.java

/**
 * Unit test for getPropertyDescriptor./*  www .j  av  a 2 s  .c  o m*/
 */
@SuppressWarnings("nls")
@Test
public void testGetPropertyDescriptor() {

    //class
    PropertyDescriptor[] props = JavaBeanUtils.getBeansProperties(BeanWith2Fields.class);
    for (PropertyDescriptor p : props) {
        PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(BeanWith2Fields.class, p.getName());
        assertNotNull(pd);
        assertEquals(pd.getName(), p.getName());
        assertEquals(pd.getPropertyType(), p.getPropertyType());
    }

    //class with inheritance
    props = JavaBeanUtils.getBeansProperties(Child.class);
    for (PropertyDescriptor p : props) {
        PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(Child.class, p.getName());
        assertNotNull(pd);
        assertEquals(pd.getName(), p.getName());
        assertEquals(pd.getPropertyType(), p.getPropertyType());
    }

    //abstract class
    PropertyDescriptor pd1 = JavaBeanUtils.getPropertyDescriptor(SampleAbstractClass2.class, "field1"); //$NON-NLS-1$
    assertNull(pd1);

    //interface
    props = JavaBeanUtils.getBeansProperties(SuperSampleInterface.class);
    for (PropertyDescriptor p : props) {
        PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(SuperSampleInterface.class, p.getName());
        assertNotNull(pd);
        assertEquals(pd.getName(), p.getName());
        assertEquals(pd.getPropertyType(), p.getPropertyType());
    }

    //interface with inheritance
    props = JavaBeanUtils.getBeansProperties(SubSampleInterface.class);
    for (PropertyDescriptor p : props) {
        PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(SubSampleInterface.class, p.getName());
        assertNotNull(pd);
        assertEquals(pd.getName(), p.getName());
        assertEquals(pd.getPropertyType(), p.getPropertyType());
    }

    //nested property
    PropertyDescriptor nestedPd = JavaBeanUtils.getPropertyDescriptor(BeanWithNestedBean.class,
            "nested.field1");
    PropertyDescriptor directPd = JavaBeanUtils.getPropertyDescriptor(BeanWith2Fields.class, "field1");
    assertNotNull(nestedPd);
    assertNotNull(directPd);
    assertEquals(nestedPd.getName(), directPd.getName());
    assertEquals(nestedPd.getPropertyType(), directPd.getPropertyType());

}

From source file:com.urbanmania.spring.beans.factory.config.annotations.PropertyAnnotationAndPlaceholderConfigurer.java

private void setProperty(Properties properties, String name, MutablePropertyValues mpv, Class<?> clazz,
        PropertyDescriptor property, Property annotation) {
    String value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);

    if (value == null) {
        value = annotation.value();//from w  ww  .  j ava2s  .co  m
    }

    value = parseStringValue(value, properties, new HashSet<String>());

    log.info("setting property=[" + clazz.getName() + "." + property.getName() + "] value=[" + annotation.key()
            + "=" + value + "]");

    mpv.addPropertyValue(property.getName(), value);

    if (annotation.update()) {
        registerBeanPropertyForUpdate(clazz, annotation, property);
    }
}

From source file:com.gmail.sretof.db.jdbc.processor.CamelBeanProcessor.java

/**
 * Returns a PropertyDescriptor[] for the given Class.
 * //w  w w.  ja v a  2 s.  com
 * @param c
 *            The Class to retrieve PropertyDescriptors for.
 * @return A PropertyDescriptor[] describing the Class.
 * @throws SQLException
 *             if introspection failed.
 */
private PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException {
    // Introspector caches BeanInfo classes for better performance
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(c);
    } catch (IntrospectionException e) {
        throw new SQLException("Bean introspection failed: " + e.getMessage());
    }
    List<PropertyDescriptor> propList = Lists.newArrayList();
    PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        String propName = prop.getName();
        try {
            Field field = ReflectionUtils.findField(c, propName);
            if (field != null && !field.isAnnotationPresent(Transient.class)) {// 1.field=null
                // 2.Transient??
                propList.add(prop);
            }
        } catch (SecurityException e) {
            throw new SQLException("Bean Get Field failed: " + e.getMessage());
        }
    }
    return propList.toArray(new PropertyDescriptor[propList.size()]);
}

From source file:com.eclecticlogic.pedal.dialect.postgresql.CopyCommand.java

private String extractColumnName(Method method, Class<? extends Serializable> clz) {
    String beanPropertyName = null;
    try {//from ww w .ja va2s.  com
        BeanInfo info;

        info = Introspector.getBeanInfo(clz);

        for (PropertyDescriptor propDesc : info.getPropertyDescriptors()) {
            if (method.equals(propDesc.getReadMethod())) {
                beanPropertyName = propDesc.getName();
                break;
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    String columnName = null;
    if (clz.isAnnotationPresent(AttributeOverrides.class)) {
        for (AttributeOverride annotation : clz.getAnnotation(AttributeOverrides.class).value()) {
            if (annotation.name().equals(beanPropertyName)) {
                columnName = annotation.column().name();
                break;
            }
        }
    } else if (clz.isAnnotationPresent(AttributeOverride.class)) {
        AttributeOverride annotation = clz.getAnnotation(AttributeOverride.class);
        if (annotation.name().equals(beanPropertyName)) {
            columnName = annotation.column().name();
        }
    }
    return columnName == null ? method.getAnnotation(Column.class).name() : columnName;
}