Example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors.

Prototype

public static PropertyDescriptor[] getPropertyDescriptors(Object bean) 

Source Link

Document

Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.

For more details see PropertyUtilsBean.

Usage

From source file:net.mojodna.searchable.AbstractBeanIndexer.java

/**
 * Process a bean.//from w ww  .ja v a2 s .  co m
 * 
 * @param doc Document to add fields to.
 * @param bean Bean to process.
 * @param stack Stack containing parent field names.
 * @param boost Boost factor to apply to fields.
 * @return Document with additional fields.
 * @throws IndexingException
 */
private Document processBean(final Document doc, final Searchable bean, final Stack<String> stack,
        final float boost) throws IndexingException {
    // iterate through fields
    for (final PropertyDescriptor d : PropertyUtils.getPropertyDescriptors(bean)) {
        if (SearchableUtils.containsIndexAnnotations(d))
            addBeanFields(doc, bean, d, stack, boost);

        if (SearchableUtils.containsSortableAnnotations(d))
            addSortableFields(doc, bean, d, stack);
    }
    return doc;
}

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.
 */// ww w  .j  a v  a2s .  co 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:com.opengamma.language.object.ObjectFunctionProvider.java

protected void loadGetAndSet(final ObjectInfo object, final Collection<MetaFunction> definitions,
        final String category) {
    if (object.getLabel() != null) {
        final Class<?> clazz = object.getObjectClass();
        final Set<String> attributes = new HashSet<String>(object.getDirectAttributes());
        for (PropertyDescriptor prop : PropertyUtils.getPropertyDescriptors(clazz)) {
            final AttributeInfo attribute = object.getDirectAttribute(prop.getName());
            if (attribute != null) {
                if (attribute.isReadable()) {
                    final Method read = PropertyUtils.getReadMethod(prop);
                    if (read != null) {
                        loadObjectGetter(object, attribute, read, definitions, category);
                        attributes.remove(prop.getName());
                    }/* w w w .  j  av  a2s  . com*/
                }
                if (attribute.isWriteable()) {
                    final Method write = PropertyUtils.getWriteMethod(prop);
                    if (write != null) {
                        loadObjectSetter(object, attribute, write, definitions, category);
                        attributes.remove(prop.getName());
                    }
                }
            }
        }
        if (!attributes.isEmpty()) {
            for (String attribute : attributes) {
                throw new OpenGammaRuntimeException(
                        "Attribute " + attribute + " is not exposed on object " + object);
            }
        }
    }
}

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./*from w w w . j  a  v a2 s.  co m*/
 */
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:gr.interamerican.bo2.utils.JavaBeanUtils.java

/**
 * Finds the properties of a bean./*from  w  w  w.ja v  a  2 s .c om*/
 * 
 * <li>If the bean is a concrete class the properties of the bean, for which
 * there exists a setter method, a getter method or both. Properties of
 * super-types are returned as well.</li>
 * 
 * <li>If the bean is an abstract class, an empty array is returned</li>
 * 
 * <li>If the bean is an interface, the properties of the bean are returned.
 * The method also queries all super-interfaces and fetches their properties
 * as well.</li>
 * 
 * @param type
 *            the bean
 * @return Returns the property descriptors of a java bean.
 * 
 * TODO: Support properties of abstract classes.
 */
public static PropertyDescriptor[] getBeansProperties(Class<?> type) {

    ArrayList<PropertyDescriptor> propertyDescriptor = new ArrayList<PropertyDescriptor>();

    for (PropertyDescriptor p : PropertyUtils.getPropertyDescriptors(type)) {
        if (!propertyDescriptor.contains(p) && !p.getName().equals("class")) { //$NON-NLS-1$
            propertyDescriptor.add(p);
        }
    }

    if (type.isInterface()) {
        Class<?>[] classArray = type.getInterfaces();
        PropertyDescriptor[] pdArray;
        for (Class<?> next : classArray) {
            pdArray = getBeansProperties(next);
            for (PropertyDescriptor pd : pdArray) {
                if (!propertyDescriptor.contains(pd)) {
                    propertyDescriptor.add(pd);
                }
            }
        }
    }
    return propertyDescriptor.toArray(new PropertyDescriptor[0]);
}

From source file:ca.sqlpower.object.PersistedSPObjectTest.java

