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:net.sf.json.util.DynaBeanToBeanMorpher.java
/** * DOCUMENT ME!/* w w w . j a v a 2s . co m*/ * * @param value DOCUMENT ME! * * @return DOCUMENT ME! */ public Object morph(Object value) { if (value == null) { return null; } if (!supports(value.getClass())) { throw new MorphException("value is not a DynaBean"); } Object bean = null; try { bean = beanClass.newInstance(); DynaBean dynaBean = (DynaBean) value; DynaClass dynaClass = dynaBean.getDynaClass(); PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(beanClass); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; String name = pd.getName(); DynaProperty dynaProperty = dynaClass.getDynaProperty(name); if (dynaProperty != null) { Class dynaType = dynaProperty.getType(); Class type = pd.getPropertyType(); if (type.isAssignableFrom(dynaType)) { PropertyUtils.setProperty(bean, name, dynaBean.get(name)); } else { if (IdentityObjectMorpher.getInstance() == morpherRegistry.getMorpherFor(type)) { throw new MorphException("Can't find a morpher for target class " + type); } else { PropertyUtils.setProperty(bean, name, morpherRegistry.morph(type, dynaBean.get(name))); } } } } } catch (InstantiationException e) { throw new MorphException(e); } catch (IllegalAccessException e) { throw new MorphException(e); } catch (InvocationTargetException e) { throw new MorphException(e); } catch (NoSuchMethodException e) { throw new MorphException(e); } return bean; }
From source file:com.subakva.formicid.options.ParameterHandler.java
protected HashMap<String, PropertyDescriptor> getWritableProperties(Class taskClass) { HashMap<String, PropertyDescriptor> writableProperties = new HashMap<String, PropertyDescriptor>(); PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(taskClass); for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getWriteMethod() != null && !excluded.contains(descriptor.getName())) { writableProperties.put(descriptor.getName().toLowerCase(), descriptor); }/*from w w w .j a va2s.com*/ } return writableProperties; }
From source file:com.ettrema.httpclient.calsync.parse.BeanPropertyMapper.java
public void toBean(Object bean, String icalText) { VCardEngine cardEngine = new VCardEngine(); VCard vcard;//from w ww . ja v a 2 s. co m try { vcard = cardEngine.parse(icalText); } catch (IOException ex) { throw new RuntimeException(ex); } PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean); for (PropertyDescriptor pd : pds) { if (pd.getReadMethod() != null && pd.getWriteMethod() != null) { Method read = pd.getReadMethod(); Annotation[] annotations = read.getAnnotations(); for (Annotation anno : annotations) { Mapper mapper = mapOfMappers.get(anno.annotationType()); if (mapper != null) { mapper.mapToBean(vcard, bean, pd); } } } } }
From source file:com.ksmpartners.ernie.util.TestUtil.java
/** * Checks equality of two objects based on the equality of their fields, items, or .equals() method. * @param obj1/*from w w w.j a v a2s . c om*/ * @param obj2 * @return */ public static <T> boolean equal(T obj1, T obj2) { if (obj1 == null || obj2 == null) { // If they're both null, we call this equal if (obj1 == null && obj2 == null) return true; else return false; } if (!obj1.getClass().equals(obj2.getClass())) return false; if (obj1.equals(obj2)) return true; List<Pair> vals = new ArrayList<Pair>(); // If obj1 and obj2 are Collections, get the objects in them if (Collection.class.isAssignableFrom(obj1.getClass())) { Collection c1 = (Collection) obj1; Collection c2 = (Collection) obj2; if (c1.size() != c2.size()) return false; Iterator itr1 = c1.iterator(); Iterator itr2 = c2.iterator(); while (itr1.hasNext() && itr2.hasNext()) { vals.add(new Pair(itr1.next(), itr2.next())); } } // Get field values from obj1 and obj2 PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj1); for (PropertyDescriptor property : properties) { // ignore getClass() and isEmpty() if (property.getName().equals("class") || property.getName().equals("empty")) continue; Object val1 = invokeMethod(obj1, property.getReadMethod(), null, property.getName()); Object val2 = invokeMethod(obj2, property.getReadMethod(), null, property.getName()); vals.add(new Pair(val1, val2)); } if (vals.isEmpty()) return false; for (Pair pair : vals) { if (!equal(pair.left, pair.right)) return false; } return true; }
From source file:com.swingtech.commons.util.ClassUtil.java
public static Class getPropertyType(final Class clazz, final String propertyName) { PropertyDescriptor[] propertyDescriptorList = null; PropertyDescriptor propertyDescriptor = null; if (clazz == null) { throw new IllegalArgumentException("clazz is null"); }// w ww . j a v a 2s . co m if (propertyName == null) { throw new IllegalArgumentException("propertyName is null"); } propertyDescriptorList = PropertyUtils.getPropertyDescriptors(clazz); for (int i = 0; i < propertyDescriptorList.length; i++) { propertyDescriptor = propertyDescriptorList[i]; if (propertyDescriptor.getName().equalsIgnoreCase(propertyName)) { return propertyDescriptor.getPropertyType(); } } return null; }
From source file:jp.go.nict.langrid.p2pgridbasis.data.langrid.converter.ConvertUtil.java
static public DataAttributes encode(Object data) throws DataConvertException { setLangridConverter();//from www.j av a 2 s. com logger.debug("##### encode #####"); try { DataAttributes attr = new DataAttributes(); for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(data)) { if (PropertyUtils.isReadable(data, descriptor.getName())) { if (descriptor.getName().equalsIgnoreCase("supportedLanguages")) { //supportedLanguages attr.setAttribute(descriptor.getName(), (String) converter.lookup(descriptor.getPropertyType()).convert(String.class, PropertyUtils.getProperty(data, descriptor.getName()))); continue; } else if (descriptor.getName().equalsIgnoreCase("instance")) { // // continue; } else if (descriptor.getName().equalsIgnoreCase("wsdl")) { // // continue; } else if (descriptor.getName().equalsIgnoreCase("interfaceDefinitions")) { // // ServiceType type = (ServiceType) data; Map<String, ServiceInterfaceDefinition> map = new HashMap<String, ServiceInterfaceDefinition>(); map = type.getInterfaceDefinitions(); String str = ""; try { for (ServiceInterfaceDefinition s : map.values()) { str = str + "ProtocolId=" + s.getProtocolId() + "\n"; str = str + "Definition=" + Base64.encode(StreamUtil.readAsBytes(s.getDefinition().getBinaryStream())) + "\n"; str = str + "###ServiceInterfaceDefinition###\n"; } } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } attr.setAttribute("interfaceDefinition_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("allowedAppProvision")) { Service s = (Service) data; String value = ""; for (String str : s.getAllowedAppProvision()) { value = value + str + "\n"; } attr.setAttribute("allowedAppProvision", value); continue; } else if (descriptor.getName().equalsIgnoreCase("allowedUse")) { Service s = (Service) data; String value = ""; for (String str : s.getAllowedUse()) { value = value + str + "\n"; } attr.setAttribute("allowedUse", value); continue; } else if (descriptor.getName().equalsIgnoreCase("supportedDomains")) { Grid g = (Grid) data; List<Domain> list = g.getSupportedDomains(); String value = ""; for (Domain d : list) { value = value + d.getDomainId() + "\n"; } attr.setAttribute("supportedDomain_list", value); continue; } else if (descriptor.getName().equalsIgnoreCase("partnerServiceNamespaceURIs")) { //partnerServiceNamespaceURIs BPELService s = (BPELService) data; List<String> list = s.getPartnerServiceNamespaceURIs(); String value = ""; for (String str : list) { value = value + str + "\n"; } attr.setAttribute("partnerServiceNamespaceURI_list", value); continue; } else if (descriptor.getName().equalsIgnoreCase("serviceDeployments")) { //ServiceDeployment Service s = (Service) data; String str = ""; for (ServiceDeployment sd : s.getServiceDeployments()) { str = str + "GridId=" + sd.getGridId() + "\n"; str = str + "ServiceId=" + sd.getServiceId() + "\n"; str = str + "NodeId=" + sd.getNodeId() + "\n"; str = str + "ServicePath=" + sd.getServicePath() + "\n"; str = str + "Enabled=" + String.valueOf(sd.isEnabled()) + "\n"; str = str + "CreateTime=" + String.valueOf(sd.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "UpdateTime=" + String.valueOf(sd.getUpdatedDateTime().getTimeInMillis()) + "\n"; if (sd.getDisabledByErrorDate() != null) { str = str + "ErrorDate=" + String.valueOf(sd.getDisabledByErrorDate().getTimeInMillis()) + "\n"; } if (sd.getDeployedDateTime() != null) { str = str + "DeployedTime=" + String.valueOf(sd.getDeployedDateTime().getTimeInMillis()) + "\n"; } str = str + "###ServiceDeployment###\n"; } attr.setAttribute("deployment_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("serviceEndpoints")) { //ServiceEndpoint StringBuilder str = new StringBuilder(); Service s = (Service) data; for (ServiceEndpoint se : s.getServiceEndpoints()) { str.append("GridId=" + se.getGridId() + "\n"); str.append("ProtocolId=" + se.getProtocolId() + "\n"); str.append("ServiceId=" + se.getServiceId() + "\n"); str.append("Enabled=" + String.valueOf(se.isEnabled()) + "\n"); str.append("Url=" + se.getUrl().toString() + "\n"); str.append("AuthUserName=" + se.getAuthUserName() + "\n"); str.append("AuthPassword=" + se.getAuthPassword() + "\n"); str.append("DisableReason=" + se.getDisableReason() + "\n"); str.append("CreateTime=" + String.valueOf(se.getCreatedDateTime().getTimeInMillis()) + "\n"); str.append("UpdateTime=" + String.valueOf(se.getUpdatedDateTime().getTimeInMillis()) + "\n"); if (se.getDisabledByErrorDate() != null) { str.append("ErrorDate=" + String.valueOf(se.getDisabledByErrorDate().getTimeInMillis()) + "\n"); } str.append("###ServiceEndpoint###\n"); } attr.setAttribute("endpoint_list", str.toString()); continue; } else if (descriptor.getName().equalsIgnoreCase("invocations")) { //Invocation String str = ""; Service s = (Service) data; for (Invocation in : s.getInvocations()) { str = str + "InvocationName=" + in.getInvocationName() + "\n"; str = str + "OwnerServiceGridId=" + in.getOwnerServiceGridId() + "\n"; str = str + "OwnerServiceId=" + in.getOwnerServiceId() + "\n"; str = str + "ServiceGridId=" + in.getServiceGridId() + "\n"; str = str + "ServiceId=" + in.getServiceId() + "\n"; str = str + "ServiceName=" + in.getServiceName() + "\n"; str = str + "CreateTime=" + String.valueOf(in.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "UpdateTime=" + String.valueOf(in.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Invocation###\n"; } attr.setAttribute("invocations_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("metaAttributes")) { //metaAttributes String str = ""; if (data.getClass().getName().endsWith("ResourceType")) { ResourceType r = (ResourceType) data; for (ResourceMetaAttribute a : r.getMetaAttributes().values()) { str = str + "DomainId=" + a.getDomainId() + "\n"; str = str + "AttributeId=" + a.getAttributeId() + "\n"; str = str + "###MetaAttribute###\n"; } } else if (data.getClass().getName().endsWith("ServiceType")) { ServiceType s = (ServiceType) data; for (ServiceMetaAttribute a : s.getMetaAttributes().values()) { str = str + "DomainId=" + a.getDomainId() + "\n"; str = str + "AttributeId=" + a.getAttributeId() + "\n"; str = str + "###MetaAttribute###\n"; } } else { logger.info("metaAttributes : " + data.getClass().getName()); } attr.setAttribute("metaAttribute_list", str); continue; } else if (descriptor.getName().equalsIgnoreCase("attributes")) { //attribute String str = ""; if (data.getClass().getName().endsWith("User")) { User u = (User) data; for (UserAttribute a : u.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getUserId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Service")) { Service s = (Service) data; for (ServiceAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getServiceId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Node")) { Node s = (Node) data; for (NodeAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getNodeId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Grid")) { Grid s = (Grid) data; for (GridAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } else if (data.getClass().getName().endsWith("Resource")) { Resource s = (Resource) data; for (ResourceAttribute a : s.getAttributes()) { str = str + "attribute_GridId=" + a.getGridId() + "\n"; str = str + "attribute_Id=" + a.getResourceId() + "\n"; str = str + "attribute_Name=" + a.getName() + "\n"; str = str + "attribute_Value=" + a.getValue() + "\n"; str = str + "attribute_CreateTime=" + String.valueOf(a.getCreatedDateTime().getTimeInMillis()) + "\n"; str = str + "attribute_UpdateTime=" + String.valueOf(a.getUpdatedDateTime().getTimeInMillis()) + "\n"; str = str + "###Attribute###\n"; } } attr.setAttribute("attribute_list", str); continue; } else if (data instanceof Service && (descriptor.getName().equals("alternateServiceId") || descriptor.getName().equals("useAlternateServices"))) { // // continue; } //Read OK if (data instanceof BPELService && descriptor.getName().equals("transferExecution")) { // ignore } else { attr.setAttribute(descriptor.getName(), BeanUtils.getProperty(data, descriptor.getName())); } } else if (descriptor.getPropertyType().isArray()) { logger.debug("name : " + descriptor.getName() + " isArray"); // // attr.setAttribute(descriptor.getName(), (String) converter.lookup(descriptor.getPropertyType()) .convert(String.class, PropertyUtils.getProperty(data, descriptor.getName()))); } else { logger.debug("Name : " + descriptor.getName()); for (Method m : data.getClass().getMethods()) { if (m.getName().equalsIgnoreCase("get" + descriptor.getName()) || m.getName().equalsIgnoreCase("is" + descriptor.getName())) { if (m.getParameterTypes().length != 0) { // // logger.debug("class : " + data.getClass().getName()); logger.debug("?:Skip"); break; } else { // // logger.debug("value : " + m.invoke(data)); } attr.setAttribute(descriptor.getName(), m.invoke(data).toString()); break; } } } } return attr; } catch (InvocationTargetException e) { throw new DataConvertException(e); } catch (IllegalArgumentException e) { throw new DataConvertException(e); } catch (IllegalAccessException e) { throw new DataConvertException(e); } catch (NoSuchMethodException e) { throw new DataConvertException(e); } }
From source file:info.magnolia.jcr.node2bean.impl.TypeMappingImpl.java
@Override public PropertyTypeDescriptor getPropertyTypeDescriptor(Class<?> beanClass, String propName) { PropertyTypeDescriptor dscr = null;/* ww w . j ava 2s. c o m*/ String key = beanClass.getName() + "." + propName; dscr = propertyTypes.get(key); if (dscr != null) { return dscr; } dscr = new PropertyTypeDescriptor(); dscr.setName(propName); PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass); Method writeMethod = null; for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getName().equals(propName)) { // may be null for indexed properties Class<?> propertyType = descriptor.getPropertyType(); writeMethod = descriptor.getWriteMethod(); if (propertyType != null) { dscr.setType(getTypeDescriptor(propertyType, writeMethod)); } // set write method dscr.setWriteMethod(writeMethod); // set add method int numberOfParameters = dscr.isMap() ? 2 : 1; dscr.setAddMethod(getAddMethod(beanClass, propName, numberOfParameters)); break; } } if (dscr.getType() != null) { // we have discovered type for property if (dscr.isMap() || dscr.isCollection()) { List<Class<?>> parameterTypes = new ArrayList<Class<?>>(); // this will contain collection types (for map key/value type, for collection value type) if (dscr.getWriteMethod() != null) { parameterTypes = inferGenericTypes(dscr.getWriteMethod()); } if (dscr.getAddMethod() != null && parameterTypes.size() == 0) { // here we know we don't have setter or setter doesn't have parameterized type // but we have add method so we take parameters from it parameterTypes = Arrays.asList(dscr.getAddMethod().getParameterTypes()); // rather set it to null because when we are here we will use add method dscr.setWriteMethod(null); } if (parameterTypes.size() > 0) { // we resolved types if (dscr.isMap()) { dscr.setCollectionKeyType(getTypeDescriptor(parameterTypes.get(0))); dscr.setCollectionEntryType(getTypeDescriptor(parameterTypes.get(1))); } else { // collection dscr.setCollectionEntryType(getTypeDescriptor(parameterTypes.get(0))); } } } else if (dscr.isArray()) { // for arrays we don't need to discover its parameter from set/add method // we just take it via Class#getComponentType() method dscr.setCollectionEntryType(getTypeDescriptor(dscr.getType().getType().getComponentType())); } } propertyTypes.put(key, dscr); return dscr; }
From source file:ca.sqlpower.matchmaker.swingui.SaveAndOpenWorkspaceActionTest.java
/** * Takes two SPObjects and recursively determines if all persistable properties * are equal. This is used in testing before-states and after-states for * persistence tests./*from w w w . j a v a2 s.co m*/ */ private boolean checkEquality(SPObject spo1, SPObject spo2) { try { Set<String> s = TestUtils.findPersistableBeanProperties(spo1, false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(spo1.getClass())); for (PropertyDescriptor property : settableProperties) { @SuppressWarnings("unused") Object oldVal; if (!s.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. if (property.getName().equals("session")) continue; if (property.getName().equals("type")) continue; try { oldVal = PropertyUtils.getSimpleProperty(spo1, property.getName()); // check for a getter if (property.getReadMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + spo1.getClass().getName()); continue; } Object spo1Property = PropertyUtils.getSimpleProperty(spo1, property.getName()); Object spo2Property = PropertyUtils.getSimpleProperty(spo2, property.getName()); assertEquals("Failed to equate " + property.getName() + " on object of type " + spo1.getClass(), spo1Property, spo2Property); } } catch (Exception e) { throw new RuntimeException(e); } // look at children Iterator<? extends SPObject> i = (spo1.getChildren().iterator()); Iterator<? extends SPObject> j = (spo2.getChildren().iterator()); while (i.hasNext() && j.hasNext()) { SPObject ii = i.next(); SPObject jj = j.next(); logger.debug("Comparing: " + ii.getClass().getSimpleName() + "," + jj.getClass().getSimpleName()); checkEquality(ii, jj); } return (!(i.hasNext() || j.hasNext())); }
From source file:com.alibaba.stonelab.toolkit.sqltester.BeanInitBuilder.java
/** * <pre>//from w ww . java 2s . c o m * build logic * TODO: * 1.?, * 2.JDK Enum? * * </pre> * * @param count * @return */ private List<T> doBuild(int count) { List<T> ret = new ArrayList<T>(); for (int i = 0; i < count; i++) { T t = null; try { t = clz.newInstance(); } catch (Exception e) { throw new BuildException("new instance error.", e); } PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clz); for (PropertyDescriptor des : descriptors) { try { // ? if (Number.class.isAssignableFrom(des.getPropertyType())) { PropertyUtils.setProperty(t, des.getName(), DEFAULT_VALUE_NUMBER.get(des.getPropertyType())); } // String? if (String.class.isAssignableFrom(des.getPropertyType())) { if (count == 1) { PropertyUtils.setProperty(t, des.getName(), des.getName()); } else { PropertyUtils.setProperty(t, des.getName(), des.getName() + i); } } // date? if (Date.class.isAssignableFrom(des.getPropertyType())) { PropertyUtils.setProperty(t, des.getName(), DEFAULT_VALUE_DATE); } // JDK? if (Enum.class.isAssignableFrom(des.getPropertyType())) { if (des.getPropertyType().getEnumConstants().length >= 1) { PropertyUtils.setProperty(t, des.getName(), des.getPropertyType().getEnumConstants()[0]); } } } catch (Exception e) { throw new BuildException("build error.", e); } } // ret.add(t); } return ret; }
From source file:com.qccr.livtrip.web.template.BaseDirective.java
/** * ?/*w w w. ja v a 2 s. co m*/ * * @param params * ? * @param type * ? * @param ignoreProperties * * @return */ 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)); } } return filters; }