Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getPropertyType.

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:org.openspotlight.persist.support.SimplePersistImpl.java

private void fillBeanParent(final List<PropertyDescriptor> parentPropertyDescriptors, final Object bean,
        final Object beanParent) throws Exception {
    if (beanParent != null) {
        final Class<?> parentType = beanParent.getClass();
        for (final PropertyDescriptor descriptor : parentPropertyDescriptors) {
            if (descriptor.getPropertyType().isAssignableFrom(parentType)) {
                descriptor.getWriteMethod().invoke(bean, beanParent);
                break;
            }// ww  w  .j a  va2 s.  c o m
        }
    }
}

From source file:org.ajax4jsf.templatecompiler.el.ELCompiler.java

private boolean processingValue(AstValue node, StringBuffer sb, CompilationContext componentBean) {
    String lastIndexValue = "null";
    String lastVariableType = null;
    List<String> names = new ArrayList<String>();

    for (int i = 0; i < node.jjtGetNumChildren(); i++) {
        StringBuffer sb1 = new StringBuffer();
        Node subChild = node.jjtGetChild(i);

        if (subChild instanceof AstIdentifier) {
            String variableName = subChild.getImage();
            if (componentBean.containsVariable(variableName)) {
                lastVariableType = componentBean.getVariableType(variableName).getName();
                names.add(variableName);
            } else {
                processingIdentifier((AstIdentifier) subChild, sb1, componentBean);
            }/*  ww w  . java 2s .  c o  m*/
        } else if (subChild instanceof AstDotSuffix) {
            String propertyName = subChild.getImage();
            log.debug("Object: " + lastVariableType + ", property: " + propertyName);

            if (lastVariableType != null) {
                try {

                    Class<?> clazz = componentBean.loadClass(lastVariableType);

                    PropertyDescriptor propertyDescriptor = getPropertyDescriptor(clazz, propertyName,
                            componentBean);

                    if (propertyDescriptor == null) {
                        throw new PropertyNotFoundException(
                                "property: " + propertyName + " not found in class: " + lastVariableType);
                    }

                    log.debug("propertyObject: " + propertyDescriptor.getPropertyType().getName());
                    StringBuffer tmpbuf = new StringBuffer();
                    tmpbuf.append(propertyDescriptor.getReadMethod().getName());
                    tmpbuf.append("()");
                    names.add(tmpbuf.toString());

                    lastVariableType = propertyDescriptor.getPropertyType().getName();
                } catch (ClassNotFoundException e) {
                    log.error(e.getLocalizedMessage(), e);
                }

            } else {

                sb1.append("getProperty(");
                sb1.append(lastIndexValue);
                sb1.append(",");
                sb1.append("\"");
                sb1.append(subChild.getImage());
                sb1.append("\")");
            }
        } else if (subChild instanceof AstBracketSuffix) {
            String bracketSuffix = processingBracketSuffix((AstBracketSuffix) subChild, componentBean);

            if (lastVariableType != null) {
                StringBuffer tmpbuf = new StringBuffer();
                if (lastVariableType.startsWith("[L")) {
                    tmpbuf.append("[");
                    tmpbuf.append(bracketSuffix);
                    tmpbuf.append("]");
                    names.add(tmpbuf.toString());
                }

                if ((lastVariableType.compareTo("java.util.List") == 0)
                        || (lastVariableType.compareTo("java.util.Map") == 0)) {
                    tmpbuf.append("get(");
                    tmpbuf.append(bracketSuffix);
                    tmpbuf.append(")");
                    names.add(tmpbuf.toString());
                }
            } else {

                sb1.append("getElelmentByIndex(");
                sb1.append(lastIndexValue);
                sb1.append(",");
                sb1.append(bracketSuffix);
                sb1.append(")");
            }

        }

    }

    if (names.size() != 0) {
        StringBuffer tmpbuf = new StringBuffer();
        for (String element : names) {
            if (tmpbuf.length() != 0) {
                tmpbuf.append(".");
            }
            tmpbuf.append(element);
        }
        sb.append(tmpbuf.toString());
    } else {
        sb.append(lastIndexValue);
    }

    return true;
}