/**
 * This test will be run for each object that extends SPObject and confirms
 * the SPSessionPersister can create new objects 
 * @throws Exception/*from  www .  j  a va 2  s.  c  o m*/
 */
public void testPersisterCreatesNewObjects() throws Exception {
    SPObjectRoot newRoot = new SPObjectRoot();
    WorkspaceContainer stub = new StubWorkspaceContainer() {
        private final SPObject workspace = new StubWorkspace(this, this, root);

        @Override
        public SPObject getWorkspace() {
            return workspace;
        }
    };
    newRoot.setParent(stub.getWorkspace());
    NewValueMaker valueMaker = createNewValueMaker(root, getPLIni());

    NewValueMaker newValueMaker = createNewValueMaker(newRoot, getPLIni());

    SessionPersisterSuperConverter newConverter = new SessionPersisterSuperConverter(getPLIni(), newRoot);

    SPSessionPersister persister = new TestingSessionPersister("Test persister", newRoot, newConverter);
    persister.setWorkspaceContainer(stub);

    for (SPObject child : root.getChildren()) {
        copyToRoot(child, newValueMaker);
    }

    SPObject objectUnderTest = getSPObjectUnderTest();

    Set<String> propertiesToPersist = findPersistableBeanProperties(false, false);

    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass()));

    //set all properties of the object
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (!propertiesToPersist.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        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;
        }

        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());
        Object newValInNewRoot = newValueMaker.makeNewValue(property.getPropertyType(), oldVal,
                property.getName());
        if (newValInNewRoot instanceof SPObject) {
            ((SPObject) newValInNewRoot).setUUID(((SPObject) newVal).getUUID());
        }

        try {
            logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(objectUnderTest, property.getName(), newVal);

        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + objectUnderTest.getClass().getName());
        }
    }

    //create a new root and parent for the object
    SPObject newParent;
    if (objectUnderTest.getParent() instanceof SPObjectRoot) {
        newParent = newRoot;
    } else {
        newParent = (SPObject) newValueMaker.makeNewValue(objectUnderTest.getParent().getClass(), null, "");
    }
    newParent.setUUID(objectUnderTest.getParent().getUUID());

    int childCount = newParent.getChildren().size();

    //persist the object to the new target root
    Class<? extends SPObject> classChildType = PersisterUtils.getParentAllowedChildType(
            objectUnderTest.getClass().getName(), objectUnderTest.getParent().getClass().getName());
    new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest,
            objectUnderTest.getParent().getChildren(classChildType).indexOf(objectUnderTest));

    //check object exists
    assertEquals(childCount + 1, newParent.getChildren().size());
    SPObject newChild = null;
    for (SPObject child : newParent.getChildren()) {
        if (child.getUUID().equals(objectUnderTest.getUUID())) {
            newChild = child;
            break;
        }
    }
    if (newChild == null)
        fail("The child was not correctly persisted.");

    //check all interesting properties
    for (PropertyDescriptor property : settableProperties) {
        if (!propertiesToPersist.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        Method readMethod = property.getReadMethod();

        Object valueBeforePersist = readMethod.invoke(objectUnderTest);
        Object valueAfterPersist = readMethod.invoke(newChild);
        Object basicValueBeforePersist = getConverter().convertToBasicType(valueBeforePersist);
        Object basicValueAfterPersist = newConverter.convertToBasicType(valueAfterPersist);

        assertPersistedValuesAreEqual(valueBeforePersist, valueAfterPersist, basicValueBeforePersist,
                basicValueAfterPersist, readMethod.getReturnType());
    }
}

From source file:jp.go.nict.langrid.p2pgridbasis.data.langrid.converter.ConvertUtil.java

