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:es.logongas.ix3.web.json.impl.JsonReaderImplEntityJackson.java

/**
 * Establece el valor de la propiedad de un Bean
 *
 * @param obj El objeto Bean//from   w  ww. ja va2s  .co  m
 * @param value El valor de la propiedad
 * @param propertyName El nombre de la propiedad
 */
private void setValueToBean(Object obj, Object value, String propertyName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        Method writeMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(propertyName)) {
                writeMethod = propertyDescriptor.getWriteMethod();
            }
        }

        if (writeMethod == null) {
            throw new RuntimeException(
                    "No existe la propiedad:" + propertyName + " en " + obj.getClass().getName());
        }

        writeMethod.invoke(obj, value);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:es.logongas.ix3.web.json.impl.JsonWriterImplEntityJackson.java

/**
 * Obtiene el valor de la propiedad de un Bean
 *
 * @param obj El objeto Bean// w  w w . ja  va2  s  .c o  m
 * @param propertyName El nombre de la propiedad
 * @return El valor de la propiedad
 */
private Object getValueFromBean(Object obj, String propertyName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        Method readMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(propertyName)) {
                readMethod = propertyDescriptor.getReadMethod();
                break;
            }
        }

        if (readMethod == null) {
            throw new RuntimeException(
                    "No existe la propiedad:" + propertyName + " en la clase " + obj.getClass().getName());
        }

        return readMethod.invoke(obj);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

protected void populateCachedReferenceEntities(final Class entityClass,
        final CachedReferenceEntity[] cachedEntities, final String[] propertyList, final Object[][] data)
        throws HibernateException {
    try {//from w  w w  . j av a  2  s. co m
        final Hashtable pdsByName = new Hashtable();
        final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
        final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < descriptors.length; i++) {
            final PropertyDescriptor descriptor = descriptors[i];
            if (descriptor.getWriteMethod() != null)
                pdsByName.put(descriptor.getName(), descriptor.getWriteMethod());
        }

        Map entityMapByCache = new HashMap<CachedReferenceEntity, Object>();
        for (int i = 0; i < data.length; i++) {
            final Object entityObject = entityClass.newInstance();
            for (int j = 0; j < propertyList.length; j++) {
                final Method setter = (Method) pdsByName.get(propertyList[j]);
                if (setter != null && data[i][j] != null) {
                    setter.invoke(entityObject, new Object[] { data[i][j] });
                }
            }
            entityMapByCache.put(cachedEntities[i], entityObject);
            if (!useEjb)
                session.save(entityObject);
            else
                entityManager.persist(entityObject);
            cachedEntities[i].setEntity((ReferenceEntity) entityObject);
        }
    } catch (Exception e) {
        log.error(e);
        throw new HibernateException(e);
    }
}

From source file:ca.sqlpower.architect.swingui.TestPlayPenComponent.java

/**
  * Checks that the properties of an instance from the copy constructor are equal to the original.
  * In the case of a mutable property, it also checks that they don't share the same instance.
  * //from   w w  w .  j  av a 2s . c o  m
  * @throws Exception
  */