From source file:org.openspotlight.persist.support.SimplePersistImpl.java

private <T> void fillBeanStreamProperties(final StorageNode node, final T bean,
        final List<PropertyDescriptor> streamPropertiesDescriptor) throws Exception {
    for (final PropertyDescriptor descriptor : streamPropertiesDescriptor) {
        final Class<?> propertyType = descriptor.getPropertyType();
        if (InputStream.class.isAssignableFrom(propertyType)) {
            final InputStream value = node.getPropertyValueAsStream(currentSession, descriptor.getName());
            descriptor.getWriteMethod().invoke(bean, value);
        } else if (Serializable.class.isAssignableFrom(propertyType)
                || Collection.class.isAssignableFrom(propertyType)
                || Map.class.isAssignableFrom(propertyType)) {
            final Serializable value = asObject(
                    node.getPropertyValueAsStream(currentSession, descriptor.getName()));
            descriptor.getWriteMethod().invoke(bean, getInternalMethods().beforeUnConvert((SimpleNodeType) bean,
                    value, descriptor.getReadMethod()));
        } else {// www . j a v  a 2  s  .c o  m
            throw new IllegalStateException("wrong type");
        }
    }
}

From source file:org.openmobster.core.mobileObject.xml.MobileObjectSerializer.java

private void setNestedProperty(Object mobileBean, String nestedProperty, String value,
        List<ArrayMetaData> objectMetaData) {
    try {// w w  w.j a v  a2s. c o  m
        StringTokenizer st = new StringTokenizer(nestedProperty, ".");
        Object courObj = mobileBean;
        StringBuilder propertyPath = new StringBuilder();

        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            propertyPath.append("/" + token);

            PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);
            if (token.indexOf('[') != -1 && token.indexOf(']') != -1) {
                String indexedPropertyName = token.substring(0, token.indexOf('['));
                metaData = PropertyUtils.getPropertyDescriptor(courObj, indexedPropertyName);
            }

            if (metaData == null) {
                log.error("******************************");
                log.error("MetaData Null For: " + token);
                log.error("Field Not Found on the MobileBean");
                log.error("******************************");
                continue;
            }

            if (!st.hasMoreTokens()) {
                if (Collection.class.isAssignableFrom(metaData.getPropertyType()) || (metaData.getPropertyType()
                        .isArray()
                        && !metaData.getPropertyType().getComponentType().isAssignableFrom(byte.class))) {
                    //An IndexedProperty
                    this.initializeIndexedProperty(courObj, token, metaData, objectMetaData,
                            propertyPath.toString());

                    if (metaData.getPropertyType().isArray()) {
                        PropertyUtils.setNestedProperty(mobileBean, nestedProperty,
                                ConvertUtils.convert(value, metaData.getPropertyType().getComponentType()));
                    } else {
                        PropertyUtils.setNestedProperty(mobileBean, nestedProperty,
                                ConvertUtils.convert(value, metaData.getPropertyType()));
                    }
                } else {
                    //A Simple Property                                          
                    if (metaData.getPropertyType().isArray()
                            && metaData.getPropertyType().getComponentType().isAssignableFrom(byte.class)) {
                        BeanUtils.setProperty(mobileBean, nestedProperty, Utilities.decodeBinaryData(value));
                    } else {
                        PropertyUtils.setNestedProperty(mobileBean, nestedProperty,
                                ConvertUtils.convert(value, metaData.getPropertyType()));
                    }
                }
            } else {
                if (Collection.class.isAssignableFrom(metaData.getPropertyType())
                        || metaData.getPropertyType().isArray()) {
                    //An IndexedProperty   
                    courObj = this.initializeIndexedProperty(courObj, token, metaData, objectMetaData,
                            propertyPath.toString());
                } else {
                    //A Simple Property
                    courObj = this.initializeSimpleProperty(courObj, token, metaData);
                }
            }
        }
    } catch (Exception e) {
        log.info("---------------------------------------------------");
        log.info("Blowing Up on---------" + nestedProperty);
        log.info("---------------------------------------------------");
        log.error(this, e);
        throw new RuntimeException(e);
    }
}

