Example usage for org.springframework.beans BeanWrapper getPropertyValue

List of usage examples for org.springframework.beans BeanWrapper getPropertyValue

Introduction

In this page you can find the example usage for org.springframework.beans BeanWrapper getPropertyValue.

Prototype

@Nullable
Object getPropertyValue(String propertyName) throws BeansException;

Source Link

Document

Get the current value of the specified property.

Usage

From source file:org.codehaus.groovy.grails.web.converters.ConverterUtil.java

/**
 * Reads the value of the primary identifier property of a domain class instance
 *
 * @param domainObject The domain class instance
 * @param idProperty   The GrailsDomainClassProperty
 * @return The primary identifier of the specified domain object
 */// w w  w.j  ava 2 s  . co m
protected Object extractIdValue(Object domainObject, GrailsDomainClassProperty idProperty) {
    BeanWrapper beanWrapper = new BeanWrapperImpl(domainObject);
    return beanWrapper.getPropertyValue(idProperty.getName());
}

From source file:org.codehaus.groovy.grails.web.converters.marshaller.json.DomainClassMarshaller.java

public void marshalObject(Object value, JSON json) throws ConverterException {
    JSONWriter writer = json.getWriter();

    Class clazz = value.getClass();
    GrailsDomainClass domainClass = ConverterUtil.getDomainClass(clazz.getName());
    BeanWrapper beanWrapper = new BeanWrapperImpl(value);

    writer.object();/*from   w w w .j  a  v  a2 s .co  m*/
    writer.key("class").value(domainClass.getClazz().getName());

    GrailsDomainClassProperty id = domainClass.getIdentifier();
    Object idValue = extractValue(value, id);

    json.property("id", idValue);

    if (isIncludeVersion()) {
        GrailsDomainClassProperty versionProperty = domainClass.getVersion();
        Object version = extractValue(value, versionProperty);
        json.property("version", version);
    }

    GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();

    for (GrailsDomainClassProperty property : properties) {
        writer.key(property.getName());
        if (!property.isAssociation()) {
            // Write non-relation property
            Object val = beanWrapper.getPropertyValue(property.getName());
            json.convertAnother(val);
        } else {
            Object referenceObject = beanWrapper.getPropertyValue(property.getName());
            if (isRenderDomainClassRelations()) {
                if (referenceObject == null) {
                    writer.value(null);
                } else {
                    if (referenceObject instanceof AbstractPersistentCollection) {
                        // Force initialisation and get a non-persistent Collection Type
                        AbstractPersistentCollection acol = (AbstractPersistentCollection) referenceObject;
                        acol.forceInitialization();
                        if (referenceObject instanceof SortedMap) {
                            referenceObject = new TreeMap((SortedMap) referenceObject);
                        } else if (referenceObject instanceof SortedSet) {
                            referenceObject = new TreeSet((SortedSet) referenceObject);
                        } else if (referenceObject instanceof Set) {
                            referenceObject = new HashSet((Set) referenceObject);
                        } else if (referenceObject instanceof Map) {
                            referenceObject = new HashMap((Map) referenceObject);
                        } else {
                            referenceObject = new ArrayList((Collection) referenceObject);
                        }
                    } else if (!Hibernate.isInitialized(referenceObject)) {
                        Hibernate.initialize(referenceObject);
                    }
                    json.convertAnother(referenceObject);
                }
            } else {
                if (referenceObject == null) {
                    json.value(null);
                } else {
                    GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();

                    // Embedded are now always fully rendered
                    if (referencedDomainClass == null || property.isEmbedded()
                            || GrailsClassUtils.isJdk5Enum(property.getType())) {
                        json.convertAnother(referenceObject);
                    } else if (property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
                        asShortObject(referenceObject, json, referencedDomainClass.getIdentifier(),
                                referencedDomainClass);
                    } else {
                        GrailsDomainClassProperty referencedIdProperty = referencedDomainClass.getIdentifier();
                        String refPropertyName = referencedDomainClass.getPropertyName();
                        if (referenceObject instanceof Collection) {
                            Collection o = (Collection) referenceObject;
                            writer.array();
                            for (Object el : o) {
                                asShortObject(el, json, referencedIdProperty, referencedDomainClass);
                            }
                            writer.endArray();

                        } else if (referenceObject instanceof Map) {
                            Map<Object, Object> map = (Map<Object, Object>) referenceObject;
                            for (Map.Entry<Object, Object> entry : map.entrySet()) {
                                String key = String.valueOf(entry.getKey());
                                Object o = entry.getValue();
                                writer.object();
                                writer.key(key);
                                asShortObject(o, json, referencedIdProperty, referencedDomainClass);
                                writer.endObject();
                            }
                        }
                    }
                }
            }
        }
    }
    writer.endObject();
}