public void testCopyConstructor() throws Exception {
    PlayPenComponent comp = getTarget();

    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(comp.getClass()));

    copyIgnoreProperties.add("UI");
    copyIgnoreProperties.add("UIClassID");
    copyIgnoreProperties.add("UUID");
    copyIgnoreProperties.add("allowedChildTypes");
    copyIgnoreProperties.add("background");
    copyIgnoreProperties.add("bounds");
    copyIgnoreProperties.add("class");
    copyIgnoreProperties.add("children");
    copyIgnoreProperties.add("fontRenderContext");
    copyIgnoreProperties.add("height");
    copyIgnoreProperties.add("insets");
    copyIgnoreProperties.add("lengths");
    copyIgnoreProperties.add("location");
    copyIgnoreProperties.add("locationOnScreen");
    copyIgnoreProperties.add("magicEnabled");
    copyIgnoreProperties.add("opaque");
    copyIgnoreProperties.add("parent");
    copyIgnoreProperties.add("playPen");
    copyIgnoreProperties.add("popup");
    copyIgnoreProperties.add("preferredLocation");
    copyIgnoreProperties.add("preferredSize");
    copyIgnoreProperties.add("selected");
    copyIgnoreProperties.add("session");
    copyIgnoreProperties.add("workspaceContainer");
    copyIgnoreProperties.add("runnableDispatcher");
    copyIgnoreProperties.add("size");
    copyIgnoreProperties.add("toolTipText");
    copyIgnoreProperties.add("width");
    copyIgnoreProperties.add("x");
    copyIgnoreProperties.add("y");

    // no setters for this and it depends on the playpen's font
    copyIgnoreProperties.add("font");

    // not so sure if this should be duplicated, it's changed as the model properties changes
    copyIgnoreProperties.add("modelName");

    // copy and original should point to same business object
    copySameInstanceIgnoreProperties.add("model");

    // First pass: set all settable properties, because testing the duplication of
    //             an object with all its properties at their defaults is not a
    //             very convincing test of duplication!
    for (PropertyDescriptor property : settableProperties) {
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(comp, property.getName());
            // check for a setter
            if (property.getWriteMethod() != null) {
                Object newVal = getNewDifferentValue(property, oldVal);
                BeanUtils.copyProperty(comp, property.getName(), newVal);
            }
        } catch (NoSuchMethodException e) {
            System.out.println("Skipping non-settable property " + property.getName() + " on "
                    + comp.getClass().getName());
        }
    }
    // Second pass get a copy make sure all of 
    // the origional mutable objects returned from getters are different
    // between the two objects, but have the same values. 
    PlayPenComponent duplicate = getTargetCopy();
    for (PropertyDescriptor property : settableProperties) {
        if (copyIgnoreProperties.contains(property.getName()))
            continue;
        Object oldVal;
        try {
            oldVal = PropertyUtils.getSimpleProperty(comp, property.getName());
            Object copyVal = PropertyUtils.getSimpleProperty(duplicate, property.getName());
            if (oldVal == null) {
                throw new NullPointerException("We forgot to set " + property.getName());
            } else {
                assertEquals("The two values for property " + property.getDisplayName() + " in "
                        + comp.getClass().getName() + " should be equal", oldVal, copyVal);

                if (isPropertyInstanceMutable(property)
                        && !copySameInstanceIgnoreProperties.contains(property.getName())) {
                    assertNotSame("Copy shares mutable property with original, property name: "
                            + property.getDisplayName(), copyVal, oldVal);
                }
            }
        } catch (NoSuchMethodException e) {
            System.out.println("Skipping non-settable property " + property.getName() + " on "
                    + comp.getClass().getName());
        }
    }
}

From source file:org.ambraproject.testutils.DummyHibernateDataStore.java

@Override
@SuppressWarnings("unchecked")
public <T> T get(final Class<T> clazz, final Serializable id) {
    return (T) hibernateTemplate.execute(new HibernateCallback() {
        @Override/* w w  w.ja v a 2  s  .  c  o m*/
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            T object = (T) session.get(clazz, id);
            if (object == null) {
                return null;
            } else {
                //Load up all the object's collection attributes in a session to make sure they aren't lazy-loaded
                BeanWrapper wrapper = new BeanWrapperImpl(object);
                for (PropertyDescriptor propertyDescriptor : wrapper.getPropertyDescriptors()) {
                    if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                        Iterator iterator = ((Collection) wrapper
                                .getPropertyValue(propertyDescriptor.getName())).iterator();
                        while (iterator.hasNext()) {
                            iterator.next();
                        }
                    }
                }
            }
            return object;
        }
    });
}

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

protected void populateCachedCustomReferenceEntities(final Class entityClass,
        final CachedCustomReferenceEntity[] cachedEntities, final String[] propertyList, final Object[][] data)
        throws HibernateException {
    try {/*from  w w w .  j a va 2s  .  c om*/
        final Hashtable pdsByName = new Hashtable();
        final BeanInfo beanInfo = Introspector.getBeanInfo(entityClass);
        final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < descriptors.length; i++) {
            final PropertyDescriptor descriptor = descriptors[i];
            if (descriptor.getWriteMethod() != null)
                pdsByName.put(descriptor.getName(), descriptor.getWriteMethod());
        }

        Map entityMapByCache = new HashMap<CachedCustomReferenceEntity, Object>();
        for (int i = 0; i < data.length; i++) {
            final Object entityObject = entityClass.newInstance();
            for (int j = 0; j < propertyList.length; j++) {
                final Method setter = (Method) pdsByName.get(propertyList[j]);
                if (setter != null && data[i][j] != null) {
                    if (data[i][j] instanceof CachedCustomHierarchyReferenceEntity) {
                        setter.invoke(entityObject, new Object[] { entityMapByCache.get(data[i][j]) });
                    } else
                        setter.invoke(entityObject, new Object[] { data[i][j] });
                }
            }
            entityMapByCache.put(cachedEntities[i], entityObject);
            if (!useEjb)
                session.save(entityObject);
            else
                entityManager.persist(entityObject);
            cachedEntities[i].setEntity((CustomReferenceEntity) entityObject);
        }
    } catch (Exception e) {
        log.error(ExceptionUtils.getStackTrace(e));
        throw new HibernateException(e);
    }
}

From source file:com.springframework.beans.CachedIntrospectionResults.java

/**
 * Create a new CachedIntrospectionResults instance for the given class.
 * @param beanClass the bean class to analyze
 * @throws BeansException in case of introspection failure
 *///  w  w w  . j  a va  2s .  c o m