public static void decode(DataAttributes from, Object to) throws DataConvertException {
    setLangridConverter();//from   w  ww .j a va 2  s  .  c  om
    logger.debug("##### decode #####");
    try {
        for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(to)) {
            logger.debug(
                    "Name : " + descriptor.getName() + " / PropertyType : " + descriptor.getPropertyType());
            Object value = from.getValue(descriptor.getName());
            if (PropertyUtils.isWriteable(to, descriptor.getName()) && value != null) {
                //Write OK
                try {
                    Converter converter = ConvertUtils.lookup(descriptor.getPropertyType());
                    if (!ignoreProps.contains(descriptor.getName())) {
                        if (converter == null) {
                            logger.error("no converter is registered : " + descriptor.getName() + " "
                                    + descriptor.getPropertyType());
                        } else {
                            Object obj = converter.convert(descriptor.getPropertyType(), value);
                            PropertyUtils.setProperty(to, descriptor.getName(), obj);
                        }
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                    logger.info(e.getMessage());
                } catch (NoSuchMethodException e) {
                    logger.info(e.getMessage());
                }
            } else {
                if (value != null) {
                    //Write NG
                    logger.debug("isWriteable = false");
                } else {
                    //Write NG
                    logger.debug("value = null");
                }
            }
        }
    } catch (IllegalAccessException e) {
        throw new DataConvertException(e);
    } catch (InvocationTargetException e) {
        throw new DataConvertException(e);
    }
}

From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java

protected Collection<AutoPropertyTemplate> getProperties(Class<?> type, XmlNodeInfo xmlNodeInfo,
        InitializerContext initializerContext) throws Exception {
    HashMap<String, AutoPropertyTemplate> properties = new LinkedHashMap<String, AutoPropertyTemplate>();
    RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager();

    if (xmlNodeInfo != null) {
        if (xmlNodeInfo.isInheritable()) {
            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("impl");
            propertyTemplate.setPrimitive(true);
            properties.put(propertyTemplate.getName(), propertyTemplate);

            propertyTemplate = new AutoPropertyTemplate("parent");
            propertyTemplate.setPrimitive(true);
            properties.put(propertyTemplate.getName(), propertyTemplate);
        }//from  w  ww  .ja  v  a 2s.  c  o m

        if (xmlNodeInfo.isScopable()) {
            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("scope");
            propertyTemplate.setPrimitive(true);

            Object[] ecs = Scope.class.getEnumConstants();
            String[] enumValues = new String[ecs.length];
            for (int i = 0; i < ecs.length; i++) {
                enumValues[i] = ecs[i].toString();
            }
            propertyTemplate.setEnumValues(enumValues);

            properties.put(propertyTemplate.getName(), propertyTemplate);
        }

        if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) {
            Class<?> definitionType = ClassUtils.forName(xmlNodeInfo.getDefinitionType());
            if (ListenableObjectDefinition.class.isAssignableFrom(definitionType)) {
                AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("listener");
                propertyTemplate.setPrimitive(true);
                properties.put(propertyTemplate.getName(), propertyTemplate);
            }

            if (InterceptableDefinition.class.isAssignableFrom(definitionType)) {
                AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("interceptor");
                propertyTemplate.setPrimitive(true);
                properties.put(propertyTemplate.getName(), propertyTemplate);
            }
        }

        for (Map.Entry<String, String> entry : xmlNodeInfo.getFixedProperties().entrySet()) {
            String propertyName = entry.getKey();
            String value = entry.getValue();

            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName);
            propertyTemplate.setDefaultValue(value);
            propertyTemplate.setPrimitive(true);
            propertyTemplate.setFixed(true);
            propertyTemplate.setVisible(false);
            properties.put(propertyName, propertyTemplate);
        }

        for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) {
            String propertyName = entry.getKey();
            XmlProperty xmlProperty = entry.getValue();
            TypeInfo propertyTypeInfo = TypeInfo.parse(xmlProperty.propertyType());
            Class<?> propertyType = null;
            if (propertyTypeInfo != null) {
                propertyType = propertyTypeInfo.getType();
            }

            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName, xmlProperty);
            propertyTemplate.setPrimitive(xmlProperty.attributeOnly());
            if (propertyType != null && !propertyType.equals(String.class)) {
                propertyTemplate.setType(propertyType.getName());
            }

            if (xmlProperty.composite()) {
                initCompositeProperty(propertyTemplate, propertyType, initializerContext);
            }
            propertyTemplate.setDeprecated(xmlProperty.deprecated());

            properties.put(propertyName, propertyTemplate);
        }
    }

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && propertyDescriptor.getWriteMethod() != null) {
            if (readMethod.getDeclaringClass() != type) {
                try {
                    readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    continue;
                }
            }

            String propertyName = propertyDescriptor.getName();

            XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
            if (xmlSubNode != null) {
                continue;
            }

            TypeInfo propertyTypeInfo;
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            if (Collection.class.isAssignableFrom(propertyType)) {
                propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true);
                propertyType = propertyTypeInfo.getType();
            } else {
                propertyTypeInfo = new TypeInfo(propertyType, false);
            }

            AutoPropertyTemplate propertyTemplate = null;
            XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class);
            if (xmlProperty != null) {
                if (xmlProperty.unsupported()) {
                    continue;
                }

                propertyTemplate = properties.get(propertyName);
                if (propertyTemplate == null) {
                    propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty);
                    propertyTemplate.setPrimitive(xmlProperty.attributeOnly());
                }

                if (("dataSet".equals(propertyName) || "dataPath".equals(propertyName)
                        || "property".equals(propertyName)) && DataControl.class.isAssignableFrom(type)) {
                    propertyTemplate.setHighlight(1);
                }

                if (xmlProperty.composite()) {
                    initCompositeProperty(propertyTemplate, propertyType, initializerContext);
                }

                int clientTypes = ClientType.parseClientTypes(xmlProperty.clientTypes());
                if (clientTypes > 0) {
                    propertyTemplate.setClientTypes(clientTypes);
                }
                propertyTemplate.setDeprecated(xmlProperty.deprecated());
            } else if (EntityUtils.isSimpleType(propertyType) || propertyType.equals(Class.class)
                    || propertyType.isArray() && propertyType.getComponentType().equals(String.class)) {
                propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty);
            }

            if (propertyTemplate != null) {
                propertyTemplate.setType(propertyDescriptor.getPropertyType().getName());

                if (propertyType.isEnum()) {
                    Object[] ecs = propertyType.getEnumConstants();
                    String[] enumValues = new String[ecs.length];
                    for (int i = 0; i < ecs.length; i++) {
                        enumValues[i] = ecs[i].toString();
                    }
                    propertyTemplate.setEnumValues(enumValues);
                }

                ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class);
                if (componentReference != null) {
                    ReferenceTemplate referenceTemplate = new LazyReferenceTemplate(ruleTemplateManager,
                            componentReference.value(), "id");
                    propertyTemplate.setReference(referenceTemplate);
                }

                IdeProperty ideProperty = readMethod.getAnnotation(IdeProperty.class);
                if (ideProperty != null) {
                    propertyTemplate.setVisible(ideProperty.visible());
                    propertyTemplate.setEditor(ideProperty.editor());
                    propertyTemplate.setHighlight(ideProperty.highlight());
                    if (StringUtils.isNotEmpty(ideProperty.enumValues())) {
                        propertyTemplate.setEnumValues(StringUtils.split(ideProperty.enumValues(), ",;"));
                    }
                }

                ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class);
                if (clientProperty != null) {
                    propertyTemplate.setDefaultValue(clientProperty.escapeValue());
                }

                properties.put(propertyName, propertyTemplate);
            }
        }
    }
    return properties.values();
}