From source file:org.jaffa.soa.dataaccess.DataTransformer.java

/**
 * Mould data from domain object and its related objects into a new JavaBean based
 * domain object graph, based on the defined mapping rules.
 *
 * @param source           Source object to mould data from, typically extends Persistent
 * @param target           Target object to mould data to, typically extends GraphDataObject
 * @param graph            The mapping class with the rules of how to map this source object
 * @param filter           Filter object that it is used to control what fields are populated or the target objects
 * @param objectPath       The path of this object being processed. This identifies possible parent
 *                         and/or indexed entries where this object is contained.
 * @param includeKeys      true if key fields should be included in results regardless of the filters
 * @param originalCriteria the original graph criteria.
 * @param handler          Possible bean handler to be used when processing this source object graph
 * @throws ApplicationExceptions Thrown if one or more application logic errors are generated during moulding
 * @throws FrameworkException    Thrown if any runtime moulding error has occured.
 *//*w w w .  j  a  v  a  2s.c om*/
public static void buildGraphFromDomain(Object source, Object target, GraphMapping graph, MappingFilter filter,
        String objectPath, boolean includeKeys, GraphCriteria originalCriteria, ITransformationHandler handler)
        throws ApplicationExceptions, FrameworkException {

    if (graph == null)
        graph = MappingFactory.getInstance(target);

    boolean useQueryDomain = graph.getQueryDomainClass() != null
            && source.getClass().isAssignableFrom(graph.getQueryDomainClass());

    //throw new InstantiationException("A GraphMapping must be supplied");
    if (filter == null)
        filter = MappingFilter.getInstance(graph);

    try {
        // get list of target fileds to populate
        String[] tFields = graph.getDataFieldNames();
        if (tFields != null && tFields.length != 0)
            for (int i = 0; i < tFields.length; i++) {
                // Try to map a source to a target
                String tName = tFields[i];
                String fullName = tName;
                if (objectPath != null)
                    fullName = objectPath + "." + fullName;

                if (filter == null || filter.isFieldIncluded(fullName)
                        || (includeKeys && graph.isKeyField(tName))) {
                    String sName = graph.getDomainFieldName(tName);
                    AccessibleObject tAccessibleObject = graph.getDataMutator(tName);
                    PropertyDescriptor tDesc = graph.getDataFieldDescriptor(tName);
                    PropertyDescriptor sDesc = useQueryDomain ? graph.getQueryDomainFieldDescriptor(tName)
                            : graph.getDomainFieldDescriptor(tName);

                    if (useQueryDomain && sDesc == null)
                        continue;

                    // Based on validation in GraphMapping, that there is a
                    // GraphObject descriptor with a setter, and a DO descriptor with a getter
                    if (sDesc == null)
                        log.error("No Getter for " + tName + " in path " + fullName);

                    // incase getter is not public, make it available
                    Method sm = sDesc.getReadMethod();
                    if (!sm.isAccessible())
                        sm.setAccessible(true);

                    // Set the value if the source and target are the same datatype
                    Class tClass = tDesc.getPropertyType();
                    Class sClass = sDesc.getPropertyType();
                    if (tClass.isAssignableFrom(sClass)) {
                        // Get the value being copied
                        Object sValue = sm.invoke(source, (Object[]) null);
                        setValue(tAccessibleObject, target, sValue);
                        if (log.isDebugEnabled())
                            log.debug("Set " + tName + " = " + sValue);

                        // See if there is a datatype mapper for these classes
                    } else if (DataTypeMapper.instance().isMappable(sClass, tClass)) {
                        // Get the value being copied
                        Object sValue = sm.invoke(source, (Object[]) null);
                        if (sValue != null) {
                            sValue = DataTypeMapper.instance().map(sValue, tClass);
                            if (log.isDebugEnabled())
                                log.debug("Set " + tName + " = " + sValue);
                        }
                        setValue(tAccessibleObject, target, sValue);

                        // See if target is a GraphObject, this could be a foreign object or one-to-one relationship...
                    } else if (GraphDataObject.class.isAssignableFrom(tClass)
                            && IPersistent.class.isAssignableFrom(sClass)) {
                        // Get the mapper for the related GraphObject, if it has keys, it must be a foriegn object
                        if (graph.isForeignField(tName)) {
                            // look at foreign key fields, and make sure they are not null
                            List foreignKeys = graph.getForeignKeys(tName);
                            List foreignKeyValues = new ArrayList();
                            boolean nullKey = false;
                            for (Iterator k = foreignKeys.iterator(); k.hasNext();) {
                                String doProp = (String) k.next();
                                Object value = null;
                                PropertyDescriptor doPd = graph.getRealDomainFieldDescriptor(doProp);
                                if (doPd != null && doPd.getReadMethod() != null) {
                                    Method m = doPd.getReadMethod();
                                    if (!m.isAccessible())
                                        m.setAccessible(true);
                                    value = m.invoke(source, new Object[] {});
                                    if (value == null)
                                        nullKey = true;
                                    foreignKeyValues.add(value);
                                } else {
                                    throw new TransformException(TransformException.INVALID_FK_MAPPING,
                                            objectPath, doProp, graph.getDomainClassShortName());
                                }
                            }
                            if (nullKey) {
                                if (log.isDebugEnabled())
                                    log.debug("Did not create skeleton object '" + tClass.getName()
                                            + "': one or more foreign key values missing.");
                            } else {
                                // Create the foreign object
                                if (log.isDebugEnabled())
                                    log.debug("Creating foreign object - " + tClass.getName());
                                Object newGDO = newGraphDataObject(tClass);
                                boolean createSkeleton = true;
                                // Only retrieve related domain object and introspect if need
                                if (filter.areSubFieldsIncluded(fullName)) {
                                    // read object and introspect all
                                    if (log.isDebugEnabled())
                                        log.debug("Read foreign object '" + fullName + "' and mold");
                                    try {
                                        Object sValue = sm.invoke(source, (Object[]) null);
                                        if (sValue != null) {
                                            DataTransformer.buildGraphFromDomain(sValue, newGDO, null, filter,
                                                    fullName, true, originalCriteria, handler);
                                            createSkeleton = false;
                                        }
                                    } catch (InvocationTargetException e) {
                                        // If the foreign object is not found, create the skeleton
                                        if (e.getCause() != null
                                                && e.getCause() instanceof InvalidForeignKeyException) {
                                            if (log.isDebugEnabled())
                                                log.debug(
                                                        "All foreign keys present, but foreign object does not exist",
                                                        e);
                                        } else
                                            throw e;
                                    }
                                }
                                if (createSkeleton) {
                                    // just set foreign keys from current object
                                    if (log.isDebugEnabled())
                                        log.debug("Set keys on skeleton foreign object only");
                                    GraphMapping graph2 = MappingFactory.getInstance(newGDO);
                                    Set keys = graph2.getKeyFields();
                                    if (keys == null || keys.size() != foreignKeyValues.size()) {
                                        throw new TransformException(TransformException.MISMATCH_FK_MAPPING,
                                                objectPath, target.getClass().getName(),
                                                newGDO.getClass().getName());
                                    }
                                    int k2 = 0;
                                    // Look through all the foreign keys on the skeleton object
                                    for (Iterator k = keys.iterator(); k.hasNext(); k2++) {
                                        String keyField = (String) k.next();
                                        Object keyValue = foreignKeyValues.get(k2);
                                        AccessibleObject accessibleObject = graph2.getDataMutator(keyField);
                                        if (accessibleObject != null) {
                                            setValue(accessibleObject, newGDO, keyValue);
                                        } else {
                                            throw new TransformException(TransformException.CANT_SET_KEY_FIELD,
                                                    objectPath, keyField, newGDO.getClass().getName());
                                        }
                                    }
                                }
                                setValue(tAccessibleObject, target, newGDO);
                                if (log.isDebugEnabled())
                                    log.debug("Set " + tName + " = " + newGDO);
                            }
                        } else {
                            // This is not a foreign object, must be a related object
                            if (filter.areSubFieldsIncluded(fullName)) {
                                // Create the related object
                                if (log.isDebugEnabled())
                                    log.debug("Creating One-To-One object - " + tClass.getName());
                                Object newGDO = newGraphDataObject(tClass);
                                // read object and introspect all
                                if (log.isDebugEnabled())
                                    log.debug("Read related object '" + fullName + "' and mold");
                                Object sValue = sm.invoke(source, (Object[]) null);
                                if (sValue != null) {
                                    DataTransformer.buildGraphFromDomain(sValue, newGDO, null, filter, fullName,
                                            false, originalCriteria, handler);
                                    setValue(tAccessibleObject, target, newGDO);
                                    if (log.isDebugEnabled())
                                        log.debug("Set " + tName + " = " + newGDO);
                                } else {
                                    if (log.isDebugEnabled())
                                        log.debug("Related object '" + fullName + "' not found. Ignore it!");
                                }
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("No subfields for object " + fullName
                                            + " included. Object not retrieved");
                            }
                        } //END-related object

                        // See if Target may be an array of GraphObject's
                    } else if (tClass.isArray()
                            && GraphDataObject.class.isAssignableFrom(tClass.getComponentType())
                            && filter.areSubFieldsIncluded(fullName)) {
                        if (log.isDebugEnabled())
                            log.debug("Target is an array of GraphObject's");
                        if (sClass.isArray() && IPersistent.class.isAssignableFrom(sClass.getComponentType())) {
                            if (log.isDebugEnabled()) {
                                log.debug("Source is an array of Persistent Objects");
                                log.debug("Read related objects '" + fullName + "' and mold");
                            }
                            Object[] sArray = findRelatedObjects(source, sClass, sm, handler, originalCriteria,
                                    fullName);
                            if (sArray != null && sArray.length > 0) {
                                Object[] tArray = (Object[]) Array.newInstance(tClass.getComponentType(),
                                        sArray.length);
                                if (log.isDebugEnabled())
                                    log.debug("Translate Array of Size " + sArray.length);
                                for (int j = 0; j < sArray.length; j++) {
                                    Object newGDO = newGraphDataObject(tClass.getComponentType());
                                    DataTransformer.buildGraphFromDomain(sArray[j], newGDO, null, filter,
                                            fullName, false, originalCriteria, handler);
                                    tArray[j] = newGDO;
                                    if (log.isDebugEnabled())
                                        log.debug("Add to array [" + j + "] : " + newGDO);
                                }
                                setValue(tAccessibleObject, target, tArray);
                                if (log.isDebugEnabled())
                                    log.debug("Set Array " + tName);
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("Source Array is empty! Do Nothing");
                            }
                        } // source is DO array

                        // Error... No way to map property
                    } else {
                        String err = "Can't Mold Property " + fullName + " from " + sClass.getName() + " to "
                                + tClass.getName();
                        log.error(err);
                        throw new RuntimeException(err);
                    }
                } // is included in filtered fields
            }

        // Load flex fields
        // By default all the domain-mapped flex fields will be loaded; unless excluded by a rule
        if (source instanceof IFlexFields && target instanceof IFlexFields) {
            String fullName = (objectPath != null ? objectPath + '.' : "") + "flexBean";
            if (filter == null || filter.isFieldIncluded(fullName)) {
                if (log.isDebugEnabled())
                    log.debug("Loading FlexBean " + fullName);
                FlexBean sFlexBean = ((IFlexFields) source).getFlexBean();
                FlexBean tFlexBean = ((IFlexFields) target).getFlexBean();
                if (sFlexBean != null && tFlexBean != null) {
                    for (DynaProperty flexProperty : sFlexBean.getDynaClass().getDynaProperties()) {
                        String name = flexProperty.getName();
                        Boolean include = filter.includeField(fullName + '.' + name);
                        if (include != null ? include
                                : ((FlexProperty) flexProperty).getFlexInfo()
                                        .getProperty("domain-mapping") != null) {
                            Object value = sFlexBean.get(name);
                            if (value != null) {
                                if (log.isDebugEnabled())
                                    log.debug("Loaded flex field '" + name + '=' + value + '\'');
                                tFlexBean.set(name, value);
                            }
                        }
                    }
                }
            }
        }

        // Clear changed fields on updated GraphObject
        if (target != null && target instanceof GraphDataObject)
            ((GraphDataObject) target).clearChanges();

        // Invoke the handler
        if (handler != null) {
            if (log.isDebugEnabled()) {
                log.debug("Invoking the endBeanLoad on the handler");
            }
            for (ITransformationHandler transformationHandler : handler.getTransformationHandlers()) {
                transformationHandler.endBeanLoad(objectPath, source, target, filter, originalCriteria);
            }
        }

    } catch (ApplicationException e) {
        throw new ApplicationExceptions(e);
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, objectPath,
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    } catch (InvocationTargetException e) {
        ApplicationExceptions appExps = ExceptionHelper.extractApplicationExceptions(e);
        if (appExps != null)
            throw appExps;
        FrameworkException fe = ExceptionHelper.extractFrameworkException(e);
        if (fe != null)
            throw fe;
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, objectPath, e);
        log.error(me.getLocalizedMessage(), me.getCause());
        throw me;
    } catch (InstantiationException e) {
        TransformException me = new TransformException(TransformException.INSTANTICATION_ERROR, objectPath,
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    }
}