private CachedIntrospectionResults(Class<?> beanClass) throws BeansException {
    try {
        if (logger.isTraceEnabled()) {
            logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]");
        }

        BeanInfo beanInfo = null;
        for (BeanInfoFactory beanInfoFactory : beanInfoFactories) {
            beanInfo = beanInfoFactory.getBeanInfo(beanClass);
            if (beanInfo != null) {
                break;
            }
        }
        if (beanInfo == null) {
            // If none of the factories supported the class, fall back to the default
            beanInfo = (shouldIntrospectorIgnoreBeaninfoClasses
                    ? Introspector.getBeanInfo(beanClass, Introspector.IGNORE_ALL_BEANINFO)
                    : Introspector.getBeanInfo(beanClass));
        }
        this.beanInfo = beanInfo;

        if (logger.isTraceEnabled()) {
            logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]");
        }
        this.propertyDescriptorCache = new LinkedHashMap<String, PropertyDescriptor>();

        // This call is slow so we do it once.
        PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            if (Class.class.equals(beanClass)
                    && ("classLoader".equals(pd.getName()) || "protectionDomain".equals(pd.getName()))) {
                // Ignore Class.getClassLoader() and getProtectionDomain() methods - nobody needs to bind to those
                continue;
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Found bean property '" + pd.getName() + "'"
                        + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]"
                                : "")
                        + (pd.getPropertyEditorClass() != null
                                ? "; editor [" + pd.getPropertyEditorClass().getName() + "]"
                                : ""));
            }
            pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
            this.propertyDescriptorCache.put(pd.getName(), pd);
        }

        this.typeDescriptorCache = new ConcurrentReferenceHashMap<PropertyDescriptor, TypeDescriptor>();
    } catch (IntrospectionException ex) {
        throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex);
    } finally {

    }
}

From source file:com.opensymphony.able.introspect.EntityInfo.java

/**
 * Lets introspect all the properties//from   www  .  j  av  a 2s .c  om
 */
protected void introspect(Class<? extends Object> type) {
    PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(entityClass);
    for (PropertyDescriptor descriptor : propertyDescriptors) {
        String name = descriptor.getName();
        if (name.equals("class")) {
            continue;
        }

        PropertyInfo propertyInfo = new PropertyInfo(this, descriptor, entityClass);
        propertyMap.put(name, propertyInfo);
        if (propertyInfo.isIdProperty()) {
            if (idProperty != null) {
                throw new IllegalStateException(
                        "Duplicate @Id properties defined for: " + idProperty + " and " + propertyInfo);
            }
            this.idProperty = propertyInfo;
        }
    }

    // now lets create the sorted properties list
    configureViewDefaults();
    configureViewTable();
    configureEditTable();
    configureViewForm();
    configureEditForm();
    configureViewField();
}

From source file:com.yosanai.java.swing.editor.ObjectEditorTableModel.java

@SuppressWarnings("rawtypes")
protected void addRows(BeanWrapper beanWrapper, PropertyDescriptor propertyDescriptor, String prefix,
        Set<Integer> visited) {
    if (StringUtils.isBlank(prefix)) {
        prefix = "";
    } else if (!prefix.endsWith(".")) {
        prefix += ".";
    }/*from  w ww  .  j  a v  a  2  s.c  o m*/
    Object propertyValue = beanWrapper.getPropertyValue(propertyDescriptor.getName());
    if (isPrimitive(propertyDescriptor.getPropertyType())) {
        String value = "";
        if (null != propertyValue) {
            if (propertyDescriptor.getPropertyType().isEnum()) {
                value = ((Enum) propertyValue).name();
            } else {
                value = propertyValue.toString();
            }
        }
        addRow(new Object[] { prefix + propertyDescriptor.getName(), value });
    } else if (expandAllProperties) {
        addRows(propertyValue, prefix + propertyDescriptor.getName(), visited);
    }
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicCommand.java

/**
 * set this instance null properties with the passed configuration
 * @param src//from   ww w .j  av  a  2 s .c  o m
 */
public void copyConfigurationIntoCommand(final ImageMosaicConfiguration src) {

    final PropertyDescriptor[] srcProps = PropertyUtils.getPropertyDescriptors(src);
    for (PropertyDescriptor srcProp : srcProps) {
        final String name = srcProp.getName();
        if (RESERVED_PROPS.contains(name)) {
            continue;
        }
        final Object obj;
        try {
            obj = PropertyUtils.getProperty(this, name);
            if (obj == null) {
                // override
                PropertyUtils.setProperty(this, name, PropertyUtils.getProperty(src, name));
            }
        } catch (InvocationTargetException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        } catch (NoSuchMethodException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        } catch (IllegalAccessException e) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(e.getMessage());
        }
    }

    copyDomainAttributes(src, this);
}