From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java

/**
 * Tests that calling/*from   w  w  w . ja  va2s . c  om*/
 * {@link SPPersister#persistObject(String, String, String, int)} for a
 * session persister will create a new object and set all of the properties
 * on the object.
 */
public void testPersisterAddsNewObject() throws Exception {

    SPObject wo = getObjectUnderTest();
    wo.setMagicEnabled(false);

    WabitSessionPersister persister = new WabitSessionPersister("test persister", session,
            session.getWorkspace(), true);
    WorkspacePersisterListener listener = new WorkspacePersisterListener(session, persister, true);

    WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter(
            new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true);

    List<PropertyDescriptor> settableProperties;
    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass()));

    //Set all possible values to new values for testing.
    Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents();
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEvents.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        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());

        try {
            logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(wo, property.getName(), newVal);

        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + wo.getClass().getName());
        }
    }

    SPObject parent = wo.getParent();
    int oldChildCount = parent.getChildren().size();

    listener.transactionStarted(null);
    listener.childRemoved(
            new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().indexOf(wo), EventType.REMOVED));
    listener.transactionEnded(null);

    //persist the object
    wo.setParent(parent);
    listener.transactionStarted(null);
    listener.childAdded(
            new SPChildEvent(parent, wo.getClass(), wo, parent.getChildren().size(), EventType.ADDED));
    listener.transactionEnded(null);

    //the object must now be added to the super parent
    assertEquals(oldChildCount, parent.getChildren().size());
    SPObject persistedObject = parent.getChildren().get(parent.childPositionOffset(wo.getClass()));
    persistedObject.setMagicEnabled(false);

    //check all the properties are what we expect on the new object
    Set<String> ignorableProperties = getPropertiesToNotPersistOnObjectPersist();

    List<String> settablePropertyNames = new ArrayList<String>();
    for (PropertyDescriptor pd : settableProperties) {
        settablePropertyNames.add(pd.getName());
    }

    settablePropertyNames.removeAll(ignorableProperties);

    for (String persistedPropertyName : settablePropertyNames) {
        Class<?> classType = null;
        for (PropertyDescriptor propertyDescriptor : settableProperties) {
            if (propertyDescriptor.getName().equals(persistedPropertyName)) {
                classType = propertyDescriptor.getPropertyType();
                break;
            }
        }

        logger.debug("Persisted object is of type " + persistedObject.getClass());
        Object oldVal = PropertyUtils.getSimpleProperty(wo, persistedPropertyName);
        Object newVal = PropertyUtils.getSimpleProperty(persistedObject, persistedPropertyName);

        //XXX will replace this later
        List<Object> additionalVals = new ArrayList<Object>();
        if (wo instanceof OlapQuery && persistedPropertyName.equals("currentCube")) {
            additionalVals.add(((OlapQuery) wo).getOlapDataSource());
        }

        Object basicOldVal = converterFactory.convertToBasicType(oldVal, additionalVals.toArray());
        Object basicNewVal = converterFactory.convertToBasicType(newVal, additionalVals.toArray());

        logger.debug("Property " + persistedPropertyName + ". oldVal is \"" + basicOldVal
                + "\" but newVal is \"" + basicNewVal + "\"");

        assertPersistedValuesAreEqual(oldVal, newVal, basicOldVal, basicNewVal, classType);
    }

}

