List of usage examples for org.springframework.beans BeanUtils getPropertyDescriptors
public static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz) throws BeansException
From source file:org.grails.datastore.mapping.reflect.ReflectionUtils.java
/** * Retrieves all the properties of the given class for the given type * * @param clazz The class to retrieve the properties from * @param propertyType The type of the properties you wish to retrieve * * @return An array of PropertyDescriptor instances *///w w w .j av a2 s . c o m public static PropertyDescriptor[] getPropertiesOfType(Class<?> clazz, Class<?> propertyType) { if (clazz == null || propertyType == null) { return new PropertyDescriptor[0]; } Set<PropertyDescriptor> properties = new HashSet<PropertyDescriptor>(); try { for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(clazz)) { Class<?> currentPropertyType = descriptor.getPropertyType(); if (isTypeInstanceOfPropertyType(propertyType, currentPropertyType)) { properties.add(descriptor); } } } catch (Exception e) { // if there are any errors in instantiating just return null for the moment return new PropertyDescriptor[0]; } return properties.toArray(new PropertyDescriptor[properties.size()]); }
From source file:org.jdal.vaadin.data.ContainerDataSource.java
/** * {@inheritDoc}//from ww w . j a va 2 s . c o m */ public Collection<?> getSortableContainerPropertyIds() { if (sortableProperties != null) return sortableProperties; if (entityClass != null) { List<String> properties = new LinkedList<String>(); PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(entityClass); for (PropertyDescriptor pd : pds) properties.add(pd.getName()); return properties; } // if we have data will try introspection if (page.getData().size() > 0) { BeanItem<T> item = items.get(0); return item.getItemPropertyIds(); } return new LinkedList<Object>(); }
From source file:com.expedia.seiso.domain.entity.ItemTests.java
private void exerciseAccessors(Object item, Class<?> itemClass) throws IllegalAccessException, InvocationTargetException { log.trace("Exercising accessors: entityClass={}", itemClass.getName()); val descs = BeanUtils.getPropertyDescriptors(itemClass); for (val desc : descs) { val propName = desc.getName(); if ("class".equals(propName)) { continue; }/*w ww.ja va 2 s.co m*/ log.trace("Testing property: {}.{}", itemClass.getSimpleName(), propName); Method reader = desc.getReadMethod(); Object value = reader.invoke(item); Method writer = desc.getWriteMethod(); if (writer != null) { writer.invoke(item, value); } } }
From source file:org.jnap.core.persistence.hsearch.FullTextDaoSupport.java
protected String[] getIndexedFields() { if (this.indexedFields == null) { PropertyDescriptor[] beanProperties = BeanUtils.getPropertyDescriptors(getEntityClass()); List<String> fields = new ArrayList<String>(); for (PropertyDescriptor propertyDescriptor : beanProperties) { Field field = AnnotationUtils.findAnnotation(propertyDescriptor.getReadMethod(), Field.class); if (field == null) { java.lang.reflect.Field propertyField = FieldUtils.getField(getEntityClass(), propertyDescriptor.getName(), true); if (propertyField != null && propertyField.isAnnotationPresent(Field.class)) { field = propertyField.getAnnotation(Field.class); }//from w w w . j a v a 2 s . co m } if (field != null) { fields.add(propertyDescriptor.getName()); } } if (fields.isEmpty()) { throw new HSearchQueryException(""); // TODO ex msg } this.indexedFields = fields.toArray(new String[] {}); } return this.indexedFields; }
From source file:org.codehaus.griffon.commons.ClassPropertyFetcher.java
private void init() { FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() { public void doWith(Field field) { if (field.isSynthetic()) return; final int modifiers = field.getModifiers(); if (!Modifier.isPublic(modifiers)) return; final String name = field.getName(); if (name.indexOf('$') == -1) { boolean staticField = Modifier.isStatic(modifiers); if (staticField) { staticFetchers.put(name, new FieldReaderFetcher(field, staticField)); } else { instanceFetchers.put(name, new FieldReaderFetcher(field, staticField)); }//from w w w. j a v a2s . c om } } }; MethodCallback methodCallback = new ReflectionUtils.MethodCallback() { public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { if (method.isSynthetic()) return; if (!Modifier.isPublic(method.getModifiers())) return; if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) { if (method.getParameterTypes().length == 0) { String name = method.getName(); if (name.indexOf('$') == -1) { if (name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3))) { name = name.substring(3); } else if (name.length() > 2 && name.startsWith("is") && Character.isUpperCase(name.charAt(2)) && (method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class)) { name = name.substring(2); } PropertyFetcher fetcher = new GetterPropertyFetcher(method, true); staticFetchers.put(name, fetcher); staticFetchers.put(StringUtils.uncapitalize(name), fetcher); } } } } }; List<Class<?>> allClasses = resolveAllClasses(clazz); for (Class<?> c : allClasses) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { try { fieldCallback.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access field '" + field.getName() + "': " + ex); } } Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { try { methodCallback.doWith(method); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access method '" + method.getName() + "': " + ex); } } } propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor desc : propertyDescriptors) { Method readMethod = desc.getReadMethod(); if (readMethod != null) { boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers()); if (staticReadMethod) { staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } else { instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } } } }
From source file:com.glaf.core.util.Tools.java
@SuppressWarnings("unchecked") public static void populate(Object model, Map<String, Object> dataMap) { if (model instanceof Map) { Map<String, Object> map = (Map<String, Object>) model; Set<Entry<String, Object>> entrySet = map.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); if (dataMap.containsKey(key)) { map.put(key, dataMap.get(key)); }/* w w w .j a v a2 s . com*/ } } else { PropertyDescriptor[] propertyDescriptor = BeanUtils.getPropertyDescriptors(model.getClass()); for (int i = 0; i < propertyDescriptor.length; i++) { PropertyDescriptor descriptor = propertyDescriptor[i]; String propertyName = descriptor.getName(); if (propertyName.equalsIgnoreCase("class")) { continue; } String value = null; Object x = null; Object object = dataMap.get(propertyName); if (object != null && object instanceof String) { value = (String) object; } try { Class<?> clazz = descriptor.getPropertyType(); if (value != null) { x = getValue(clazz, value); } else { x = object; } if (x != null) { // PropertyUtils.setProperty(model, propertyName, x); ReflectUtils.setFieldValue(model, propertyName, x); } } catch (Exception ex) { logger.debug(ex); } } } }
From source file:com.nway.spring.jdbc.bean.AsmBeanProcessor.java
/** * Creates a new object and initializes its fields from the ResultSet. * * @param <T> The type of bean to create * @param rs The result set.//from w w w. j av a 2s. co m * @param type The bean type (the return type of the object). * @param props The property descriptors. * @param columnToProperty The column indices in the result set. * @return An initialized object. * @throws SQLException if a database error occurs. */ private <T> T createBeanByASM(ResultSet rs, Class<T> mappedClass, String key) throws SQLException { DbBeanFactory dynamicRse = DBBEANFACTORY_CACHE.get(key); // if (dynamicRse != null) { return dynamicRse.createBean(rs, mappedClass); } T bean = this.newInstance(mappedClass); ResultSetMetaData rsmd = rs.getMetaData(); MethodVisitor mv = null; final ClassWriter cw = new ClassWriter(0); PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(mappedClass); int[] columnToProperty = this.mapColumnsToProperties(rsmd, props); String beanName = mappedClass.getName().replace('.', '/'); String processorName = DynamicClassUtils.getBeanProcessorName(mappedClass); String internalProcessorName = processorName.replace('.', '/'); Object[] labelArr = prepScript(cw, mv, internalProcessorName, beanName); mv = (MethodVisitor) labelArr[1]; Label firstLabel = null; PropertyDescriptor desc = null; for (int i = 1; i < columnToProperty.length; i++) { if (columnToProperty[i] == PROPERTY_NOT_FOUND) { continue; } desc = props[columnToProperty[i]]; Class<?> propType = desc.getPropertyType(); if (null == firstLabel) { firstLabel = firstLabel(mv, beanName, 12); } else { visitLabel(mv, 11 + i); } // rs.getXXX Object value = processColumn(rs, i, propType, desc.getWriteMethod().getName(), internalProcessorName, beanName, mv); this.callSetter(bean, desc, value); } if (firstLabel != null) { endScript(mv, (Label) labelArr[0], firstLabel, 12 + columnToProperty.length, internalProcessorName, beanName); cw.visitEnd(); try { DynamicBeanClassLoader beanClassLoader = new DynamicBeanClassLoader( ClassUtils.getDefaultClassLoader()); Class<?> processor = beanClassLoader.defineClass(processorName, cw.toByteArray()); DBBEANFACTORY_CACHE.put(key, (DbBeanFactory) processor.newInstance()); } catch (Exception e) { throw new DynamicObjectException("ASM [ " + processorName + " ] ", e); } } return bean; }
From source file:dhbw.ka.mwi.businesshorizon2.ui.process.period.input.AbstractInputPresenter.java
/** * Sorgt dafuer, dass aenderungen in das Periodenobjekt geschrieben werden. * ueberprueft die Benutzereingabe auf ihre Konvertierbarkeit in eine * Doublevariable und gibt im Fehlerfall eine Fehlermeldung an den User * zurueck.//from w w w. j a v a 2 s. co m * * @param newContent * Inhalt des Textfeldes das in das Periodenobjekt geschrieben * werden soll * @param textFieldColumn * Spalte des GridLayouts wo das Textfeld liegt * @param textFieldRow * Reihe des GridLayouts wo das Textfeld liegt * @param destination * Name der Property in welche newContent geschrieben werden soll */ public void validateChange(String newContent, int textFieldColumn, int textFieldRow, String destination) { destination = shownProperties[Arrays.asList(germanNamesProperties).indexOf(destination)]; logger.debug("" + newContent); try { df.parse(newContent).doubleValue(); df.parse(newContent).doubleValue(); } catch (Exception e) { getView().setWrong(textFieldColumn, textFieldRow, true); return; } getView().setWrong(textFieldColumn, textFieldRow, false); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(period.getClass())) { if (Arrays.asList(shownProperties).contains(destination)) { if (pd.getDisplayName().equals(destination)) { try { pd.getWriteMethod(); period.toString(); pd.getWriteMethod().invoke(period, new Object[] { df.parse(newContent).doubleValue() }); logger.debug("Content should be written: " + (double) pd.getReadMethod().invoke(period)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | ParseException e) { e.printStackTrace(); } } } } }
From source file:org.kmnet.com.fw.web.el.Functions.java
/** * build query string from map or bean./* ww w . j a v a 2 s . co m*/ * <p> * query string is encoded with "UTF-8". * </p> * @param params map or bean * @return query string. returns empty string if <code>params</code> is <code>null</code> or empty string or * {@link Iterable} or {@link BeanUtils#isSimpleValueType(Class)}. */ @SuppressWarnings("unchecked") public static String query(Object params) { if (params == null) { return ""; } Class<?> clazz = params.getClass(); if (clazz.isArray() || params instanceof Iterable || BeanUtils.isSimpleValueType(clazz)) { return ""; } String query; if (params instanceof Map) { query = mapToQuery((Map<String, Object>) params); } else { Map<String, Object> map = new LinkedHashMap<String, Object>(); BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(params); PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor pd : pds) { String name = pd.getName(); if (!"class".equals(name)) { Object value = beanWrapper.getPropertyValue(name); map.put(name, value); } } query = mapToQuery(map, beanWrapper); } return query; }
From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java
/** * Constructs an attribute model for a property * //from w w w.java 2s. c o m * @param descriptor * the property descriptor * @param entityModel * the entity model * @param parentClass * the type of the direct parent of the attribute (relevant in case of embedded * attributes) * @param nested * whether this is a nested attribute * @param prefix * the prefix to apply to the attribute name * @return */ private <T> List<AttributeModel> constructAttributeModel(PropertyDescriptor descriptor, EntityModelImpl<T> entityModel, Class<?> parentClass, boolean nested, String prefix) { List<AttributeModel> result = new ArrayList<AttributeModel>(); // validation methods annotated with @AssertTrue or @AssertFalse have to // be ignored String fieldName = descriptor.getName(); AssertTrue assertTrue = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, AssertTrue.class); AssertFalse assertFalse = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, AssertFalse.class); if (assertTrue == null && assertFalse == null) { AttributeModelImpl model = new AttributeModelImpl(); model.setEntityModel(entityModel); String displayName = DefaultFieldFactory.createCaptionByPropertyId(fieldName); // first, set the defaults model.setDisplayName(displayName); model.setDescription(displayName); model.setPrompt(displayName); model.setMainAttribute(descriptor.isPreferred()); model.setSearchable(descriptor.isPreferred()); model.setName((prefix == null ? "" : (prefix + ".")) + fieldName); model.setImage(false); model.setReadOnly(descriptor.isHidden()); model.setSortable(true); model.setComplexEditable(false); model.setPrecision(SystemPropertyUtils.getDefaultDecimalPrecision()); model.setSearchCaseSensitive(false); model.setSearchPrefixOnly(false); model.setUrl(false); model.setUseThousandsGrouping(true); Id idAttr = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, Id.class); if (idAttr != null) { entityModel.setIdAttributeModel(model); // the ID column is hidden. details collections are also hidden // by default model.setVisible(false); } else { model.setVisible(true); } model.setType(descriptor.getPropertyType()); // determine the possible date type model.setDateType(determineDateType(model.getType(), entityModel.getEntityClass(), fieldName)); // determine default display format model.setDisplayFormat(determineDefaultDisplayFormat(model.getType(), entityModel.getEntityClass(), fieldName, model.getDateType())); // determine if the attribute is required based on the @NotNull // annotation NotNull notNull = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, NotNull.class); model.setRequired(notNull != null); model.setAttributeType(determineAttributeType(parentClass, model)); // minimum and maximum length based on the @Size annotation Size size = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, Size.class); if (AttributeType.BASIC.equals(model.getAttributeType()) && size != null) { model.setMaxLength(size.max()); model.setMinLength(size.min()); } setNestedEntityModel(model); // only basic attributes are shown in the table by default model.setVisibleInTable( !nested && model.isVisible() && (AttributeType.BASIC.equals(model.getAttributeType()))); if (getMessageService() != null) { model.setTrueRepresentation(getMessageService().getMessage("ocs.true")); model.setFalseRepresentation(getMessageService().getMessage("ocs.false")); } // by default, use a combo box to look up model.setSelectMode(AttributeSelectMode.COMBO); model.setTextFieldMode(AttributeTextFieldMode.TEXTFIELD); model.setSearchSelectMode(AttributeSelectMode.COMBO); // is the field an email field? Email email = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, Email.class); model.setEmail(email != null); // override the defaults with annotation values setAnnotationOverrides(parentClass, model, descriptor, nested); // override any earlier version with message bundle contents setMessageBundleOverrides(entityModel, model); if (!model.isEmbedded()) { result.add(model); } else { // an embedded object is not directly added. Instead, its child // properties are added as attributes if (model.getType().equals(entityModel.getEntityClass())) { throw new IllegalStateException("Embedding a class in itself is not allowed"); } PropertyDescriptor[] embeddedDescriptors = BeanUtils.getPropertyDescriptors(model.getType()); for (PropertyDescriptor embeddedDescriptor : embeddedDescriptors) { String name = embeddedDescriptor.getName(); if (!skipAttribute(name)) { List<AttributeModel> embeddedModels = constructAttributeModel(embeddedDescriptor, entityModel, model.getType(), nested, model.getName()); result.addAll(embeddedModels); } } } } return result; }