List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
protected void setPropertyValue(PropertyTokenHolder tokens, Object newValue) throws BeansException { String propertyName = tokens.canonicalName; if (tokens.keys != null) { // apply indexes and map keys: fetch value for all keys but the last one PropertyTokenHolder getterTokens = new PropertyTokenHolder(); getterTokens.canonicalName = tokens.canonicalName; getterTokens.actualName = tokens.actualName; getterTokens.keys = new String[tokens.keys.length - 1]; System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); Object propValue = null;// w w w . j a v a 2 s .c o m Type type; try { propValue = getPropertyValue(getterTokens); type = getPropertyType(getterTokens); if (propValue == null) { Class rawType = null; if (type instanceof ParameterizedType) { if (((ParameterizedType) type).getRawType() instanceof Class) { rawType = (Class) ((ParameterizedType) type).getRawType(); } else if (type instanceof Class) { rawType = (Class) type; } } if (rawType != null && List.class.isAssignableFrom(rawType)) { PropertyTokenHolder propertyTokenHolder = new PropertyTokenHolder(); propertyTokenHolder.actualName = getterTokens.actualName; propertyTokenHolder.canonicalName = getterTokens.canonicalName; setPropertyValue(propertyTokenHolder, new ArrayList()); } } } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "'", ex); } // set value for last key String key = tokens.keys[tokens.keys.length - 1]; if (propValue == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "': returned null"); } else if (propValue.getClass().isArray()) { Class requiredType = propValue.getClass().getComponentType(); int arrayIndex = Integer.parseInt(key); Object oldValue = null; try { if (this.extractOldValueForEditor) { oldValue = Array.get(propValue, arrayIndex); } Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue, requiredType); Array.set(propValue, Integer.parseInt(key), convertedValue); } catch (IllegalArgumentException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new TypeMismatchException(pce, requiredType, ex); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid array index in property path '" + propertyName + "'", ex); } } else if (propValue instanceof List) { List list = (List) propValue; int index = Integer.parseInt(key); Object oldValue = null; if (this.extractOldValueForEditor && index < list.size()) { oldValue = list.get(index); } Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue, null); if (index < list.size()) { list.set(index, convertedValue); } else if (index >= list.size()) { for (int i = list.size(); i < index; i++) { try { list.add(null); } catch (NullPointerException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot set element with index " + index + " in List of size " + list.size() + ", accessed using property path '" + propertyName + "': List does not support filling up gaps with null elements"); } } list.add(convertedValue); } } else if (propValue instanceof Map) { Map map = (Map) propValue; propValue.getClass().getGenericSuperclass(); Object oldValue = null; if (this.extractOldValueForEditor) { oldValue = map.get(key); } Type type2 = ((ParameterizedType) type).getActualTypeArguments()[1]; Type type3 = ((ParameterizedType) type).getActualTypeArguments()[0]; Class reqClass = null; Class keyReqClass = null; if (type2 instanceof Class) { reqClass = (Class) type2; } else if (type2 instanceof ParameterizedType) { reqClass = (Class) ((ParameterizedType) type2).getRawType(); } if (type3 instanceof Class) { keyReqClass = (Class) type3; } else if (type3 instanceof ParameterizedType) { keyReqClass = (Class) ((ParameterizedType) type3).getRawType(); } Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue, reqClass); Object convertedKey = doTypeConversionIfNecessary(key, keyReqClass); map.put(convertedKey, convertedValue); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Map; returned value was [" + newValue + "]"); } } else { PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd == null || pd.getWriteMethod() == null) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName); } Method readMethod = pd.getReadMethod(); Method writeMethod = pd.getWriteMethod(); Object oldValue = null; if (this.extractOldValueForEditor && readMethod != null) { try { oldValue = readMethod.invoke(this.object, new Object[0]); } catch (Exception ex) { logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName, ex); } } try { Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue, pd.getPropertyType()); if (pd.getPropertyType().isPrimitive() && (convertedValue == null || "".equals(convertedValue))) { throw new IllegalArgumentException("Invalid value [" + newValue + "] for property '" + pd.getName() + "' of primitive type [" + pd.getPropertyType() + "]"); } if (logger.isDebugEnabled()) { logger.debug("About to invoke write method [" + writeMethod + "] on object of class [" + this.object.getClass().getName() + "]"); } writeMethod.invoke(this.object, new Object[] { convertedValue }); if (logger.isDebugEnabled()) { logger.debug("Invoked write method [" + writeMethod + "] with value of type [" + pd.getPropertyType().getName() + "]"); } } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); } else { throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); } } catch (IllegalArgumentException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new TypeMismatchException(pce, pd.getPropertyType(), ex); } catch (IllegalAccessException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new MethodInvocationException(pce, ex); } } }
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 ava 2 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:com.xwtec.xwserver.util.json.JSONArray.java
/** * Get the collection type from a getter or setter, or null if no type was * found.<br/>/* w ww . j a v a 2 s . c om*/ * Contributed by [Matt Small @ WaveMaker]. */ public static Class[] getCollectionType(PropertyDescriptor pd, boolean useGetter) throws JSONException { Type type; if (useGetter) { Method m = pd.getReadMethod(); type = m.getGenericReturnType(); } else { Method m = pd.getWriteMethod(); Type[] gpts = m.getGenericParameterTypes(); if (1 != gpts.length) { throw new JSONException("method " + m + " is not a standard setter"); } type = gpts[0]; } if (!(type instanceof ParameterizedType)) { return null; // throw new JSONException("type not instanceof ParameterizedType: // "+type.getClass()); } ParameterizedType pType = (ParameterizedType) type; Type[] actualTypes = pType.getActualTypeArguments(); Class[] ret = new Class[actualTypes.length]; for (int i = 0; i < ret.length; i++) { ret[i] = (Class) actualTypes[i]; } return ret; }
From source file:com.xwtec.xwserver.util.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *//*w ww . ja v a 2 s .co 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 = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; 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 = findTargetClass(key, classMap); newTargetClass = newTargetClass == null ? findTargetClass(name, classMap) : newTargetClass; 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 { // pd is null 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 = findTargetClass(key, classMap); newTargetClass = newTargetClass == null ? findTargetClass(name, classMap) : newTargetClass; 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:net.sf.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *//* w w w . j a va 2 s . co 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:com.complexible.pinto.RDFMapper.java
private Class pinpointClass(final Model theGraph, final Resource theResource, final PropertyDescriptor theDescriptor) { Class aClass = theDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(aClass)) { // if the field we're assigning from is a collection, try and figure out the type of the thing // we're creating from the collection Type[] aTypes = null;/*from w w w . j a va 2s .com*/ if (theDescriptor.getReadMethod().getGenericParameterTypes().length > 0) { // should this be the return type? eg new Type[] { theDescriptor.getReadMethod().getGenericReturnType() }; aTypes = theDescriptor.getReadMethod().getGenericParameterTypes(); } else if (theDescriptor.getWriteMethod().getGenericParameterTypes().length > 0) { aTypes = theDescriptor.getWriteMethod().getGenericParameterTypes(); } if (aTypes != null && aTypes.length >= 1) { // first type argument to a collection is usually the one we care most about if (aTypes[0] instanceof ParameterizedType && ((ParameterizedType) aTypes[0]).getActualTypeArguments().length > 0) { Type aType = ((ParameterizedType) aTypes[0]).getActualTypeArguments()[0]; if (aType instanceof Class) { aClass = (Class) aType; } else if (aType instanceof WildcardTypeImpl) { WildcardTypeImpl aWildcard = (WildcardTypeImpl) aType; // trying to suss out super v extends w/o resorting to string munging. if (aWildcard.getLowerBounds().length == 0 && aWildcard.getUpperBounds().length > 0) { // no lower bounds afaik indicates ? extends Foo aClass = ((Class) aWildcard.getUpperBounds()[0]); } else if (aWildcard.getLowerBounds().length > 0) { // lower & upper bounds I believe indicates something of the form Foo super Bar aClass = ((Class) aWildcard.getLowerBounds()[0]); } else { // shoot, we'll try the string hack that Adrian posted on the mailing list. try { aClass = Class.forName(aType.toString().split(" ")[2].substring(0, aTypes[0].toString().split(" ")[2].length() - 1)); } catch (Exception e) { // everything has failed, let aClass be the default (theClass) and hope for the best } } } else { // punt? wtf else could it be? try { aClass = Class.forName(aType.toString()); } catch (ClassNotFoundException e) { // oh well, we did the best we can } } } else if (aTypes[0] instanceof Class) { aClass = (Class) aTypes[0]; } } else { LOGGER.info("Could not find type for collection %s", aClass); } } else if (!Classes.isInstantiable(aClass) || !Classes.hasDefaultConstructor(aClass)) { Class<?> aCurr = null; final Iterable<Resource> aRdfTypes = Models2.getTypes(theGraph, theResource); for (Resource aType : aRdfTypes) { Class<?> aMappedClass = mMappings.get(aType); if (aMappedClass != null) { if (aCurr == null) { aCurr = aMappedClass; } else if (aCurr.isAssignableFrom(aMappedClass)) { // we want the most specific class, that's likely to be what's instantiable aCurr = aMappedClass; } } } if (aCurr != null) { aClass = aCurr; } } return aClass; }
From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java
/** * Return an array of non-simple bean properties that are unsatisfied. * These are probably unsatisfied references to other beans in the * factory. Does not include simple properties like primitives or Strings. * @param mbd the merged bean definition the bean was created with * @param bw the BeanWrapper the bean was created with * @return an array of bean property names * @see org.springframework.beans.BeanUtils#isSimpleProperty *///from w w w . j a v a 2 s . c om protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) { Set<String> result = new TreeSet<>(); PropertyValues pvs = mbd.getPropertyValues(); PropertyDescriptor[] pds = bw.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) && !BeanUtils.isSimpleProperty(pd.getPropertyType())) { result.add(pd.getName()); } } return StringUtils.toStringArray(result); }
From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java
/** * Perform a dependency check that all properties exposed have been set, * if desired. Dependency checks can be objects (collaborating beans), * simple (primitives and String), or all (both). * @param beanName the name of the bean//from ww w .ja v a2s. co m * @param mbd the merged bean definition the bean was created with * @param pds the relevant property descriptors for the target bean * @param pvs the property values to be applied to the bean * @see #isExcludedFromDependencyCheck(java.beans.PropertyDescriptor) */ protected void checkDependencies(String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, @Nullable PropertyValues pvs) throws UnsatisfiedDependencyException { int dependencyCheck = mbd.getDependencyCheck(); for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() != null && (pvs == null || !pvs.contains(pd.getName()))) { boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType()); boolean unsatisfied = (dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_ALL) || (isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_SIMPLE) || (!isSimple && dependencyCheck == RootBeanDefinition.DEPENDENCY_CHECK_OBJECTS); if (unsatisfied) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(), "Set this property value or disable dependency checking for this bean."); } } } }
From source file:de.xwic.appkit.webbase.toolkit.app.EditorToolkit.java
/** * Saves the values from GUI controls into the entity of the editormodel. No update on DB is triggered. *//*from w w w . ja v a 2 s . c om*/ public void saveFieldValues() { Object obj = null; Class<?> clazz = null; if (null != baseObj) { obj = baseObj; clazz = obj.getClass(); } else if (null != model) { obj = model.getEntity(); clazz = ((IEntity) obj).type(); } for (Iterator<IControl> iterator = registeredControls.values().iterator(); iterator.hasNext();) { IControl control = iterator.next(); String propName = getPropertyName(control); PropertyDescriptor propInfo = null; try { propInfo = new PropertyDescriptor(propName, clazz); } catch (IntrospectionException ex) { throw new RuntimeException("Could find property: " + propName + " of entityclass: " + (obj == null ? "No entity!" : obj.getClass().getName()), ex); } if (!control.isVisible()) { continue; } if (control instanceof IHTMLElement) { IHTMLElement htmlElement = (IHTMLElement) control; if (!htmlElement.isEnabled()) { continue; } } IToolkitControlHelper helper = allControls.get(control.getClass()); if (helper == null) { throw new RuntimeException("Could not find control helper: " + control.getClass()); } Object value; Object controlValue = helper.getContent(control); ITypeConverter converter = registeredConverters.get(propName); if (converter != null) { //if we have a type converter registered for the property, convert the control value type to the entity value type first value = converter.convertRight(controlValue); } else { value = autoConvertToEntityType(propInfo, controlValue); } try { propInfo.getWriteMethod().invoke(obj, new Object[] { value }); } catch (Exception ex) { throw new RuntimeException("Could not write property: " + propName + " of entityclass: " + (obj == null ? "No entity!" : obj.getClass().getName()), ex); } } }
From source file:org.yes.cart.bulkimport.csv.impl.CsvBulkImportServiceImpl.java
/** * Fill the given entity object with line information using import column descriptions. * * @param tuple given csv line * @param object entity object * @param importColumns particular type column collection * @param masterObject master object , that set from main import in case of sub import * @param importDescriptor import descriptor * @param entityCache runtime cache * * @throws Exception in case if something wrong with reflection (IntrospectionException, * InvocationTargetException, * IllegalAccessException) */// w ww . j a v a2 s .c om private void fillEntityForeignKeys(final ImportTuple tuple, final Object object, final Collection<ImportColumn> importColumns, final Object masterObject, final ImportDescriptor importDescriptor, final Map<String, Object> entityCache) throws Exception { ImportColumn currentColumn = null; final Class clz = object.getClass(); Object singleObjectValue = null; PropertyDescriptor propertyDescriptor = null; try { for (ImportColumn importColumn : importColumns) { currentColumn = importColumn; if (importColumn.isUseMasterObject()) { singleObjectValue = masterObject; } else { singleObjectValue = getEntity(tuple, importColumn, masterObject, importDescriptor, entityCache); } propertyDescriptor = new PropertyDescriptor(importColumn.getName(), clz); final Object oldValue = propertyDescriptor.getReadMethod().invoke(object); if (oldValue instanceof Identifiable || singleObjectValue instanceof Identifiable) { final Object oldValuePK = oldValue != null ? genericDAO.getEntityIdentifier(oldValue) : null; final Object newValuePK = singleObjectValue != null ? genericDAO.getEntityIdentifier(singleObjectValue) : null; if (oldValuePK == null || !oldValuePK.equals(newValuePK)) { // Update the object only if the value has changed propertyDescriptor.getWriteMethod().invoke(object, singleObjectValue); } } else { // This is not identifiable, possibly primitive (PK) so write always propertyDescriptor.getWriteMethod().invoke(object, singleObjectValue); } } } catch (Exception exp) { final String propName = propertyDescriptor != null ? propertyDescriptor.getName() : null; final String propType = propertyDescriptor != null ? propertyDescriptor.getPropertyType().getName() : null; throw new Exception(MessageFormat.format( "Failed to process property name {0} type {1} object is {2} caused by column {0} with value {1}", propName, propType, object, currentColumn, singleObjectValue), exp); } }