From source file:ca.sqlpower.object.PersistedSPObjectTest.java

/**
 * Tests passing an object to an {@link SPPersisterListener} will persist
 * the object and all of the properties that have setters.
 *//*from w  w w. j  a  v  a  2s.com*/
public void testSPListenerPersistsNewObjects() throws Exception {
    CountingSPPersister persister = new CountingSPPersister();
    NewValueMaker valueMaker = createNewValueMaker(root, getPLIni());

    SPObject objectUnderTest = getSPObjectUnderTest();

    Set<String> propertiesToPersist = findPersistableBeanProperties(false, false);

    List<PropertyDescriptor> settableProperties = Arrays
            .asList(PropertyUtils.getPropertyDescriptors(objectUnderTest.getClass()));

    //set all properties of the object
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (!propertiesToPersist.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        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;
        }

        Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());

        try {
            logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(objectUnderTest, property.getName(), newVal);

        } catch (InvocationTargetException e) {
            logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + objectUnderTest.getClass().getName());
        }
    }

    //persist the object to the new target root
    new SPPersisterListener(persister, getConverter()).persistObject(objectUnderTest,
            objectUnderTest.getParent().getChildren(objectUnderTest.getClass()).indexOf(objectUnderTest));

    assertTrue(persister.getPersistPropertyCount() > 0);

    assertEquals(getSPObjectUnderTest().getUUID(), persister.getPersistObjectList().get(0).getUUID());

    //set all properties of the object
    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (!propertiesToPersist.contains(property.getName()))
            continue;
        if (property.getName().equals("parent"))
            continue; //Changing the parent causes headaches.

        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;
        }

        Object newValue = null;

        boolean found = false;
        for (PersistedSPOProperty persistedSPO : persister.getPersistPropertyList()) {
            if (persistedSPO.getPropertyName().equals(property.getName())
                    && persistedSPO.getUUID().equals(getSPObjectUnderTest().getUUID())) {
                newValue = persistedSPO.getNewValue();
                found = true;
                break;
            }
        }

        assertTrue("Could not find the persist call for property " + property.getName(), found);

        if (oldVal == null) {
            assertNull(newValue);
        } else {
            assertPersistedValuesAreEqual(oldVal,
                    getConverter().convertToComplexType(newValue, oldVal.getClass()),
                    getConverter().convertToBasicType(oldVal), newValue, property.getPropertyType());
        }
    }
}