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:gov.nih.nci.caarray.external.v1_0.AbstractCaArrayEntityTest.java

private void setSomeProperty(AbstractCaArrayEntity a) throws Exception {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(a);
    for (PropertyDescriptor p : pds) {
        if (p.getName().equals("id"))
            continue;
        if (p.getPropertyType() == String.class) {
            p.getWriteMethod().invoke(a, "some String");
            return;
        }/*from  www .  j a  v a2s . c om*/

        if (p.getPropertyType() == Person.class) {
            p.getWriteMethod().invoke(a, new Person());
            return;
        }

        if (p.getPropertyType() == FileMetadata.class) {
            p.getWriteMethod().invoke(a, new FileMetadata());
            return;
        }

    }

    throw new UnsupportedOperationException("did know how to set a property on " + a.getClass());
}

From source file:egovframework.com.ext.ldapumt.service.impl.ObjectMapper.java

/**
 * ContextAdapter?  ? vo .//from  w  w  w.jav a 2 s.  c o  m
 */
public Object mapFromContext(Object arg0) throws NamingException {
    DirContextAdapter adapter = (DirContextAdapter) arg0;
    Attributes attrs = adapter.getAttributes();

    LdapObject vo = null;

    try {
        vo = (LdapObject) type.newInstance();
    } catch (Exception e2) {
        throw new RuntimeException(e2);
    }

    vo.setDn(adapter.getDn().toString());

    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(type);
    } catch (IntrospectionException e1) {
        throw new RuntimeException(e1);
    }

    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

    for (PropertyDescriptor descriptor : propertyDescriptors) {
        if (attrs.get(descriptor.getName()) != null)
            try {
                Class<?> o = descriptor.getPropertyType();
                if (o == int.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            Integer.valueOf((String) attrs.get(descriptor.getName()).get()));
                if (o == String.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            (String) attrs.get(descriptor.getName()).get());
                if (o == Boolean.class)
                    PropertyUtils.setProperty(vo, descriptor.getName(),
                            ((String) attrs.get(descriptor.getName()).get()).equals("Y"));

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

    return vo;
}

From source file:de.tudarmstadt.ukp.csniper.webapp.security.dao.AbstractDao.java

/**
 * Finds all entities that have the same type as the given example and all fields are equal to
 * non-null fields in the example./*from   ww w.j a  va2  s.  c o  m*/
 */
protected <TT> CriteriaQuery<TT> queryByExample(TT aExample, String aOrderBy, boolean aAscending) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    @SuppressWarnings("unchecked")
    CriteriaQuery<TT> query = cb.createQuery((Class<TT>) aExample.getClass());
    @SuppressWarnings("unchecked")
    Root<TT> root = query.from((Class<TT>) aExample.getClass());
    query.select(root);

    List<Predicate> predicates = new ArrayList<Predicate>();
    BeanWrapper a = PropertyAccessorFactory.forBeanPropertyAccess(aExample);

    // Iterate over all properties
    for (PropertyDescriptor d : a.getPropertyDescriptors()) {
        Object value = a.getPropertyValue(d.getName());

        // Only consider writeable properties. This filters out e.g. the "class" (getClass())
        // property.
        if (value != null && a.isWritableProperty(d.getName())) {
            predicates.add(cb.equal(root.get(d.getName()), value));
        }
    }

    if (!predicates.isEmpty()) {
        query.where(predicates.toArray(new Predicate[predicates.size()]));
    }

    if (aOrderBy != null) {
        if (aAscending) {
            query.orderBy(cb.asc(root.get(aOrderBy)));
        } else {
            query.orderBy(cb.desc(root.get(aOrderBy)));
        }
    }

    return query;
}

From source file:cherry.foundation.type.jdbc.CustomBeanPropertyRowMapper.java

@Override
protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {

    Object object = super.getColumnValue(rs, index, pd);
    if (maskerMap == null || !maskerMap.containsKey(pd.getName())) {
        return object;
    }//w  w  w .j av a2 s .c  o  m

    @SuppressWarnings("unchecked")
    Masker<Object> masker = (Masker<Object>) maskerMap.get(pd.getName());
    return masker.mask(object);
}

From source file:info.magnolia.content2bean.TypeDescriptor.java

/**
 * This method is not synchronized to avoid thread blocking, but the method guarantees that the returned map is not mutated afterward.
 *///from   w  ww .j  a v a 2s.co  m
public Map<String, PropertyTypeDescriptor> getPropertyDescriptors(TypeMapping typeMapping) {
    //TODO ---- moved this out to TypeDescriptorFactory or something ?
    if (this.descriptors == null) {

        // for not making this method synchronized we create a local variable first
        // this guarantees that the map you get is not changed after return
        final Map<String, PropertyTypeDescriptor> tmpDescriptors = new HashMap<String, PropertyTypeDescriptor>();
        PropertyDescriptor[] dscrs = PropertyUtils.getPropertyDescriptors(this.getType());
        for (int i = 0; i < dscrs.length; i++) {
            PropertyDescriptor descriptor = dscrs[i];
            tmpDescriptors.put(descriptor.getName(),
                    typeMapping.getPropertyTypeDescriptor(this.getType(), descriptor.getName()));
        }

        this.descriptors = Collections.unmodifiableMap(tmpDescriptors);
    }
    return this.descriptors;
}

From source file:io.spring.initializr.web.project.AbstractInitializrController.java

/**
 * Render the home page with the specified template.
 * @param model the model data//from   w w w . java2 s  .  c  o  m
 */