From source file:org.openspotlight.persist.support.SimplePersistImpl.java

private <T> void fillNodeStreamProperties(final T bean,
        final List<PropertyDescriptor> streamPropertiesDescriptor, final StorageNode newNodeEntry)
        throws Exception {
    for (final PropertyDescriptor property : streamPropertiesDescriptor) {
        final Class<?> propertyType = property.getPropertyType();
        final Method readMethod = property.getReadMethod();
        final Object value = readMethod.invoke(bean);
        if (InputStream.class.isAssignableFrom(propertyType)) {
            newNodeEntry.setSimpleProperty(currentSession, property.getName(), (InputStream) value);
        } else if (Collection.class.isAssignableFrom(propertyType)) {
            final Reflection.UnwrappedCollectionTypeFromMethodReturn<Object> methodInformation = unwrapCollectionFromMethodReturn(
                    property.getReadMethod());
            if (List.class.isAssignableFrom(methodInformation.getCollectionType())) {
                newNodeEntry.setSimpleProperty(currentSession, property.getName(),
                        asStream(beforeSerializeList((List<? extends Serializable>) value, readMethod)));
            } else if (Set.class.isAssignableFrom(methodInformation.getCollectionType())) {
                newNodeEntry.setSimpleProperty(currentSession, property.getName(),
                        asStream(beforeSerializeSet((Set<? extends Serializable>) value, readMethod)));
            } else {
                throw new IllegalStateException("invalid collection type");
            }/*from  ww  w  . ja  va 2  s . c  o  m*/

        } else if (Map.class.isAssignableFrom(propertyType)) {
            newNodeEntry.setSimpleProperty(currentSession, property.getName(),
                    asStream(beforeSerializeMap((Map<? extends Serializable, ? extends Serializable>) value,
                            readMethod)));

        } else if (Serializable.class.isAssignableFrom(propertyType)) {
            if (propertyType.equals(String.class) || Number.class.isAssignableFrom(propertyType)
                    || propertyType.isPrimitive() || Boolean.class.equals(propertyType)
                    || Character.class.equals(propertyType) || Date.class.equals(propertyType)) {
                newNodeEntry.setSimpleProperty(currentSession, property.getName(),
                        Conversion.convert(value, String.class));
            } else {
                newNodeEntry.setSimpleProperty(currentSession, property.getName(),
                        asStream(beforeSerializeSerializable((Serializable) value)));
            }

        } else {
            throw new IllegalStateException("invalid type");
        }

    }
}

