List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors
public static PropertyDescriptor[] getPropertyDescriptors(Object bean)
Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.
For more details see PropertyUtilsBean
.
From source file:org.nekorp.workflow.desktop.view.model.validacion.ValidacionParticular.java
public String concatenaErrores() { try {//ww w . ja v a 2s .c o m String result = ""; for (PropertyDescriptor x : PropertyUtils.getPropertyDescriptors(this)) { if (EstatusValidacion.class.isAssignableFrom(x.getPropertyType())) { EstatusValidacion arg = (EstatusValidacion) PropertyUtils.getProperty(this, x.getName()); if (!arg.isValido()) { if (!StringUtils.isEmpty(result)) { result = result + "\n"; } result = result + arg.getDetalle(); } } } return result; } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { throw new IllegalArgumentException("No se logro evaluar", ex); } }
From source file:org.neovera.jdiablo.environment.SpringEnvironment.java
private void injectProperties(Object object) { Map<String, PropertyPlaceholderProvider> map = _context.getBeansOfType(PropertyPlaceholderProvider.class); PropertyPlaceholderProvider ppp = null; if (map.size() != 0) { ppp = map.values().iterator().next(); }/*from w w w.j a v a 2 s. c o m*/ // Analyze members to see if they are annotated. Map<String, String> propertyNamesByField = new HashMap<String, String>(); Class<?> clz = object.getClass(); while (!clz.equals(Object.class)) { for (Field field : clz.getDeclaredFields()) { if (field.isAnnotationPresent(PropertyPlaceholder.class)) { propertyNamesByField.put( field.getName().startsWith("_") ? field.getName().substring(1) : field.getName(), field.getAnnotation(PropertyPlaceholder.class).value()); } } clz = clz.getSuperclass(); } PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(object.getClass()); for (PropertyDescriptor pd : descriptors) { if (propertyNamesByField.keySet().contains(pd.getName())) { if (ppp == null) { _logger.error( "Field {} is annotated with PropertyPlaceholder but no bean of type " + "PropertyPlaceholderProvider is defined in the Spring application context.", pd.getName()); break; } else { setValue(pd, object, ppp.getProperty(propertyNamesByField.get(pd.getName()))); } } else if (pd.getReadMethod() != null && pd.getReadMethod().isAnnotationPresent(PropertyPlaceholder.class)) { if (ppp == null) { _logger.error( "Field {} is annotated with PropertyPlaceholder but no bean of type " + "PropertyPlaceholderProvider is defined in the Spring application context.", pd.getName()); break; } else { setValue(pd, object, ppp.getProperty(pd.getReadMethod().getAnnotation(PropertyPlaceholder.class).value())); } } } }
From source file:org.neovera.jdiablo.internal.BuilderImpl.java
private List<OptionPropertySpi> buildOptions(final Class<?> claz, Object instance) { List<OptionPropertySpi> list = new ArrayList<OptionPropertySpi>(); Class<?> clz = claz;//w w w .j a v a2s . c o m while (clz != null) { for (Field field : clz.getDeclaredFields()) { Option option = field.getAnnotation(Option.class); if (option != null) { String fieldName = field.getName(); if (fieldName.startsWith("_")) { fieldName = fieldName.substring(1); } Method method = BeanUtils.getWriteMethod(fieldName, clz); if (method != null) { OptionPropertySpi po = new OptionPropertyImpl(); po.setOption(option); po.setPropertyName(fieldName); po.setSetterMethod(method); list.add(po); } else { _logger.error("No setter method for " + fieldName); } } } // for (Field field : ... PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clz); for (Method method : clz.getDeclaredMethods()) { Option option = method.getAnnotation(Option.class); if (option != null) { for (PropertyDescriptor propertyDescriptor : descriptors) { if (propertyDescriptor.getReadMethod() != null && propertyDescriptor.getReadMethod().equals(method)) { String fieldName = propertyDescriptor.getName(); if (propertyDescriptor.getWriteMethod() == null) { _logger.error("No setter method for {}" + fieldName); } else { OptionPropertySpi po = new OptionPropertyImpl(); po.setOption(option); po.setPropertyName(fieldName); po.setSetterMethod(propertyDescriptor.getWriteMethod()); list.add(po); } // end else break; } } // for (PropertyDescriptor ... } } // for (Method method : ... clz = clz.getSuperclass(); } return list; }
From source file:org.obm.sync.metadata.DatabaseTruncationServiceImpl.java
@Override public <T> T getTruncatingEntity(T entity) throws SQLException { if (entity == null) { return null; }/*w ww .jav a 2 s . com*/ try { T newInstance = (T) entity.getClass().newInstance(); PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(entity.getClass()); for (PropertyDescriptor descriptor : descriptors) { Method writeMethod = descriptor.getWriteMethod(), readMethod = descriptor.getReadMethod(); if (writeMethod != null) { String propertyName = descriptor.getName(); Object value = PropertyUtils.getProperty(entity, propertyName); if (readMethod.isAnnotationPresent(DatabaseEntity.class)) { if (value instanceof Collection) { value = copyEntityCollection(value); } else if (value instanceof Map) { value = copyEntityMap(value); } else { value = copyEntity(value); } } else { DatabaseField dbField = readMethod.getAnnotation(DatabaseField.class); if (dbField != null && value instanceof String) { value = truncate((String) value, dbField.table(), dbField.column()); } } PropertyUtils.setProperty(newInstance, propertyName, value); } } return newInstance; } catch (Exception e) { Throwables.propagateIfInstanceOf(e, SQLException.class); throw Throwables.propagate(e); } }
From source file:org.oddjob.framework.WrapDynaClass.java
/** * Introspect our bean class to identify the supported properties. *//*from w w w .j av a 2 s. c o m*/ protected void introspect(Class<?> beanClass) { Set<String> mismatched = new HashSet<String>(); // first find simple and indexed properties via usual means. PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass); for (int i = 0; i < descriptors.length; ++i) { PropertyDescriptor descriptor = descriptors[i]; String propertyName = descriptor.getName(); DynaProperty dynaProperty; // indexed property? if (descriptor instanceof IndexedPropertyDescriptor) { dynaProperty = new DynaProperty(propertyName, descriptor.getPropertyType(), ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType()); } // else a simple property. else { dynaProperty = new DynaProperty(propertyName, descriptor.getPropertyType()); } propertiesMap.put(propertyName, dynaProperty); // update readable writable if (MethodUtils.getAccessibleMethod(descriptor.getReadMethod()) != null) { readableProperties.add(propertyName); } if (MethodUtils.getAccessibleMethod(descriptor.getWriteMethod()) != null) { writableProperties.add(propertyName); } } // now find mapped properties. Method[] methods = beanClass.getMethods(); for (int i = 0; i < methods.length; ++i) { Method method = methods[i]; // methods beginning with get could be properties. if (!method.getName().startsWith("get") && !method.getName().startsWith("set")) { continue; } String propertyName = method.getName().substring(3); // get on it's own is not a property if (propertyName.length() == 0) { continue; } // lowercase first letter propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); Class<?>[] args = method.getParameterTypes(); DynaProperty dynaProperty = null; boolean readable = false; boolean writable = false; // is mapped property? if (method.getName().startsWith("get") && Void.TYPE != method.getReturnType() && args.length == 1 && args[0] == String.class) { DynaProperty existing = (DynaProperty) propertiesMap.get(propertyName); if (existing != null && !existing.isMapped()) { mismatched.add(propertyName); continue; } dynaProperty = new DynaProperty(propertyName, Map.class, method.getReturnType()); readable = true; } else if (args.length == 2 && args[0] == String.class && Void.TYPE == method.getReturnType()) { DynaProperty existing = (DynaProperty) propertiesMap.get(propertyName); if (existing != null && !existing.isMapped()) { mismatched.add(propertyName); continue; } dynaProperty = new DynaProperty(propertyName, Map.class, args[1]); writable = true; } else { continue; } propertiesMap.put(propertyName, dynaProperty); // update readable writable if (readable) { readableProperties.add(propertyName); } if (writable) { writableProperties.add(propertyName); } } for (String element : mismatched) { propertiesMap.remove(element); readableProperties.remove(element); writableProperties.remove(element); } properties = (DynaProperty[]) propertiesMap.values().toArray(new DynaProperty[0]); }
From source file:org.openamf.io.AMFSerializer.java
/** * Writes Object/* w w w . j a va 2s .c o m*/ * * @param object * @throws IOException */ protected void writeObject(Object object) throws IOException { if (log.isDebugEnabled()) { if (object == null) { log.debug("Writing object, object param == null"); } else { log.debug("Writing object, class = " + object.getClass()); } } String customClassName = OpenAMFConfig.getInstance().getCustomClassName(object.getClass().getName()); if (customClassName == null) { outputStream.writeByte(AMFBody.DATA_TYPE_OBJECT); } else { if (log.isDebugEnabled()) { log.debug("customClassName : " + customClassName); } outputStream.writeByte(AMFBody.DATA_TYPE_CUSTOM_CLASS); outputStream.writeUTF(customClassName); } try { PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(object); for (int i = 0; i < properties.length; i++) { if (!properties[i].getName().equals("class")) { String propertyName = properties[i].getName(); Method readMethod = properties[i].getReadMethod(); Object propertyValue = null; if (readMethod == null) { log.error("unable to find readMethod for : " + propertyName + " writing null!"); } else { log.debug("invoking readMethod " + readMethod); propertyValue = readMethod.invoke(object, new Object[0]); } log.debug(propertyName + " = " + propertyValue); outputStream.writeUTF(propertyName); writeData(propertyValue); } } outputStream.writeShort(0); outputStream.writeByte(AMFBody.DATA_TYPE_OBJECT_END); } catch (RuntimeException e) { throw e; } catch (Exception e) { log.error(e, e); throw new IOException(e.getMessage()); } }
From source file:org.openamf.recordset.ASRecordSet.java
/** * @param list List of JavaBeans, all beans should be of the same type * @param ignoreProperties properties that should not be added to the RecordSet *//*from w ww .jav a 2 s . c om*/ public void populate(List list, String[] ignoreProperties) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { List names = new ArrayList(); Object firstBean = list.get(0); PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(firstBean); for (int i = 0; i < properties.length; i++) { PropertyDescriptor descriptor = properties[i]; if (!ignoreProperty(descriptor, ignoreProperties)) { names.add(descriptor.getDisplayName()); } } String[] columnNames = new String[names.size()]; columnNames = (String[]) names.toArray(columnNames); setColumnNames(columnNames); int rowIndex = 0; List initialData = new ArrayList(); Iterator iterator = list.iterator(); while (iterator.hasNext()) { rowIndex++; Object bean = (Object) iterator.next(); List row = new ArrayList(); for (int i = 0; i < properties.length; i++) { PropertyDescriptor descriptor = properties[i]; if (!ignoreProperty(descriptor, ignoreProperties)) { Object value = null; Method readMethod = descriptor.getReadMethod(); if (readMethod != null) { value = readMethod.invoke(bean, new Object[0]); } row.add(value); } } rows.add(row); if (rowIndex <= initialRowCount) { initialData.add(row); } } setInitialData(initialData); setTotalCount(rows.size()); log.debug(this); }
From source file:org.opencms.configuration.CmsDefaultUserSettings.java
/** * Initializes the preference configuration.<p> * * Note that this method should only be called once the resource types have been initialized, but after addPreference has been called for all configured preferences. * * @param wpManager the active workplace manager *///from w ww. j a v a 2 s .c om public void initPreferences(CmsWorkplaceManager wpManager) { CURRENT_DEFAULT_SETTINGS = this; Class<?> accessorClass = CmsUserSettingsStringPropertyWrapper.class; // first initialize all built-in preferences. these are: // a) Bean properties of CmsUserSettingsStringPropertyWrapper // b) Editor setting preferences // c) Gallery setting preferences PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(accessorClass); for (PropertyDescriptor descriptor : propDescs) { String name = descriptor.getName(); Method getter = descriptor.getReadMethod(); Method setter = descriptor.getWriteMethod(); if ((getter == null) || (setter == null)) { continue; } PrefMetadata metadata = getter.getAnnotation(PrefMetadata.class); if (metadata == null) { CmsBuiltinPreference preference = new CmsBuiltinPreference(name); m_preferences.put(preference.getName(), preference); } else { try { Constructor<?> constructor = metadata.type().getConstructor(String.class); I_CmsPreference pref = (I_CmsPreference) constructor.newInstance(name); m_preferences.put(pref.getName(), pref); } catch (Exception e) { throw new RuntimeException(e); } } } Map<String, String> editorValues = getEditorSettings(); if (wpManager.getWorkplaceEditorManager() != null) { for (String resType : wpManager.getWorkplaceEditorManager().getConfigurableEditors().keySet()) { if (!editorValues.containsKey(resType)) { editorValues.put(resType, null); } } } for (Map.Entry<String, String> editorSettingEntry : editorValues.entrySet()) { CmsEditorPreference pref = new CmsEditorPreference(editorSettingEntry.getKey(), editorSettingEntry.getValue()); m_preferences.put(pref.getName(), pref); } Map<String, String> galleryValues = new HashMap<String, String>(getStartGalleriesSettings()); for (String key : wpManager.getGalleries().keySet()) { if (!galleryValues.containsKey(key)) { galleryValues.put(key, null); } } for (Map.Entry<String, String> galleryEntry : galleryValues.entrySet()) { CmsStartGallleryPreference pref = new CmsStartGallleryPreference(galleryEntry.getKey(), galleryEntry.getValue()); m_preferences.put(pref.getName(), pref); } // Now process configured preferences. Each configuration entry is either // for a built-in preference, in which case we create a wrapper around the existing preference, // or for a custom user-defined preference. for (CmsPreferenceData prefData : m_preferenceData) { String name = prefData.getName(); I_CmsPreference pref = null; if (m_preferences.containsKey(name)) { // we first remove the existing preference, because in a LinkedHashMap, put(key, value) will not // update the position of the entry if the key already exists pref = new CmsWrapperPreference(prefData, m_preferences.remove(name)); } else { pref = new CmsUserDefinedPreference(prefData.getName(), prefData.getDefaultValue(), prefData.getPropertyDefinition(), prefData.getTab()); } m_preferences.put(pref.getName(), pref); pref.setValue(this, prefData.getDefaultValue()); } }
From source file:org.openempi.webapp.server.util.BaseModelDataDtoGenerator.java
/** * @param args/* ww w . java 2 s . c om*/ */ public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: BaseModelDataDtoGenerator <FQ-Class-Name> <Destination-Package-Name>"); System.exit(-1); } String fqClassName = args[0]; String className = extractClassName(fqClassName); String packageName = args[1]; log.debug("Generating DTO for class: " + fqClassName + " into class " + className); StringBuilder sourceCode = generateClassHeader(packageName, className); Class<?> beanClass = Class.forName(fqClassName); PropertyDescriptor[] descs = PropertyUtils.getPropertyDescriptors(beanClass); for (PropertyDescriptor desc : descs) { log.debug(desc.getName() + " of type " + desc.getPropertyType()); if (!desc.getName().equalsIgnoreCase("class") && !desc.getPropertyType().getCanonicalName().startsWith("org")) { generateGetterSetter(sourceCode, desc); } } sourceCode.append("}"); System.out.println(sourceCode.toString()); }
From source file:org.openlegacy.terminal.mvc.rest.DefaultScreensRestController.java
@Override protected ModelAndView getEntityInner(Object entity, boolean children) { if (entity == null) { logger.warn("Current screen is not recognized"); return null; }/* w w w . ja v a 2s . c o m*/ // fetch child entities ScreenEntityDefinition entityDefinition = (ScreenEntityDefinition) getEntitiesRegistry() .get(entity.getClass()); List<EntityDefinition<?>> childEntitiesDefinitions = entityDefinition.getChildEntitiesDefinitions(); if (children && childEntitiesDefinitions.size() > 0) { PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(entity); for (EntityDefinition<?> childEntityDefinition : childEntitiesDefinitions) { for (PropertyDescriptor propertyDescriptor : properties) { if (childEntityDefinition.getEntityName().equalsIgnoreCase(propertyDescriptor.getName())) { try { propertyDescriptor.getReadMethod().invoke(entity); } catch (Exception e) { logger.warn(e.getMessage()); } } } } } return super.getEntityInner(entity, children); }