From source file:org.codehaus.groovy.grails.web.converters.marshaller.json.DomainClassMarshaller.java

protected Object extractValue(Object domainObject, GrailsDomainClassProperty property) {
    BeanWrapper beanWrapper = new BeanWrapperImpl(domainObject);
    return beanWrapper.getPropertyValue(property.getName());
}

From source file:org.codehaus.groovy.grails.web.converters.marshaller.xml.DomainClassMarshaller.java

public void marshalObject(Object value, XML xml) throws ConverterException {
    Class clazz = value.getClass();
    GrailsDomainClass domainClass = ConverterUtil.getDomainClass(clazz.getName());
    BeanWrapper beanWrapper = new BeanWrapperImpl(value);

    GrailsDomainClassProperty id = domainClass.getIdentifier();
    Object idValue = beanWrapper.getPropertyValue(id.getName());

    if (idValue != null)
        xml.attribute("id", String.valueOf(idValue));

    if (includeVersion) {
        Object versionValue = beanWrapper.getPropertyValue(domainClass.getVersion().getName());
        xml.attribute("version", String.valueOf(versionValue));
    }//ww  w .j av a  2s . com

    GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();

    for (GrailsDomainClassProperty property : properties) {
        xml.startNode(property.getName());
        if (!property.isAssociation()) {
            // Write non-relation property
            Object val = beanWrapper.getPropertyValue(property.getName());
            xml.convertAnother(val);
        } else {
            Object referenceObject = beanWrapper.getPropertyValue(property.getName());
            if (isRenderDomainClassRelations()) {
                if (referenceObject == null) {
                } else {
                    if (referenceObject instanceof AbstractPersistentCollection) {
                        // Force initialisation and get a non-persistent Collection Type
                        AbstractPersistentCollection acol = (AbstractPersistentCollection) referenceObject;
                        acol.forceInitialization();
                        if (referenceObject instanceof SortedMap) {
                            referenceObject = new TreeMap((SortedMap) referenceObject);
                        } else if (referenceObject instanceof SortedSet) {
                            referenceObject = new TreeSet((SortedSet) referenceObject);
                        } else if (referenceObject instanceof Set) {
                            referenceObject = new HashSet((Set) referenceObject);
                        } else if (referenceObject instanceof Map) {
                            referenceObject = new HashMap((Map) referenceObject);
                        } else {
                            referenceObject = new ArrayList((Collection) referenceObject);
                        }
                    } else if (!Hibernate.isInitialized(referenceObject)) {
                        Hibernate.initialize(referenceObject);
                    }
                    xml.convertAnother(referenceObject);
                }
            } else {
                if (referenceObject != null) {
                    GrailsDomainClass referencedDomainClass = property.getReferencedDomainClass();

                    // Embedded are now always fully rendered
                    if (referencedDomainClass == null || property.isEmbedded()
                            || GrailsClassUtils.isJdk5Enum(property.getType())) {
                        xml.convertAnother(referenceObject);
                    } else if (property.isOneToOne() || property.isManyToOne() || property.isEmbedded()) {
                        asShortObject(referenceObject, xml, referencedDomainClass.getIdentifier(),
                                referencedDomainClass);
                    } else {
                        GrailsDomainClassProperty referencedIdProperty = referencedDomainClass.getIdentifier();
                        String refPropertyName = referencedDomainClass.getPropertyName();
                        if (referenceObject instanceof Collection) {
                            Collection o = (Collection) referenceObject;
                            for (Object el : o) {
                                xml.startNode(xml.getElementName(el));
                                asShortObject(el, xml, referencedIdProperty, referencedDomainClass);
                                xml.end();
                            }

                        } else if (referenceObject instanceof Map) {
                            Map<Object, Object> map = (Map<Object, Object>) referenceObject;
                            for (Map.Entry<Object, Object> entry : map.entrySet()) {
                                String key = String.valueOf(entry.getKey());
                                Object o = entry.getValue();
                                xml.startNode("entry").attribute("key", key);
                                asShortObject(o, xml, referencedIdProperty, referencedDomainClass);
                                xml.end();
                            }
                        }
                    }
                }
            }
        }
        xml.end();
    }
}

From source file:org.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

public static void autoAssociateBidirectionalOneToOnes(DefaultGrailsDomainClass domainClass, Object target) {
    List<GrailsDomainClassProperty> associations = domainClass.getAssociations();
    for (GrailsDomainClassProperty association : associations) {
        if (!association.isOneToOne() || !association.isBidirectional() || !association.isOwningSide()) {
            continue;
        }//from  w  w  w  .ja  v a 2 s  .com

        if (!isInitialized(target, association.getName())) {
            continue;
        }

        GrailsDomainClassProperty otherSide = association.getOtherSide();
        if (otherSide == null) {
            continue;
        }

        BeanWrapper bean = new BeanWrapperImpl(target);
        Object inverseObject = bean.getPropertyValue(association.getName());
        if (inverseObject == null) {
            continue;
        }

        if (!isInitialized(inverseObject, otherSide.getName())) {
            continue;
        }

        BeanWrapper inverseBean = new BeanWrapperImpl(inverseObject);
        Object propertyValue = inverseBean.getPropertyValue(otherSide.getName());
        if (propertyValue == null) {
            inverseBean.setPropertyValue(otherSide.getName(), target);
        }
    }
}

From source file:org.hoteia.qalingo.core.web.util.BeanUtilsBean.java

public static void copyNotNullProperties(final Object source, final Object target,
        final Iterable<String> properties) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    final BeanWrapper trg = new BeanWrapperImpl(target);
    for (final String propertyName : properties) {
        trg.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
    }/*from   www  . j av  a2 s.c  om*/
}

From source file:org.opennms.core.test.xml.XmlTest.java

private static void assertDepthEquals(final int depth, final String propertyName, final Object expected,
        Object actual) {/* w  w  w  .  j  av  a2s .c om*/
    if (expected == null && actual == null) {
        return;
    } else if (expected == null) {
        fail("expected " + propertyName + " was null but actual was not!");
    } else if (actual == null) {
        fail("actual " + propertyName + " was null but expected was not!");
    }

    final String assertionMessage = propertyName == null
            ? ("Top-level objects (" + expected.getClass().getName() + ") do not match.")
            : ("Properties " + propertyName + " do not match.");
    if (expected.getClass().getName().startsWith("java") || actual.getClass().getName().startsWith("java")) {
        // java primitives, just do assertEquals
        if (expected instanceof Object[] || actual instanceof Object[]) {
            assertTrue(assertionMessage, Arrays.equals((Object[]) expected, (Object[]) actual));
        } else {
            assertEquals(assertionMessage, expected, actual);
        }
        return;
    }

    final BeanWrapper expectedWrapper = new BeanWrapperImpl(expected);
    final BeanWrapper actualWrapper = new BeanWrapperImpl(actual);

    final Set<String> properties = new TreeSet<String>();
    for (final PropertyDescriptor descriptor : expectedWrapper.getPropertyDescriptors()) {
        properties.add(descriptor.getName());
    }
    for (final PropertyDescriptor descriptor : actualWrapper.getPropertyDescriptors()) {
        properties.add(descriptor.getName());
    }

    properties.remove("class");

    for (final String property : properties) {
        final PropertyDescriptor expectedDescriptor = expectedWrapper.getPropertyDescriptor(property);
        final PropertyDescriptor actualDescriptor = actualWrapper.getPropertyDescriptor(property);

        if (expectedDescriptor != null && actualDescriptor != null) {
            // both have descriptors, so walk the sub-objects
            Object expectedValue = null;
            Object actualValue = null;
            try {
                expectedValue = expectedWrapper.getPropertyValue(property);
            } catch (final Exception e) {
            }
            try {
                actualValue = actualWrapper.getPropertyValue(property);
            } catch (final Exception e) {
            }

            assertDepthEquals(depth + 1, property, expectedValue, actualValue);
        } else if (expectedDescriptor != null) {
            fail("Should have '" + property + "' property on actual object, but there was none!");
        } else if (actualDescriptor != null) {
            fail("Should have '" + property + "' property on expected object, but there was none!");
        }

    }

    if (expected instanceof Object[] || actual instanceof Object[]) {
        final Object[] expectedArray = (Object[]) expected;
        final Object[] actualArray = (Object[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else if (expected instanceof long[] || actual instanceof long[]) {
        final long[] expectedArray = (long[]) expected;
        final long[] actualArray = (long[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else {
        expected.getClass().isPrimitive();
        assertEquals(assertionMessage, expected, actual);
    }
}

From source file:org.opennms.protocols.xml.collector.AbstractXmlCollectionHandler.java

/**
 * Parses the string.//from   ww  w .ja  v  a  2  s .c om
 * 
 * <p>Valid placeholders are:</p>
 * <ul>
 * <li><b>ipAddr|ipAddress</b>, The Node IP Address</li>
 * <li><b>step</b>, The Collection Step in seconds</li>
 * <li><b>nodeId</b>, The Node ID</li>
 * <li><b>nodeLabel</b>, The Node Label</li>
 * <li><b>foreignId</b>, The Node Foreign ID</li>
 * <li><b>foreignSource</b>, The Node Foreign Source</li>
 * <li>Any asset property defined on the node.</li>
 * </ul>
 *
 * @param reference the reference
 * @param unformattedString the unformatted string
 * @param node the node
 * @param ipAddress the IP address
 * @param collectionStep the collection step
 * @return the string
 * @throws IllegalArgumentException the illegal argument exception
 */
protected String parseString(final String reference, final String unformattedString, final OnmsNode node,
        final String ipAddress, final Integer collectionStep) throws IllegalArgumentException {
    if (unformattedString == null || node == null)
        return null;
    String formattedString = unformattedString.replaceAll("[{](?i)(ipAddr|ipAddress)[}]", ipAddress);
    formattedString = formattedString.replaceAll("[{](?i)step[}]", collectionStep.toString());
    formattedString = formattedString.replaceAll("[{](?i)nodeId[}]", node.getNodeId());
    if (node.getLabel() != null)
        formattedString = formattedString.replaceAll("[{](?i)nodeLabel[}]", node.getLabel());
    if (node.getForeignId() != null)
        formattedString = formattedString.replaceAll("[{](?i)foreignId[}]", node.getForeignId());
    if (node.getForeignSource() != null)
        formattedString = formattedString.replaceAll("[{](?i)foreignSource[}]", node.getForeignSource());
    if (node.getAssetRecord() != null) {
        BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord());
        for (PropertyDescriptor p : wrapper.getPropertyDescriptors()) {
            Object obj = wrapper.getPropertyValue(p.getName());
            if (obj != null) {
                String objStr = obj.toString();
                try {
                    //NMS-7381 - if pulling from asset info you'd expect to not have to encode reserved words yourself.  
                    objStr = URLEncoder.encode(obj.toString(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                formattedString = formattedString.replaceAll("[{](?i)" + p.getName() + "[}]", objStr);
            }
        }
    }
    if (formattedString.matches(".*[{].+[}].*"))
        throw new IllegalArgumentException(
                "The " + reference + " " + formattedString + " contains unknown placeholders.");
    return formattedString;
}

From source file:org.springframework.beans.BeanWrapperTests.java

@Test
public void testBeanWrapperUpdates() {
    TestBean t = new TestBean();
    int newAge = 33;
    try {//from w w w. ja  v  a  2  s  . co  m
        BeanWrapper bw = new BeanWrapperImpl(t);
        t.setAge(newAge);
        Object bwAge = bw.getPropertyValue("age");
        assertTrue("Age is an integer", bwAge instanceof Integer);
        int bwi = ((Integer) bwAge).intValue();
        assertTrue("Bean wrapper must pick up changes", bwi == newAge);
    } catch (Exception ex) {
        fail("Shouldn't throw exception when everything is valid");
    }
}

From source file:org.springframework.beans.BeanWrapperTests.java

@Test
public void testBooleanObject() {
    BooleanTestBean tb = new BooleanTestBean();
    BeanWrapper bw = new BeanWrapperImpl(tb);

    bw.setPropertyValue("bool2", "true");
    assertTrue("Correct bool2 value", Boolean.TRUE.equals(bw.getPropertyValue("bool2")));
    assertTrue("Correct bool2 value", tb.getBool2().booleanValue());

    bw.setPropertyValue("bool2", "false");
    assertTrue("Correct bool2 value", Boolean.FALSE.equals(bw.getPropertyValue("bool2")));
    assertTrue("Correct bool2 value", !tb.getBool2().booleanValue());

}