From source file:org.openspotlight.persist.support.SimplePersistImpl.java

private <T> void fillBeanChildren(final ConversionToBeanContext context, final StorageNode node, final T bean,
        final List<PropertyDescriptor> childrenPropertiesDescriptor) throws Exception {
    for (final PropertyDescriptor descriptor : childrenPropertiesDescriptor) {
        final Class<?> propertyType = descriptor.getPropertyType();
        Class<?> nodeType = null;
        final boolean isMultiple = Collection.class.isAssignableFrom(propertyType);
        final Method readMethod = descriptor.getReadMethod();
        if (isMultiple) {
            final Reflection.UnwrappedCollectionTypeFromMethodReturn<Object> methodDescription = unwrapCollectionFromMethodReturn(
                    readMethod);//from ww w.j a va2s .  co  m
            if (List.class.isAssignableFrom(propertyType)) {
                descriptor.getWriteMethod().invoke(bean, newLinkedList());
            } else if (Set.class.isAssignableFrom(propertyType)) {
                descriptor.getWriteMethod().invoke(bean, newHashSet());
            } else {
                throw new IllegalStateException("wrong child type");
            }
            nodeType = methodDescription.getItemType();
        } else if (SimpleNodeType.class.isAssignableFrom(propertyType)) {
            nodeType = propertyType;
        } else {
            throw new IllegalStateException("wrong child type");
        }

        if (!SimpleNodeType.class.isAssignableFrom(nodeType)) {
            throw new IllegalStateException("wrong child type");
        }
        final String childrenName = internalGetNodeName(nodeType);
        Iterable<StorageNode> children = iterableToList(
                node.getChildren(currentPartition, currentSession, childrenName));
        children = filterChildrenWithProperty(children, descriptor.getName());
        final List<Object> childrenAsBeans = newLinkedList();
        for (final StorageNode child : children) {
            childrenAsBeans.add(internalConvertNodeToBean(context, child, bean));
        }
        if (isMultiple) {
            final Collection c = (Collection) readMethod.invoke(bean);
            for (final Object o : childrenAsBeans) {
                c.add(o);
            }
            if (Comparable.class.isAssignableFrom(nodeType) && c instanceof List) {
                sort((List) c);
            }
        } else if (childrenAsBeans.size() > 0) {
            final Object value = childrenAsBeans.iterator().next();
            descriptor.getWriteMethod().invoke(bean, value);
        }
    }
}

