List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:com.xwtec.xwserver.util.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *//*from w w w . j a va2 s.c o m*/ public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) { if (jsonObject == null || jsonObject.isNullObject() || root == null) { return root; } Class rootClass = root.getClass(); if (rootClass.isInterface()) { throw new JSONException("Root bean is an interface. " + rootClass); } Map classMap = jsonConfig.getClassMap(); if (classMap == null) { classMap = Collections.EMPTY_MAP; } Map props = JSONUtils.getProperties(jsonObject); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) { String name = (String) entries.next(); Class type = (Class) props.get(name); Object value = jsonObject.get(name); if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) { continue; } String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig); try { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key); if (pd != null && pd.getWriteMethod() == null) { log.info("Property '" + key + "' of " + root.getClass() + " has no write method. SKIPPED."); continue; } if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig); setProperty(root, key, list, jsonConfig); } else { Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType()); Class targetInnerType = findTargetClass(key, classMap); if (innerType.equals(Object.class) && targetInnerType != null && !targetInnerType.equals(Object.class)) { innerType = targetInnerType; } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null); Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig); if (innerType.isPrimitive() || JSONUtils.isNumber(innerType) || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) { array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } else if (!array.getClass().equals(pd.getPropertyType())) { if (!pd.getPropertyType().equals(Object.class)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(Array.newInstance(innerType, 0).getClass()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher( new BeanMorpher(innerType, JSONUtils.getMorpherRegistry())); JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher); } array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } } setProperty(root, key, array, jsonConfig); } } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(root, key, null, jsonConfig); } else if (!pd.getPropertyType().isInstance(value)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(pd.getPropertyType()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { log.warn("Can't transform property '" + key + "' from " + type.getName() + " into " + pd.getPropertyType().getName() + ". Will register a default BeanMorpher"); JSONUtils.getMorpherRegistry().registerMorpher( new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry())); } setProperty(root, key, JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value), jsonConfig); } else { setProperty(root, key, value, jsonConfig); } } else if (root instanceof Map) { setProperty(root, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + root.getClass().getName()); } } else { if (pd != null) { Class targetClass = pd.getPropertyType(); if (jsonConfig.isHandleJettisonSingleElementArray()) { JSONArray array = new JSONArray().element(value, jsonConfig); Class newTargetClass = findTargetClass(key, classMap); newTargetClass = newTargetClass == null ? findTargetClass(name, classMap) : newTargetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass, null); if (targetClass.isArray()) { setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig), jsonConfig); } else if (Collection.class.isAssignableFrom(targetClass)) { setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig), jsonConfig); } else if (JSONArray.class.isAssignableFrom(targetClass)) { setProperty(root, key, array, jsonConfig); } else { setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else { if (targetClass == Object.class) { targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else if (root instanceof Map) { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + rootClass.getName()); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(root, key, null, jsonConfig); } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type " + type, e); } } return root; }
From source file:net.sf.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *///from ww w.ja v a 2s . c o m public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) { if (jsonObject == null || jsonObject.isNullObject()) { return null; } Class beanClass = jsonConfig.getRootClass(); Map classMap = jsonConfig.getClassMap(); if (beanClass == null) { return toBean(jsonObject); } if (classMap == null) { classMap = Collections.EMPTY_MAP; } Object bean = null; try { if (beanClass.isInterface()) { if (!Map.class.isAssignableFrom(beanClass)) { throw new JSONException("beanClass is an interface. " + beanClass); } else { bean = new HashMap(); } } else { bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject); } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException(e); } Map props = JSONUtils.getProperties(jsonObject); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) { String name = (String) entries.next(); Class type = (Class) props.get(name); Object value = jsonObject.get(name); if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) { continue; } String key = Map.class.isAssignableFrom(beanClass) && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name : JSONUtils.convertToJavaIdentifier(name, jsonConfig); PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass); if (propertyNameProcessor != null) { key = propertyNameProcessor.processPropertyName(beanClass, key); } try { if (Map.class.isAssignableFrom(beanClass)) { // no type info available for conversion if (JSONUtils.isNull(value)) { setProperty(bean, key, value, jsonConfig); } else if (value instanceof JSONArray) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, List.class), jsonConfig); } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(bean, key, null, jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } else { Class targetClass = resolveClass(classMap, key, name, type); JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(targetClass); jsc.setClassMap(classMap); if (targetClass != null) { setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } else { setProperty(bean, key, toBean((JSONObject) value), jsonConfig); } } } else { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key); if (pd != null && pd.getWriteMethod() == null) { log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED."); continue; } if (pd != null) { Class targetType = pd.getPropertyType(); if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { if (List.class.isAssignableFrom(pd.getPropertyType())) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, pd.getPropertyType()), jsonConfig); } else if (Set.class.isAssignableFrom(pd.getPropertyType())) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, pd.getPropertyType()), jsonConfig); } else { setProperty(bean, key, convertPropertyValueToArray(key, value, targetType, jsonConfig, classMap), jsonConfig); } } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(bean, key, null, jsonConfig); } else if (!targetType.isInstance(value)) { setProperty(bean, key, morphPropertyValue(key, value, type, targetType), jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } else if (beanClass == null || bean instanceof Map) { setProperty(bean, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass().getName()); } } else { if (jsonConfig.isHandleJettisonSingleElementArray()) { JSONArray array = new JSONArray().element(value, jsonConfig); Class newTargetClass = resolveClass(classMap, key, name, type); JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(newTargetClass); jsc.setClassMap(classMap); if (targetType.isArray()) { setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig); } else if (JSONArray.class.isAssignableFrom(targetType)) { setProperty(bean, key, array, jsonConfig); } else if (List.class.isAssignableFrom(targetType) || Set.class.isAssignableFrom(targetType)) { jsc.setCollectionType(targetType); setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig); } else { setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } } else { if (targetType == Object.class || targetType.isInterface()) { Class targetTypeCopy = targetType; targetType = findTargetClass(key, classMap); targetType = targetType == null ? findTargetClass(name, classMap) : targetType; targetType = targetType == null && targetTypeCopy.isInterface() ? targetTypeCopy : targetType; } JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(targetType); jsc.setClassMap(classMap); setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(bean, key, null, jsonConfig); } } } else { if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, List.class), jsonConfig); } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (beanClass == null || bean instanceof Map || jsonConfig.getPropertySetStrategy() != null || !jsonConfig.isIgnorePublicFields()) { setProperty(bean, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass().getName()); } } else { if (jsonConfig.isHandleJettisonSingleElementArray()) { Class newTargetClass = resolveClass(classMap, key, name, type); JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(newTargetClass); jsc.setClassMap(classMap); setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(bean, key, null, jsonConfig); } } } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type " + type, e); } } return bean; }
From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java
/** * Test for {@link ReflectionUtils#getPropertyDescriptors(BeanInfo, Class)}. * <p>//www. j av a2 s .c o m * When we try to use "bridge" method during {@link PropertyDescriptor} creation, this causes * exception under OpenJDK 6 and 7. */ public void test_getPropertyDescriptors_whenBridgeMethod() throws Exception { @SuppressWarnings({ "unused" }) class GenericClass<T> { public T getFoo() { return null; } public void setFoo(T value) { } } class SpecificClass extends GenericClass<String> { @Override public String getFoo() { return null; } } // prepare PropertyDescriptor-s Map<String, PropertyDescriptor> descriptors = getPropertyDescriptorNames(SpecificClass.class); // check "foo(java.lang.Object)" PropertyDescriptor propertyDescriptor; if (SystemUtils.JAVA_VERSION_FLOAT < 1.7f) { propertyDescriptor = descriptors.get("foo(java.lang.Object)"); } else { propertyDescriptor = descriptors.get("foo"); } assertNotNull(propertyDescriptor); assertSame(Object.class, propertyDescriptor.getPropertyType()); }
From source file:net.sf.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *//* w w w . java2 s.c o m*/ public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) { if (jsonObject == null || jsonObject.isNullObject() || root == null) { return root; } Class rootClass = root.getClass(); if (rootClass.isInterface()) { throw new JSONException("Root bean is an interface. " + rootClass); } Map classMap = jsonConfig.getClassMap(); if (classMap == null) { classMap = Collections.EMPTY_MAP; } Map props = JSONUtils.getProperties(jsonObject); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) { String name = (String) entries.next(); Class type = (Class) props.get(name); Object value = jsonObject.get(name); if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) { continue; } String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig); try { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key); if (pd != null && pd.getWriteMethod() == null) { log.info("Property '" + key + "' of " + root.getClass() + " has no write method. SKIPPED."); continue; } if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) { Class targetClass = resolveClass(classMap, key, name, type); Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig); setProperty(root, key, list, jsonConfig); } else { Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType()); Class targetInnerType = findTargetClass(key, classMap); if (innerType.equals(Object.class) && targetInnerType != null && !targetInnerType.equals(Object.class)) { innerType = targetInnerType; } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null); Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig); if (innerType.isPrimitive() || JSONUtils.isNumber(innerType) || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) { array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } else if (!array.getClass().equals(pd.getPropertyType())) { if (!pd.getPropertyType().equals(Object.class)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(Array.newInstance(innerType, 0).getClass()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher( new BeanMorpher(innerType, JSONUtils.getMorpherRegistry())); JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher); } array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } } setProperty(root, key, array, jsonConfig); } } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(root, key, null, jsonConfig); } else if (!pd.getPropertyType().isInstance(value)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(pd.getPropertyType()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { log.warn("Can't transform property '" + key + "' from " + type.getName() + " into " + pd.getPropertyType().getName() + ". Will register a default BeanMorpher"); JSONUtils.getMorpherRegistry().registerMorpher( new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry())); } setProperty(root, key, JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value), jsonConfig); } else { setProperty(root, key, value, jsonConfig); } } else if (root instanceof Map) { setProperty(root, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + root.getClass().getName()); } } else { if (pd != null) { Class targetClass = pd.getPropertyType(); if (jsonConfig.isHandleJettisonSingleElementArray()) { JSONArray array = new JSONArray().element(value, jsonConfig); Class newTargetClass = resolveClass(classMap, key, name, type); Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass, (JSONObject) value); if (targetClass.isArray()) { setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig), jsonConfig); } else if (Collection.class.isAssignableFrom(targetClass)) { setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig), jsonConfig); } else if (JSONArray.class.isAssignableFrom(targetClass)) { setProperty(root, key, array, jsonConfig); } else { setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else { if (targetClass == Object.class) { targetClass = resolveClass(classMap, key, name, type); if (targetClass == null) { targetClass = Object.class; } } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, (JSONObject) value); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else if (root instanceof Map) { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + rootClass.getName()); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(root, key, null, jsonConfig); } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type " + type, e); } } return root; }
From source file:org.malaguna.cmdit.service.reflection.ReflectionUtils.java
public boolean compareAndUpdateAttribute(Object oldObj, Object newObj, String atributo, boolean update, StringBuffer msgBuffer, String msgContext) { boolean result = false; if (oldObj != null && newObj != null) { oldObj = hpu.unproxy(oldObj);//w ww . j ava 2 s .co m newObj = hpu.unproxy(newObj); if (!isHibernateProxy(oldObj) && !isHibernateProxy(newObj)) { PropertyDescriptor desc = null; try { String firstAttribute = null; String restAttribute = null; int pos = atributo.indexOf("."); if (pos >= 0) { firstAttribute = atributo.substring(0, pos); restAttribute = atributo.substring(pos + 1); } else { firstAttribute = atributo; } desc = PropertyUtils.getPropertyDescriptor(oldObj, firstAttribute); if (desc != null) { Object oldValue = hpu.unproxy(desc.getReadMethod().invoke(oldObj)); Object newValue = hpu.unproxy(desc.getReadMethod().invoke(newObj)); if (restAttribute == null && !isHibernateProxy(oldValue) && !isHibernateProxy(newValue)) { String auxChangeMsg = null; result = (oldValue != null) ? compareObjects(desc, oldValue, newValue) : (newValue == null); if (!result) { if (msgBuffer != null) { auxChangeMsg = buildChangeMessage(desc, firstAttribute, oldValue, newValue, msgContext); } if (update) { updateOldValue(oldObj, desc, oldValue, newValue); } } if (msgBuffer != null) msgBuffer.append(getAppendMsg(auxChangeMsg, msgBuffer)); } if (restAttribute != null) { if (Collection.class.isAssignableFrom(desc.getPropertyType())) { Collection<?> oldSetAux = (Collection<?>) oldValue; Collection<?> newSetAux = (Collection<?>) newValue; if (oldValue != null && newValue != null) { Collection<?> intersection = CollectionUtils.intersection(oldSetAux, newSetAux); for (Object obj : intersection) { RUPredicate rup = new RUPredicate(obj.hashCode()); Object oldElement = CollectionUtils.find(oldSetAux, rup); Object newElement = CollectionUtils.find(newSetAux, rup); String context = (msgContext != null) ? msgContext + firstAttribute : firstAttribute; context += "([" + oldElement.toString() + "])."; compareAndUpdateAttribute(oldElement, newElement, restAttribute, update, msgBuffer, context); } } } else { compareAndUpdateAttribute(oldValue, newValue, restAttribute, update, msgBuffer); } } } } catch (NoSuchMethodException e) { String error = "Error in compareAndUpdateAttribute, class type [%s] has no property [%s]"; throw new RuntimeException(String.format(error, oldObj.getClass(), atributo), e); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return result; }
From source file:org.apache.usergrid.persistence.Schema.java
public synchronized void registerEntity(Class<? extends Entity> entityClass) { logger.info("Registering {}", entityClass); EntityInfo e = registeredEntityClasses.get(entityClass); if (e != null) { return;/* ww w.j a va 2 s . c o m*/ } Map<String, PropertyDescriptor> propertyDescriptors = entityClassPropertyToDescriptor.get(entityClass); if (propertyDescriptors == null) { EntityInfo entity = new EntityInfo(); String type = getEntityType(entityClass); propertyDescriptors = new LinkedHashMap<String, PropertyDescriptor>(); Map<String, PropertyInfo> properties = new TreeMap<String, PropertyInfo>(String.CASE_INSENSITIVE_ORDER); Map<String, CollectionInfo> collections = new TreeMap<String, CollectionInfo>( String.CASE_INSENSITIVE_ORDER); Map<String, DictionaryInfo> sets = new TreeMap<String, DictionaryInfo>(String.CASE_INSENSITIVE_ORDER); PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(entityClass); for (PropertyDescriptor descriptor : descriptors) { String name = descriptor.getName(); EntityProperty propertyAnnotation = getAnnotation(entityClass, descriptor, EntityProperty.class); if (propertyAnnotation != null) { if (isNotBlank(propertyAnnotation.name())) { name = propertyAnnotation.name(); } propertyDescriptors.put(name, descriptor); PropertyInfo propertyInfo = new PropertyInfo(propertyAnnotation); propertyInfo.setName(name); propertyInfo.setType(descriptor.getPropertyType()); properties.put(name, propertyInfo); // logger.info(propertyInfo); } EntityCollection collectionAnnotation = getAnnotation(entityClass, descriptor, EntityCollection.class); if (collectionAnnotation != null) { CollectionInfo collectionInfo = new CollectionInfo(collectionAnnotation); collectionInfo.setName(name); collectionInfo.setContainer(entity); collections.put(name, collectionInfo); // logger.info(collectionInfo); } EntityDictionary setAnnotation = getAnnotation(entityClass, descriptor, EntityDictionary.class); if (setAnnotation != null) { DictionaryInfo setInfo = new DictionaryInfo(setAnnotation); setInfo.setName(name); // setInfo.setType(descriptor.getPropertyType()); sets.put(name, setInfo); // logger.info(setInfo); } } if (!DynamicEntity.class.isAssignableFrom(entityClass)) { entity.setProperties(properties); entity.setCollections(collections); entity.setDictionaries(sets); entity.mapCollectors(this, type); entityMap.put(type, entity); allProperties.putAll(entity.getProperties()); Set<String> propertyNames = entity.getIndexedProperties(); for (String propertyName : propertyNames) { PropertyInfo property = entity.getProperty(propertyName); if ((property != null) && !allIndexedProperties.containsKey(propertyName)) { allIndexedProperties.put(propertyName, property); } } } entityClassPropertyToDescriptor.put(entityClass, propertyDescriptors); registeredEntityClasses.put(entityClass, entity); } }
From source file:com.espertech.esperio.csv.CSVInputAdapter.java
private Map<String, Object> constructPropertyTypes(String eventTypeName, Map<String, Object> propertyTypesGiven, EventAdapterService eventAdapterService) { Map<String, Object> propertyTypes = new HashMap<String, Object>(); EventType eventType = eventAdapterService.getExistsTypeByName(eventTypeName); if (eventType == null) { if (propertyTypesGiven != null) { eventAdapterService.addNestableMapType(eventTypeName, new HashMap<String, Object>(propertyTypesGiven), null, true, true, true, false, false); }/*from www .j a va2 s . co m*/ return propertyTypesGiven; } if (!eventType.getUnderlyingType().equals(Map.class)) { beanClass = eventType.getUnderlyingType(); } if (propertyTypesGiven != null && eventType.getPropertyNames().length != propertyTypesGiven.size()) { // allow this scenario for beans as we may want to bring in a subset of properties if (beanClass != null) { return propertyTypesGiven; } else { throw new EPException("Event type " + eventTypeName + " has already been declared with a different number of parameters"); } } for (String property : eventType.getPropertyNames()) { Class type; try { type = eventType.getPropertyType(property); } catch (PropertyAccessException e) { // thrown if trying to access an invalid property on an EventBean throw new EPException(e); } if (propertyTypesGiven != null && propertyTypesGiven.get(property) == null) { throw new EPException( "Event type " + eventTypeName + "has already been declared with different parameters"); } if (propertyTypesGiven != null && !propertyTypesGiven.get(property).equals(type)) { throw new EPException("Event type " + eventTypeName + "has already been declared with a different type for property " + property); } // we can't set read-only properties for bean if (!eventType.getUnderlyingType().equals(Map.class)) { PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(beanClass); PropertyDescriptor pd = null; for (PropertyDescriptor p : pds) { if (p.getName().equals(property)) pd = p; } if (pd == null) { continue; } if (pd.getWriteMethod() == null) { if (propertyTypesGiven == null) { continue; } else { throw new EPException( "Event type " + eventTypeName + "property " + property + " is read only"); } } } propertyTypes.put(property, type); } // flatten nested types Map<String, Object> flattenPropertyTypes = new HashMap<String, Object>(); for (String p : propertyTypes.keySet()) { Object type = propertyTypes.get(p); if (type instanceof Class && ((Class) type).getName().equals("java.util.Map") && eventType instanceof MapEventType) { MapEventType mapEventType = (MapEventType) eventType; Map<String, Object> nested = (Map) mapEventType.getTypes().get(p); for (String nestedProperty : nested.keySet()) { flattenPropertyTypes.put(p + "." + nestedProperty, nested.get(nestedProperty)); } } else if (type instanceof Class) { Class c = (Class) type; if (!c.isPrimitive() && !c.getName().startsWith("java")) { PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(c); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null) flattenPropertyTypes.put(p + "." + pd.getName(), pd.getPropertyType()); } } else { flattenPropertyTypes.put(p, type); } } else { flattenPropertyTypes.put(p, type); } } return flattenPropertyTypes; }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * This test will make changes to the {@link SPObject} under test and then * cause an exception forcing the persister to roll back the changes in the * object.//from ww w . j a va 2 s . c o m * <p> * Both the changes have to come through the persister initially before the * exception and they have to be reset after the exception. */ public void testSessionPersisterRollsBackProperties() throws Exception { SPObject objectUnderTest = getSPObjectUnderTest(); final Map<PropertyDescriptor, Object> initialProperties = new HashMap<PropertyDescriptor, Object>(); final Map<PropertyDescriptor, Object> newProperties = new HashMap<PropertyDescriptor, Object>(); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); Set<String> ignorePropertySet = getRollbackTestIgnorePropertySet(); NewValueMaker valueMaker = createNewValueMaker(getRootObject(), getPLIni()); SPSessionPersister persister = new TestingSessionPersister("tester", getRootObject(), getConverter()); persister.setWorkspaceContainer(getRootObject().getWorkspaceContainer()); failureReason = null; SPPersisterListener listener = new SPPersisterListener(new CountingSPPersister(), converter) { private boolean transactionAlreadyFinished = false; @Override public void transactionEnded(TransactionEvent e) { if (transactionAlreadyFinished) return; transactionAlreadyFinished = true; try { for (Map.Entry<PropertyDescriptor, Object> newProperty : newProperties.entrySet()) { Object objectUnderTest = getSPObjectUnderTest(); Object newVal = newProperty.getValue(); Object basicNewValue = converter.convertToBasicType(newVal); Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest, newProperty.getKey().getName()); Object basicExpectedValue = converter.convertToBasicType(newValAfterSet); logger.debug("Testing property " + newProperty.getKey().getName()); assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue, newProperty.getKey().getPropertyType()); } } catch (Throwable ex) { failureReason = ex; throw new RuntimeException(ex); } throw new RuntimeException("Forcing rollback."); } }; //Transactions begin and commits are currently sent on the workspace. getRootObject().getParent().addSPListener(listener); persister.begin(); for (PropertyDescriptor property : settableProperties) { Object oldVal; //Changing the UUID of the object makes it referenced as a different object //and would make the check later in this test fail. if (property.getName().equals("UUID")) continue; if (!propertiesToPersist.contains(property.getName())) continue; if (ignorePropertySet.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + objectUnderTest.getClass().getName()); continue; } initialProperties.put(property, oldVal); //special case for parent types. If a specific wabit object has a tighter parent then //WabitObject the getParentClass should return the parent type. Class<?> propertyType = property.getPropertyType(); if (property.getName().equals("parent")) { propertyType = getSPObjectUnderTest().getClass().getMethod("getParent").getReturnType(); logger.debug("Persisting parent, type is " + propertyType); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = converter.convertToBasicType(newVal); persister.begin(); persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type, converter.convertToBasicType(oldVal), basicNewValue); persister.commit(); newProperties.put(property, newVal); } try { persister.commit(); fail("An exception should make the persister hit the exception block."); } catch (Exception e) { //continue, exception expected. } if (failureReason != null) { throw new RuntimeException("Failed when asserting properties were " + "fully persisted.", failureReason); } for (Map.Entry<PropertyDescriptor, Object> entry : initialProperties.entrySet()) { assertEquals("Property " + entry.getKey().getName() + " did not match after rollback.", entry.getValue(), PropertyUtils.getSimpleProperty(objectUnderTest, entry.getKey().getName())); } }
From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java
private static final Object newLazyObject(Class<?> targetClass) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IntrospectionException, IllegalArgumentException, InvocationTargetException, PersistenceException { Object lazyObj = targetClass.newInstance(); String name = targetClass.getName(); Set<PropertyDescriptor> pds = idsByClassName.get(name); for (PropertyDescriptor pd : pds) { pd.getWriteMethod().invoke(lazyObj, getLazyValue(pd.getPropertyType())); }// w ww . j a va2 s. c o m return lazyObj; }
From source file:nl.strohalm.cyclos.utils.binding.CustomBeanUtilsBean.java
@Override public void setProperty(final Object bean, String name, final Object value) throws IllegalAccessException, InvocationTargetException { // Resolve any nested expression to get the actual target bean Object target = bean;/*from w ww .j a v a2 s.c o m*/ final int delim = findLastNestedIndex(name); if (delim >= 0) { try { target = getPropertyUtils().getProperty(bean, name.substring(0, delim)); } catch (final NoSuchMethodException e) { return; // Skip this property setter } name = name.substring(delim + 1); } // Declare local variables we will require String propName = null; // Simple name of target property Class<?> type = null; // Java type of target property int index = -1; // Indexed subscript value (if any) String key = null; // Mapped key value (if any) // Calculate the property name, index, and key values propName = name; final int i = propName.indexOf(PropertyUtils.INDEXED_DELIM); if (i >= 0) { final int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2); try { index = Integer.parseInt(propName.substring(i + 1, k)); } catch (final NumberFormatException e) { // Ignore } propName = propName.substring(0, i); } final int j = propName.indexOf(PropertyUtils.MAPPED_DELIM); if (j >= 0) { final int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2); try { key = propName.substring(j + 1, k); } catch (final IndexOutOfBoundsException e) { // Ignore } propName = propName.substring(0, j); } // Calculate the property type if (target instanceof DynaBean) { final DynaClass dynaClass = ((DynaBean) target).getDynaClass(); final DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; // Skip this property setter } type = dynaProperty.getType(); if (type.isArray() || Collection.class.isAssignableFrom(type)) { type = Object[].class; } } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (final NoSuchMethodException e) { return; // Skip this property setter } if (descriptor instanceof MappedPropertyDescriptor) { if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) { return; // Read-only, skip this property setter } type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType(); /** * Overriden behaviour ------------------- When a type is Object on a mapped property, retrieve the value to check if it's an array */ if (Object.class.equals(type)) { try { final Object retrieved = getPropertyUtils().getMappedProperty(target, propName, key); if (retrieved != null) { final Class<?> retrievedType = retrieved.getClass(); if (retrievedType.isArray() || Collection.class.isAssignableFrom(retrievedType)) { type = Object[].class; } } } catch (final NoSuchMethodException e) { throw new PropertyException(target, propName + "(" + key + ")"); } } } else if (descriptor instanceof IndexedPropertyDescriptor) { if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) { return; // Read-only, skip this property setter } type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType(); } else { if (descriptor.getWriteMethod() == null) { return; // Read-only, skip this property setter } type = descriptor.getPropertyType(); } } /** * Overriden behaviour ------------------- When a type is Map on a mapped property, retrieve the value to check if it's an array */ if (Map.class.isAssignableFrom(type) && StringUtils.isNotEmpty(key)) { try { final Map<?, ?> map = (Map<?, ?>) getPropertyUtils().getProperty(target, propName); final Object retrieved = map.get(key); if (retrieved != null) { final Class<?> retrievedType = retrieved.getClass(); if (retrievedType.isArray() || Collection.class.isAssignableFrom(retrievedType)) { type = Object[].class; } } } catch (final NoSuchMethodException e) { throw new PropertyException(target, propName + "(" + key + ")"); } } // Convert the specified value to the required type Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value == null) { final String values[] = new String[1]; values[0] = (String) value; newValue = getConvertUtils().convert(values, type); } else if (value instanceof String) { final String values[] = new String[1]; values[0] = (String) value; newValue = getConvertUtils().convert(values, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert((String[]) value, type); } else { newValue = value; } } else if (type.isArray()) { // Indexed value into array if (value instanceof String) { newValue = getConvertUtils().convert((String) value, type.getComponentType()); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType()); } else { newValue = value; } } else { // Value into scalar if ((value instanceof String) || (value == null)) { newValue = getConvertUtils().convert((String) value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type); } else if (getConvertUtils().lookup(value.getClass()) != null) { newValue = getConvertUtils().convert(value.toString(), type); } else { newValue = value; } } // Invoke the setter method try { if (index >= 0) { getPropertyUtils().setIndexedProperty(target, propName, index, newValue); } else if (key != null) { getPropertyUtils().setMappedProperty(target, propName, key, newValue); } else { getPropertyUtils().setProperty(target, propName, newValue); } } catch (final NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } }