List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * This will reflectively iterate over all of the properties in the Wabit * object and set each value that has a setter and getter. When the property * is set it should cause the property to be persisted through the * {@link WorkspacePersisterListener}./*ww w . j a v a2 s. com*/ */ public void testPropertiesArePersisted() throws Exception { CountingWabitPersister countingPersister = new CountingWabitPersister(); WorkspacePersisterListener listener = new WorkspacePersisterListener( new StubWabitSession(new StubWabitSessionContext()), countingPersister, true); SPObject wo = getObjectUnderTest(); wo.addSPListener(listener); WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); //Ignore properties that are not in events because we won't have an event //to respond to. Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents(); Set<String> propertiesToIgnoreForPersisting = getPropertiesToIgnoreForPersisting(); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEvents.contains(property.getName())) continue; if (propertiesToIgnoreForPersisting.contains(property.getName())) continue; countingPersister.clearAllPropertyChanges(); try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); int oldChangeCount = countingPersister.getPersistPropertyCount(); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(wo, property.getName(), newVal); assertTrue("Did not persist property " + property.getName(), oldChangeCount < countingPersister.getPersistPropertyCount()); //The first property change at current is always the property change we are //looking for, this may need to be changed in the future to find the correct //property. PersistedSPOProperty propertyChange = null; for (PersistedSPOProperty nextPropertyChange : countingPersister.getAllPropertyChanges()) { if (nextPropertyChange.getPropertyName().equals(property.getName())) { propertyChange = nextPropertyChange; break; } } assertNotNull("A property change event cannot be found for the property " + property.getName(), propertyChange); assertEquals(wo.getUUID(), propertyChange.getUUID()); assertEquals(property.getName(), propertyChange.getPropertyName()); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } Object oldConvertedType = converterFactory.convertToBasicType(oldVal, additionalVals.toArray()); assertEquals( "Old value of property " + property.getName() + " was wrong, value expected was " + oldConvertedType + " but is " + countingPersister.getLastOldValue(), oldConvertedType, propertyChange.getOldValue()); //Input streams from images are being compared by hash code not values if (Image.class.isAssignableFrom(property.getPropertyType())) { logger.debug(propertyChange.getNewValue().getClass()); assertTrue(Arrays.equals(PersisterUtils.convertImageToStreamAsPNG((Image) newVal).toByteArray(), PersisterUtils .convertImageToStreamAsPNG((Image) converterFactory .convertToComplexType(propertyChange.getNewValue(), Image.class)) .toByteArray())); } else { assertEquals(converterFactory.convertToBasicType(newVal, additionalVals.toArray()), propertyChange.getNewValue()); } Class<? extends Object> classType; if (oldVal != null) { classType = oldVal.getClass(); } else { classType = newVal.getClass(); } assertEquals(PersisterUtils.getDataType(classType), propertyChange.getDataType()); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + wo.getClass().getName()); } } }
From source file:org.usergrid.persistence.Schema.java
public void setEntityProperty(Entity entity, String property, Object value) { PropertyDescriptor descriptor = getDescriptorForEntityProperty(entity.getClass(), property); if (descriptor != null) { Class<?> cls = descriptor.getPropertyType(); if (cls != null) { if ((value == null) || (cls.isAssignableFrom(value.getClass()))) { try { descriptor.getWriteMethod().invoke(entity, value); return; } catch (Exception e) { logger.error("Unable to set entity property " + property, e); }//w ww . jav a 2 s . com } try { descriptor.getWriteMethod().invoke(entity, mapper.convertValue(value, cls)); return; } catch (Exception e) { logger.error("Unable to set entity property " + property, e); } } } entity.setDynamicProperty(property, value); }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * This test uses the object under test to ensure that the * {@link WabitSessionPersister} updates each property appropriately on * persistence.// ww w.jav a2 s . c om */ public void testPersisterUpdatesProperties() throws Exception { SPObject wo = getObjectUnderTest(); WabitSessionPersister persister = new WabitSessionPersister("secondary test persister", session, getWorkspace(), true); WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); //Ignore properties that are not in events because we won't have an event //to respond to. Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents(); Set<String> propertiesToIgnoreForPersisting = getPropertiesToIgnoreForPersisting(); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEvents.contains(property.getName())) continue; if (propertiesToIgnoreForPersisting.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } //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 = getParentClass(); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); logger.debug("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal + "\" to newVal \"" + newVal + "\""); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = converterFactory.convertToBasicType(newVal, additionalVals.toArray()); persister.begin(); persister.persistProperty(wo.getUUID(), property.getName(), type, converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), basicNewValue); persister.commit(); Object newValAfterSet = PropertyUtils.getSimpleProperty(wo, property.getName()); Object basicExpectedValue = converterFactory.convertToBasicType(newValAfterSet, additionalVals.toArray()); assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue, property.getPropertyType()); } }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * This test will set all of the properties in a WabitObject in one transaction then * after committing the next persister after it will throw an exception causing the * persister to undo all of the changes it just made. *///from w ww . j av a 2 s . co m public void testPersisterCommitCanRollbackProperties() throws Exception { SPObject wo = getObjectUnderTest(); WabitSessionPersister persister = new WabitSessionPersister("test persister", session, getWorkspace(), true); CountingWabitListener countingListener = new CountingWabitListener(); ErrorWabitPersister errorPersister = new ErrorWabitPersister(); WorkspacePersisterListener listener = new WorkspacePersisterListener(session, errorPersister, true); SQLPowerUtils.listenToHierarchy(getWorkspace(), listener); wo.addSPListener(countingListener); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); Set<String> propertiesToIgnore = new HashSet<String>(getPropertiesToIgnoreForEvents()); propertiesToIgnore.addAll(getPropertiesToIgnoreForPersisting()); //Track old and new property values to test they are set properly Map<String, Object> propertyNameToOldVal = new HashMap<String, Object>(); //Set all of the properties of the object under test in one transaction. persister.begin(); int propertyChangeCount = 0; for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnore.contains(property.getName())) continue; try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } propertyNameToOldVal.put(property.getName(), 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 = getParentClass(); } Object newVal = valueMaker.makeNewValue(propertyType, oldVal, property.getName()); logger.debug("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal + "\" to newVal \"" + newVal + "\""); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = converterFactory.convertToBasicType(newVal, additionalVals.toArray()); persister.persistProperty(wo.getUUID(), property.getName(), type, converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), basicNewValue); propertyChangeCount++; } //Commit the transaction causing the rollback to occur errorPersister.setThrowError(true); try { persister.commit(); fail("The commit method should have an error sent to it and it should rethrow the exception."); } catch (SPPersistenceException t) { //continue } for (PropertyDescriptor property : settableProperties) { Object currentVal; if (propertiesToIgnore.contains(property.getName())) continue; try { currentVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object oldVal = propertyNameToOldVal.get(property.getName()); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } logger.debug("Checking property " + property.getName() + " was set to " + oldVal + ", actual value is " + currentVal); assertEquals(converterFactory.convertToBasicType(oldVal, additionalVals.toArray()), converterFactory.convertToBasicType(currentVal, additionalVals.toArray())); } logger.debug("Received " + countingListener.getPropertyChangeCount() + " change events."); assertTrue(propertyChangeCount * 2 <= countingListener.getPropertyChangeCount()); }
From source file:com.interface21.beans.BeanWrapperImpl.java
/** * Set an individual field.//from ww w . j a va2 s .co m * All other setters go through this. * @param pv property value to use for update * @throws PropertyVetoException if a listeners throws a JavaBeans API veto * @throws BeansException if there's a low-level, fatal error */ public void setPropertyValue(PropertyValue pv) throws PropertyVetoException, BeansException { if (isNestedProperty(pv.getName())) { try { BeanWrapper nestedBw = getBeanWrapperForNestedProperty(pv.getName()); nestedBw.setPropertyValue(new PropertyValue(getFinalPath(pv.getName()), pv.getValue())); return; } catch (NullValueInNestedPathException ex) { // Let this through throw ex; } catch (FatalBeanException ex) { // Error in the nested path throw new NotWritablePropertyException(pv.getName(), getWrappedClass()); } } if (!isWritableProperty(pv.getName())) { throw new NotWritablePropertyException(pv.getName(), getWrappedClass()); } PropertyDescriptor pd = getPropertyDescriptor(pv.getName()); Method writeMethod = pd.getWriteMethod(); Method readMethod = pd.getReadMethod(); Object oldValue = null; // May stay null if it's not a readable property PropertyChangeEvent propertyChangeEvent = null; try { if (readMethod != null && eventPropagationEnabled) { // Can only find existing value if it's a readable property try { oldValue = readMethod.invoke(object, new Object[] {}); } catch (Exception ex) { // The getter threw an exception, so we couldn't retrieve the old value. // We're not really interested in any exceptions at this point, // so we merely log the problem and leave oldValue null logger.warn("Failed to invoke getter '" + readMethod.getName() + "' to get old property value before property change: getter probably threw an exception", ex); } } // Old value may still be null propertyChangeEvent = createPropertyChangeEventWithTypeConversionIfNecessary(object, pv.getName(), oldValue, pv.getValue(), pd.getPropertyType()); // May throw PropertyVetoException: if this happens the PropertyChangeSupport // class fires a reversion event, and we jump out of this method, meaning // the change was never actually made if (eventPropagationEnabled) { vetoableChangeSupport.fireVetoableChange(propertyChangeEvent); } if (pd.getPropertyType().isPrimitive() && (pv.getValue() == null || "".equals(pv.getValue()))) { throw new IllegalArgumentException("Invalid value [" + pv.getValue() + "] for property [" + pd.getName() + "] of primitive type [" + pd.getPropertyType() + "]"); } // Make the change if (logger.isDebugEnabled()) logger.debug("About to invoke write method [" + writeMethod + "] on object of class '" + object.getClass().getName() + "'"); writeMethod.invoke(object, new Object[] { propertyChangeEvent.getNewValue() }); if (logger.isDebugEnabled()) logger.debug("Invoked write method [" + writeMethod + "] ok"); // If we get here we've changed the property OK and can broadcast it if (eventPropagationEnabled) propertyChangeSupport.firePropertyChange(propertyChangeEvent); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof PropertyVetoException) throw (PropertyVetoException) ex.getTargetException(); if (ex.getTargetException() instanceof ClassCastException) throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); throw new MethodInvocationException(ex.getTargetException(), propertyChangeEvent); } catch (IllegalAccessException ex) { throw new FatalBeanException("illegal attempt to set property [" + pv + "] threw exception", ex); } catch (IllegalArgumentException ex) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex); } }
From source file:org.openmobster.core.mobileObject.xml.MobileObjectSerializer.java
private Object initializeIndexedProperty(Object parentObject, String property, PropertyDescriptor propertyMetaData, List<ArrayMetaData> objectMetaData, String propertyPath) throws Exception { Object element = null;/* w ww . j av a 2 s . c o m*/ //ArrayUri String arrayUri = null; Integer arrayIndex = 0; if (propertyPath.endsWith("]")) { int lastIndex = propertyPath.lastIndexOf('['); arrayUri = propertyPath.substring(0, lastIndex); arrayIndex = Integer.parseInt(propertyPath.substring(lastIndex + 1, propertyPath.length() - 1).trim()); } ArrayMetaData arrayMetaData = null; for (ArrayMetaData local : objectMetaData) { if (local.arrayUri.equals(arrayUri)) { arrayMetaData = local; break; } } //Find the Class of the elementType String elementTypeName = arrayMetaData.arrayClass; Class elementType = null; if (elementTypeName != null && elementTypeName.trim().length() > 0 && !elementTypeName.equals("null")) { elementType = Thread.currentThread().getContextClassLoader().loadClass(arrayMetaData.arrayClass); } else { //Figure out the element type from the Property Information //This happens when a brand new object is created on the device and is being synced //with the backend //The MobileObject Framework on the device does not know about any Class level information //of the remote bean //The Limitation of this is that: // //* Indexed Properties if Collections must be Parameterized with Concrete Types //* Indexed Properties if Arrays must be Arrays of Concrete Types if (!propertyMetaData.getPropertyType().isArray()) { ParameterizedType returnType = (ParameterizedType) propertyMetaData.getReadMethod() .getGenericReturnType(); Type[] actualTypes = returnType.getActualTypeArguments(); for (Type actualType : actualTypes) { elementType = (Class) actualType; } } else { elementType = propertyMetaData.getPropertyType().getComponentType(); } } //An IndexedProperty Object indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName()); //Initialize the IndexedProperty (An Array or Collection) if (propertyMetaData.getPropertyType().isArray()) { int arraySize = arrayMetaData.arrayLength; if (indexedProperty == null) { //Initialize the Array with Size from Object Meta Data PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), Array.newInstance(elementType, arraySize)); } else { //Make sure the Array Size matches int actualSize = Array.getLength(indexedProperty); if (actualSize != arraySize) { //Re-set the existing Array PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), Array.newInstance(elementType, arraySize)); } } } else { if (indexedProperty == null) { //Handle Collection Construction PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), new ArrayList()); } } //Check to see if the index specified by the field requires creation of new //element indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName()); if (!propertyMetaData.getPropertyType().isArray()) { try { element = PropertyUtils.getIndexedProperty(parentObject, property); } catch (IndexOutOfBoundsException iae) { Object newlyInitialized = elementType.newInstance(); ((Collection) indexedProperty).add(newlyInitialized); element = newlyInitialized; } } else { element = PropertyUtils.getIndexedProperty(parentObject, property); if (element == null) { Object newlyInitialized = elementType.newInstance(); Array.set(indexedProperty, arrayIndex, newlyInitialized); element = newlyInitialized; } } return element; }
From source file:org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass.java
/** * Establishes a relationship for a java.util.Set * * @param property The collection property *//*w w w . j a v a 2 s. c o m*/ private void establishRelationshipForCollection(DefaultGrailsDomainClassProperty property) { // is it a relationship Class<?> relatedClassType = getRelatedClassType(property.getName()); if (relatedClassType != null) { // set the referenced type in the property associations.add(property); property.setReferencedPropertyType(relatedClassType); // if the related type is a domain class // then figure out what kind of relationship it is if (DomainClassArtefactHandler.isDomainClass(relatedClassType)) { // check the relationship defined in the referenced type // if it is also a Set/domain class etc. Map relatedClassRelationships = GrailsDomainConfigurationUtil.getAssociationMap(relatedClassType); Class<?> relatedClassPropertyType = null; // First check whether there is an explicit relationship // mapping for this property (as provided by "mappedBy"). String mappingProperty = (String) mappedBy.get(property.getName()); if (!StringUtils.isBlank(mappingProperty)) { // First find the specified property on the related class, if it exists. PropertyDescriptor pd = findProperty( GrailsClassUtils.getPropertiesOfType(relatedClassType, getClazz()), mappingProperty); // If a property of the required type does not exist, search // for any collection properties on the related class. if (pd == null) pd = findProperty( GrailsClassUtils.getPropertiesAssignableToType(relatedClassType, Collection.class), mappingProperty); // We've run out of options. The given "mappedBy" // setting is invalid. boolean isNone = "none".equals(mappingProperty); if (pd == null && !isNone) { throw new GrailsDomainException( "Non-existent mapping property [" + mappingProperty + "] specified for property [" + property.getName() + "] in class [" + getClazz() + "]"); } else if (pd != null) { // Tie the properties together. relatedClassPropertyType = pd.getPropertyType(); property.setReferencePropertyName(pd.getName()); } } else { if (mappedBy.containsKey(property.getName()) && mappedBy.get(property.getName()) == null) return; // if the related type has a relationships map it may be a many-to-many // figure out if there is a many-to-many relationship defined if (isRelationshipManyToMany(property, relatedClassType, relatedClassRelationships)) { String relatedClassPropertyName = null; Map relatedClassMappedBy = GrailsDomainConfigurationUtil.getMappedByMap(relatedClassType); // retrieve the relationship property for (Object o : relatedClassRelationships.keySet()) { String currentKey = (String) o; String mappedByProperty = (String) relatedClassMappedBy.get(currentKey); if (mappedByProperty != null && !mappedByProperty.equals(property.getName())) continue; Class<?> currentClass = (Class<?>) relatedClassRelationships.get(currentKey); if (currentClass.isAssignableFrom(getClazz())) { relatedClassPropertyName = currentKey; break; } } // if there is one defined get the type if (relatedClassPropertyName != null) { relatedClassPropertyType = GrailsClassUtils.getPropertyType(relatedClassType, relatedClassPropertyName); } } // otherwise figure out if there is a one-to-many relationship by retrieving any properties that are of the related type // if there is more than one property then (for the moment) ignore the relationship if (relatedClassPropertyType == null) { PropertyDescriptor[] descriptors = GrailsClassUtils.getPropertiesOfType(relatedClassType, getClazz()); if (descriptors.length == 1) { relatedClassPropertyType = descriptors[0].getPropertyType(); property.setReferencePropertyName(descriptors[0].getName()); } else if (descriptors.length > 1) { // try now to use the class name by convention String classPropertyName = getPropertyName(); PropertyDescriptor pd = findProperty(descriptors, classPropertyName); if (pd == null) { throw new GrailsDomainException("Property [" + property.getName() + "] in class [" + getClazz() + "] is a bidirectional one-to-many with two possible properties on the inverse side. " + "Either name one of the properties on other side of the relationship [" + classPropertyName + "] or use the 'mappedBy' static to define the property " + "that the relationship is mapped with. Example: static mappedBy = [" + property.getName() + ":'myprop']"); } relatedClassPropertyType = pd.getPropertyType(); property.setReferencePropertyName(pd.getName()); } } } establishRelationshipForSetToType(property, relatedClassPropertyType); // if its a many-to-many figure out the owning side of the relationship if (property.isManyToMany()) { establishOwnerOfManyToMany(property, relatedClassType); } } // otherwise set it to not persistent as you can't persist // relationships to non-domain classes else { property.setBasicCollectionType(true); } } else if (!Map.class.isAssignableFrom(property.getType())) { // no relationship defined for set. // set not persistent property.setPersistent(false); } }
From source file:com.xwtec.xwserver.util.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *///from w w w . ja v a 2s . com 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:ca.sqlpower.object.PersistedSPObjectTest.java
/** * Tests the {@link SPSessionPersister} can update every settable property * on an object based on a persist call. *//*from w w w .j av a 2s . c o m*/ public void testSPPersisterPersistsProperties() throws Exception { SPSessionPersister persister = new TestingSessionPersister("Testing Persister", root, getConverter()); persister.setWorkspaceContainer(root.getWorkspaceContainer()); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); SPObject objectUnderTest = getSPObjectUnderTest(); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass())); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); 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; 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; } //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()); System.out.println("Persisting property \"" + property.getName() + "\" from oldVal \"" + oldVal + "\" to newVal \"" + newVal + "\""); DataType type = PersisterUtils.getDataType(property.getPropertyType()); Object basicNewValue = getConverter().convertToBasicType(newVal); persister.begin(); persister.persistProperty(objectUnderTest.getUUID(), property.getName(), type, getConverter().convertToBasicType(oldVal), basicNewValue); persister.commit(); Object newValAfterSet = PropertyUtils.getSimpleProperty(objectUnderTest, property.getName()); Object basicExpectedValue = getConverter().convertToBasicType(newValAfterSet); assertPersistedValuesAreEqual(newVal, newValAfterSet, basicNewValue, basicExpectedValue, property.getPropertyType()); } }
From source file:org.obiba.onyx.jade.instrument.gehealthcare.CardiosoftInstrumentRunner.java
/** * Place the results and xml and pdf files into a map object to send them to the server for persistence * @param resultParser/*from w ww . j ava 2s . co m*/ * @throws Exception */ public void sendDataToServer(CardiosoftInstrumentResultParser resultParser) { Map<String, Data> outputToSend = new HashMap<String, Data>(); try { for (PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class) .getPropertyDescriptors()) { if (!pd.getName().equalsIgnoreCase("doc") && !pd.getName().equalsIgnoreCase("xpath") && !pd.getName().equalsIgnoreCase("xmldocument") && !pd.getName().equalsIgnoreCase("class")) { Object value = pd.getReadMethod().invoke(resultParser); if (value != null) { if (value instanceof Long) { // We need to subtract one to the birthday month since the month of January is represented by "0" in // java.util.Calendar (January is represented by "1" in Cardiosoft). if (pd.getName().equals("participantBirthMonth")) { outputToSend.put(pd.getName(), DataBuilder.buildInteger(((Long) value) - 1)); } else { outputToSend.put(pd.getName(), DataBuilder.buildInteger((Long) value)); } } else if (value instanceof Double) { outputToSend.put(pd.getName(), DataBuilder.buildDecimal((Double) value)); } else { outputToSend.put(pd.getName(), DataBuilder.buildText(value.toString())); } } else { // send null values as well (ONYX-585) log.info("Output parameter " + pd.getName() + " was null; will send null to server"); if (pd.getPropertyType().isAssignableFrom(Long.class)) { log.info("Output parameter " + pd.getName() + " is of type INTEGER"); outputToSend.put(pd.getName(), new Data(DataType.INTEGER, null)); } else if (pd.getPropertyType().isAssignableFrom(Double.class)) { log.info("Output parameter " + pd.getName() + " is of type DECIMAL"); outputToSend.put(pd.getName(), new Data(DataType.DECIMAL, null)); } else { log.info("Output parameter " + pd.getName() + " is of type TEXT"); outputToSend.put(pd.getName(), new Data(DataType.TEXT, null)); } } } } // Save the xml and pdf files File xmlFile = new File(getExportPath(), getXmlFileName()); outputToSend.put("xmlFile", DataBuilder.buildBinary(xmlFile)); File pdfRestingEcgFile = new File(getExportPath(), getPdfFileNameRestingEcg()); outputToSend.put("pdfFile", DataBuilder.buildBinary(pdfRestingEcgFile)); File pdfFullEcgFile = new File(getExportPath(), getPdfFileNameFullEcg()); outputToSend.put("pdfFileFull", DataBuilder.buildBinary(pdfFullEcgFile)); instrumentExecutionService.addOutputParameterValues(outputToSend); } catch (Exception e) { throw new RuntimeException(e); } }