From source file:org.kuali.rice.kns.datadictionary.validation.AttributeValidatingTypeServiceBase.java

/**
 * <p>Validates a data dictionary mapped attribute for a primitive property.</p>
 * <p>This implementation checks that the attribute is defined using the {@link DataDictionaryService} if it is
 * from a specific set of types defined in TypeUtils.  Then, if the value is not blank, it checks for errors by
 * calling//from   w  w w .j a  v a2 s .c  o m
 * {@link #validateAttributeFormat(org.kuali.rice.core.api.uif.RemotableAttributeField, String, String, String, String)}.
 * If it is blank, it checks for errors by calling
 * {@link #validateAttributeRequired(org.kuali.rice.core.api.uif.RemotableAttributeField, String, String, Object, String)}
 * .</p>
 *
 * @param typeAttributeDefinition the definition for the attribute
 * @param componentName the data dictionary component name
 * @param object the instance of the component
 * @param propertyDescriptor the descriptor for the property that the attribute maps to
 * @return a List of errors ({@link RemotableAttributeError}s) encountered during validation.  Cannot return null.
 */
protected List<RemotableAttributeError> validatePrimitiveAttributeFromDescriptor(
        TypeAttributeDefinition typeAttributeDefinition, String componentName, Object object,
        PropertyDescriptor propertyDescriptor) {

    List<RemotableAttributeError> errors = new ArrayList<RemotableAttributeError>();
    // validate the primitive attributes if defined in the dictionary
    if (null != propertyDescriptor
            && getDataDictionaryService().isAttributeDefined(componentName, propertyDescriptor.getName())) {

        Object value = ObjectUtils.getPropertyValue(object, propertyDescriptor.getName());
        Class<?> propertyType = propertyDescriptor.getPropertyType();

        if (TypeUtils.isStringClass(propertyType) || TypeUtils.isIntegralClass(propertyType)
                || TypeUtils.isDecimalClass(propertyType) || TypeUtils.isTemporalClass(propertyType)) {

            // check value format against dictionary
            if (value != null && StringUtils.isNotBlank(value.toString())) {
                if (!TypeUtils.isTemporalClass(propertyType)) {
                    errors.addAll(validateAttributeFormat(typeAttributeDefinition.getField(), componentName,
                            propertyDescriptor.getName(), value.toString(), propertyDescriptor.getName()));
                }
            } else {
                // if it's blank, then we check whether the attribute should be required
                errors.addAll(validateAttributeRequired(typeAttributeDefinition.getField(), componentName,
                        propertyDescriptor.getName(), value, propertyDescriptor.getName()));
            }
        }
    }
    return errors;
}