protected void renderHome(Map<String, Object> model) {
    InitializrMetadata metadata = this.metadataProvider.get();

    model.put("serviceUrl", generateAppUrl());
    BeanWrapperImpl wrapper = new BeanWrapperImpl(metadata);
    for (PropertyDescriptor descriptor : wrapper.getPropertyDescriptors()) {
        if ("types".equals(descriptor.getName())) {
            model.put("types", removeTypes(metadata.getTypes()));
        } else {
            model.put(descriptor.getName(), wrapper.getPropertyValue(descriptor.getName()));
        }
    }

    // Google analytics support
    model.put("trackingCode", metadata.getConfiguration().getEnv().getGoogleAnalyticsTrackingCode());

}

From source file:com.lingxiang2014.template.directive.BaseDirective.java

protected List<Filter> getFilters(Map<String, TemplateModel> params, Class<?> type, String... ignoreProperties)
        throws TemplateModelException {
    List<Filter> filters = new ArrayList<Filter>();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String propertyName = propertyDescriptor.getName();
        Class<?> propertyType = propertyDescriptor.getPropertyType();
        if (!ArrayUtils.contains(ignoreProperties, propertyName) && params.containsKey(propertyName)) {
            Object value = FreemarkerUtils.getParameter(propertyName, propertyType, params);
            filters.add(Filter.eq(propertyName, value));
        }//from  w ww.ja v  a 2  s. c  om
    }
    return filters;
}

From source file:jeeves.server.overrides.AddPropertyUpdater.java

@SuppressWarnings("unchecked")
@Override/* www .  j  a va2  s.c  o m*/
protected void doUpdate(ConfigurableListableBeanFactory beanFactory, BeanDefinition bean, Object value) {
    Log.debug(Log.JEEVES, "Adding new value " + value + " to property: " + propertyName + " on " + beanName);
    PropertyValue propertyValue = bean.getPropertyValues().getPropertyValue(propertyName);
    if (propertyValue == null) {
        final String beanClassName = bean.getBeanClassName();
        try {
            final Class<?> aClass = Class.forName(beanClassName);
            final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(aClass);
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                if (propertyName.equals(descriptor.getName())) {
                    final Class<?> collectionType = descriptor.getWriteMethod().getParameterTypes()[0];
                    if (List.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedList<Object>());
                    } else if (Set.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedSet<Object>());
                    } else if (Map.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedMap<Object, Object>());
                    } else if (Properties.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedProperties());
                    } else if (Array.class.isAssignableFrom(collectionType)) {
                        throw new IllegalArgumentException("Array collections not currently supported");
                    } else if (Collection.class.isAssignableFrom(collectionType)) {
                        propertyValue = new PropertyValue(propertyName, new ManagedList<Object>());
                    } else {
                        throw new IllegalArgumentException(
                                collectionType + " is not a supported type for adding new values");
                    }
                    break;
                }
            }
            if (propertyValue == null) {
                throw new IllegalArgumentException("Unable to find the collection type for property: "
                        + propertyName + " on bean " + beanName);
            }
            bean.getPropertyValues().addPropertyValue(propertyValue);
        } catch (ClassNotFoundException e) {
            throw new AssertionError(e);
        }
    }

    Object originalValue = propertyValue.getValue();
    if (originalValue instanceof Collection) {
        Collection<Object> coll = (Collection<Object>) originalValue;
        coll.add(value);
    } else {
        throw new IllegalArgumentException(originalValue + " is not a collection as expected");
    }
}

From source file:com.easyget.commons.csv.bean.HeaderColumnNameMappingStrategy.java

/**
 * Determines if the name of a property descriptor matches the column name.
 * Currently only used by unit tests.//from ww  w  . ja  va2 s. co  m
 * @param name - name of the column.
 * @param desc - property descriptor to check against
 * @return - true if the name matches the name in the property descriptor.
 */
protected boolean matches(String name, PropertyDescriptor desc) {
    return desc.getName().equals(name.trim());
}

From source file:com.ebay.pulsar.analytics.dao.mapper.BaseDBMapper.java

@SuppressWarnings("unchecked")
@Override//from   w ww  . j  a  v  a  2s .co  m
public T mapRow(ResultSet r, int index) throws SQLException {
    try {
        T obj = (T) clazz.newInstance();
        if (obj == null) {
            return null;
        }
        try {

            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (!key.equals("class")) {
                    Object value = null;
                    try {
                        Method setter = property.getWriteMethod();
                        value = r.getObject(key.toLowerCase());
                        if (value != null && value instanceof Number) {
                            @SuppressWarnings("rawtypes")
                            Class[] types = setter.getParameterTypes();
                            value = NumberUtils.convertNumberToTargetClass((Number) value, types[0]);
                        }
                        if (value != null) {
                            if (value.getClass().equals(BigInteger.class)) {
                                setter.invoke(obj, ((BigInteger) value).longValue());
                            } else if (value.getClass().equals(byte[].class)) {
                                setter.invoke(obj, new String((byte[]) value));
                            } else if (Blob.class.isAssignableFrom(value.getClass())) {
                                Blob bv = (Blob) value;
                                byte[] b = new byte[(int) bv.length()];
                                InputStream stream = bv.getBinaryStream();
                                stream.read(b);
                                stream.close();
                                String v = new String(b);
                                setter.invoke(obj, v);
                            } else {
                                setter.invoke(obj, value);
                            }
                        }
                    } catch (Exception e) {
                        logger.error("transBean2Map Error " + e);
                        logger.error("name[" + key + "]=" + (value == null ? "NULL" : value.toString())
                                + ", class:" + (value == null ? "NULL" : value.getClass()) + ", err:"
                                + e.getMessage());
                    }

                }

            }
        } catch (Exception e) {
            logger.error("transBean2Map Error " + e);
        }
        return obj;
    } catch (Exception e) {
        logger.error("Exception:" + e);
    }

    return null;
}