From source file:org.fhcrc.cpl.toolbox.filehandler.TabLoader.java

private void initColumnInfos(Class clazz) {
    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(clazz);
    HashMap<String, PropertyDescriptor> mappedPropNames = new HashMap<String, PropertyDescriptor>();
    for (PropertyDescriptor origDescriptor : origDescriptors) {
        if (origDescriptor.getName().equals("class"))
            continue;

        mappedPropNames.put(origDescriptor.getName().toLowerCase(), origDescriptor);
    }/*  ww  w . j  av a  2 s .com*/

    boolean isMapClass = java.util.Map.class.isAssignableFrom(clazz);
    for (ColumnDescriptor column : _columns) {
        PropertyDescriptor prop = mappedPropNames.get(column.name.toLowerCase());
        if (null != prop) {
            column.name = prop.getName();
            column.clazz = prop.getPropertyType();
            column.isProperty = true;
            column.setter = prop.getWriteMethod();
            if (column.clazz.isPrimitive()) {
                if (Float.TYPE.equals(column.clazz))
                    column.missingValues = 0.0F;
                else if (Double.TYPE.equals(column.clazz))
                    column.missingValues = 0.0;
                else if (Boolean.TYPE.equals(column.clazz))
                    column.missingValues = Boolean.FALSE;
                else
                    column.missingValues = 0; //Will get converted.
            }
        } else if (isMapClass) {
            column.isProperty = false;
        } else {
            column.load = false;
        }
    }
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Turn an object into a simple XML Element, supporting custom property
 * editors./* w ww.ja  v  a  2 s.c  o m*/
 * 
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * <p>
 * {@link PropertyEditor} instances can be registered with the supplied
 * {@link BeanWrapper} for custom handling of properties, e.g. dates.
 * </p>
 * 
 * @param bean
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Element
 */
protected Element getElement(BeanWrapper bean, String elementName, Document dom) {
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    Element root = null;
    root = dom.createElement(elementName);
    for (int i = 0; i < props.length; i++) {
        PropertyDescriptor prop = props[i];
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if ("class".equals(propName)) {
            continue;
        }
        Object propValue = null;
        PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName());
        if (editor != null) {
            editor.setValue(bean.getPropertyValue(propName));
            propValue = editor.getAsText();
        } else {
            propValue = bean.getPropertyValue(propName);
        }
        if (propValue == null) {
            continue;
        }
        if (log.isTraceEnabled()) {
            log.trace("attribute name: " + propName + " attribute value: " + propValue);
        }
        root.setAttribute(propName, propValue.toString());
    }
    return root;
}