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.apache.jmeter.testbeans.gui.GenericTestBeanCustomizer.java

/**
 * Create a customizer for a given test bean type.
 *
 * @param testBeanClass/*from w w w . j av  a  2  s.c  om*/
 *            a subclass of TestBean
 * @see org.apache.jmeter.testbeans.TestBean
 */
GenericTestBeanCustomizer(BeanInfo beanInfo) {
    super();

    this.beanInfo = beanInfo;

    // Get and sort the property descriptors:
    descriptors = beanInfo.getPropertyDescriptors();
    Arrays.sort(descriptors, new PropertyComparator(beanInfo));

    // Obtain the propertyEditors:
    editors = new PropertyEditor[descriptors.length];
    int scriptLanguageIndex = 0;
    int textAreaEditorIndex = 0;
    for (int i = 0; i < descriptors.length; i++) { // Index is also used for accessing editors array
        PropertyDescriptor descriptor = descriptors[i];
        String name = descriptor.getName();

        // Don't get editors for hidden or non-read-write properties:
        if (TestBeanHelper.isDescriptorIgnored(descriptor)) {
            log.debug("Skipping editor for property " + name);
            editors[i] = null;
            continue;
        }

        PropertyEditor propertyEditor;
        Object guiType = descriptor.getValue(GUITYPE);
        if (guiType instanceof TypeEditor) {
            propertyEditor = ((TypeEditor) guiType).getInstance(descriptor);
        } else if (guiType instanceof Class && Enum.class.isAssignableFrom((Class<?>) guiType)) {
            @SuppressWarnings("unchecked") // we check the class type above
            final Class<? extends Enum<?>> enumClass = (Class<? extends Enum<?>>) guiType;
            propertyEditor = new EnumEditor(descriptor, enumClass,
                    (ResourceBundle) descriptor.getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE));
        } else {
            Class<?> editorClass = descriptor.getPropertyEditorClass();
            if (log.isDebugEnabled()) {
                log.debug("Property " + name + " has editor class " + editorClass);
            }

            if (editorClass != null) {
                try {
                    propertyEditor = (PropertyEditor) editorClass.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                    log.error("Can't create property editor.", e);
                    throw new Error(e.toString());
                }
            } else {
                Class<?> c = descriptor.getPropertyType();
                propertyEditor = PropertyEditorManager.findEditor(c);
            }
        }

        if (propertyEditor == null) {
            log.warn("No editor for property: " + name + " type: " + descriptor.getPropertyType() + " in bean: "
                    + beanInfo.getBeanDescriptor().getDisplayName());
            editors[i] = null;
            continue;
        }

        if (log.isDebugEnabled()) {
            log.debug("Property " + name + " has property editor " + propertyEditor);
        }

        validateAttributes(descriptor, propertyEditor);

        if (!propertyEditor.supportsCustomEditor()) {
            propertyEditor = createWrapperEditor(propertyEditor, descriptor);

            if (log.isDebugEnabled()) {
                log.debug("Editor for property " + name + " is wrapped in " + propertyEditor);
            }
        }
        if (propertyEditor instanceof TestBeanPropertyEditor) {
            ((TestBeanPropertyEditor) propertyEditor).setDescriptor(descriptor);
        }

        if (propertyEditor instanceof TextAreaEditor) {
            textAreaEditorIndex = i;
        }
        if (propertyEditor.getCustomEditor() instanceof JScrollPane) {
            scrollerCount++;
        }

        editors[i] = propertyEditor;

        // Initialize the editor with the provided default value or null:
        setEditorValue(i, descriptor.getValue(DEFAULT));

        if (name.equals("scriptLanguage")) {
            scriptLanguageIndex = i;
        }

    }
    // In case of BSF and JSR elements i want to add textAreaEditor as a listener to scriptLanguage ComboBox.
    String beanName = this.beanInfo.getBeanDescriptor().getName();
    if (beanName.startsWith("BSF") || beanName.startsWith("JSR223")) { // $NON-NLS-1$ $NON-NLS-2$
        WrapperEditor we = (WrapperEditor) editors[scriptLanguageIndex];
        TextAreaEditor tae = (TextAreaEditor) editors[textAreaEditorIndex];
        we.addChangeListener(tae);
    }

    // Obtain message formats:
    propertyFieldLabelMessage = new MessageFormat(JMeterUtils.getResString("property_as_field_label")); //$NON-NLS-1$
    propertyToolTipMessage = new MessageFormat(JMeterUtils.getResString("property_tool_tip")); //$NON-NLS-1$

    // Initialize the GUI:
    init();
}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

protected void setPropertyValue(PropertyTokenHolder tokens, Object newValue) throws BeansException {
    String propertyName = tokens.canonicalName;

    if (tokens.keys != null) {
        // apply indexes and map keys: fetch value for all keys but the last one
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue = null;//from   w  w w.j  av a2 s . c  om
        Type type;
        try {
            propValue = getPropertyValue(getterTokens);
            type = getPropertyType(getterTokens);
            if (propValue == null) {
                Class rawType = null;
                if (type instanceof ParameterizedType) {
                    if (((ParameterizedType) type).getRawType() instanceof Class) {
                        rawType = (Class) ((ParameterizedType) type).getRawType();
                    } else if (type instanceof Class) {
                        rawType = (Class) type;
                    }
                }
                if (rawType != null && List.class.isAssignableFrom(rawType)) {
                    PropertyTokenHolder propertyTokenHolder = new PropertyTokenHolder();
                    propertyTokenHolder.actualName = getterTokens.actualName;
                    propertyTokenHolder.canonicalName = getterTokens.canonicalName;
                    setPropertyValue(propertyTokenHolder, new ArrayList());
                }
            }
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // set value for last key
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "': returned null");
        } else if (propValue.getClass().isArray()) {
            Class requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (this.extractOldValueForEditor) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue,
                        newValue, requiredType);
                Array.set(propValue, Integer.parseInt(key), convertedValue);
            } catch (IllegalArgumentException ex) {
                PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject,
                        this.nestedPath + propertyName, oldValue, newValue);
                throw new TypeMismatchException(pce, requiredType, ex);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            List list = (List) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (this.extractOldValueForEditor && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    null);
            if (index < list.size()) {
                list.set(index, convertedValue);
            } else if (index >= list.size()) {
                for (int i = list.size(); i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + list.size()
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            }
        } else if (propValue instanceof Map) {
            Map map = (Map) propValue;
            propValue.getClass().getGenericSuperclass();
            Object oldValue = null;
            if (this.extractOldValueForEditor) {
                oldValue = map.get(key);
            }
            Type type2 = ((ParameterizedType) type).getActualTypeArguments()[1];
            Type type3 = ((ParameterizedType) type).getActualTypeArguments()[0];
            Class reqClass = null;
            Class keyReqClass = null;
            if (type2 instanceof Class) {
                reqClass = (Class) type2;
            } else if (type2 instanceof ParameterizedType) {
                reqClass = (Class) ((ParameterizedType) type2).getRawType();
            }

            if (type3 instanceof Class) {
                keyReqClass = (Class) type3;
            } else if (type3 instanceof ParameterizedType) {
                keyReqClass = (Class) ((ParameterizedType) type3).getRawType();
            }
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    reqClass);
            Object convertedKey = doTypeConversionIfNecessary(key, keyReqClass);
            map.put(convertedKey, convertedValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + newValue
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName);
        if (pd == null || pd.getWriteMethod() == null) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName);
        }

        Method readMethod = pd.getReadMethod();
        Method writeMethod = pd.getWriteMethod();
        Object oldValue = null;

        if (this.extractOldValueForEditor && readMethod != null) {
            try {
                oldValue = readMethod.invoke(this.object, new Object[0]);
            } catch (Exception ex) {
                logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName,
                        ex);
            }
        }

        try {
            Object convertedValue = doTypeConversionIfNecessary(propertyName, propertyName, oldValue, newValue,
                    pd.getPropertyType());

            if (pd.getPropertyType().isPrimitive() && (convertedValue == null || "".equals(convertedValue))) {
                throw new IllegalArgumentException("Invalid value [" + newValue + "] for property '"
                        + pd.getName() + "' of primitive type [" + pd.getPropertyType() + "]");
            }

            if (logger.isDebugEnabled()) {
                logger.debug("About to invoke write method [" + writeMethod + "] on object of class ["
                        + this.object.getClass().getName() + "]");
            }
            writeMethod.invoke(this.object, new Object[] { convertedValue });
            if (logger.isDebugEnabled()) {
                logger.debug("Invoked write method [" + writeMethod + "] with value of type ["
                        + pd.getPropertyType().getName() + "]");
            }
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, newValue);
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (IllegalArgumentException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, newValue);
            throw new TypeMismatchException(pce, pd.getPropertyType(), ex);
        } catch (IllegalAccessException ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, newValue);
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private static Object deproxyObject(Class<?> targetClass, Object proxy)
        throws InstantiationException, IllegalAccessException, IntrospectionException,
        InvocationTargetException, PersistenceException, ClassNotFoundException {
    Object target = targetClass.newInstance();
    PropertyDescriptor[] targetPds = Introspector.getBeanInfo(targetClass).getPropertyDescriptors();
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getReadMethod() != null && targetPd.getWriteMethod() != null) {
            Object o = targetPd.getReadMethod().invoke(proxy, new Object[0]);
            if (o != null) {
                Class<?> propertyType = targetPd.getPropertyType();
                String className = propertyType.getName();
                if (!propertyType.isPrimitive() && !o.getClass().isPrimitive() && !(o instanceof Date)
                        && isProxy(o, className)) {
                    if (Set.class.isAssignableFrom(propertyType)) {
                        o = new LazySet();
                    } else if (List.class.isAssignableFrom(propertyType)) {
                        o = new LazyList();
                    } else
                        o = newLazyObject(propertyType);
                }/*from   w  ww.j a va2  s.  c  o m*/
                targetPd.getWriteMethod().invoke(target, o);
            }
        }
    }

    return target;
}

From source file:org.enerj.apache.commons.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>/*from  w ww . j  a v a2  s.c  om*/
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String values[] = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    int delim = findLastNestedIndex(name);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
        if (log.isTraceEnabled()) {
            log.trace("    Target bean = " + target);
            log.trace("    Target name = " + name);
        }
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the property name, index, and key values
    propName = name;
    int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (NumberFormatException e) {
            ;
        }
        propName = propName.substring(0, i);
    }
    int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (IndexOutOfBoundsException e) {
            ;
        }
        propName = propName.substring(0, j);
    }

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if ((value instanceof String) || (value == null)) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else if (getConvertUtils().lookup(value.getClass()) != null) {
            newValue = getConvertUtils().convert(value.toString(), type);
        } else {
            newValue = value;
        }
    }

    // Invoke the setter method
    try {
        if (index >= 0) {
            getPropertyUtils().setIndexedProperty(target, propName, index, newValue);
        } else if (key != null) {
            getPropertyUtils().setMappedProperty(target, propName, key, newValue);
        } else {
            getPropertyUtils().setProperty(target, propName, newValue);
        }
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

/**
 * Return the Java Class representing the property type of the specified
 * property, or <code>null</code> if there is no such property for the
 * specified bean. This method follows the same name resolution rules used
 * by <code>getPropertyDescriptor()</code>, so if the last element of a name
 * reference is indexed, the type of the property itself will be returned.
 * If the last (or only) element has no property with the specified name,
 * <code>null</code> is returned.
 * <p>//from  ww  w  .  j a va2  s  . c om
 * If the property is an indexed property (e.g. <code>String[]</code>), this
 * method will return the type of the items within that array. Note that
 * from Java 8 and newer, this method do not support such index types from
 * items within an Collection, and will instead return the collection type
 * (e.g. java.util.List) from the getter mtethod.
 *
 * @param bean
 *            Bean for which a property descriptor is requested
 * @param name
 *            Possibly indexed and/or nested name of the property for which
 *            a property descriptor is requested
 * @return The property type
 *
 * @throws IllegalAccessException
 *             if the caller does not have access to the property accessor
 *             method
 * @throws IllegalArgumentException
 *             if <code>bean</code> or <code>name</code> is null
 * @throws IllegalArgumentException
 *             if a nested reference to a property returns null
 * @throws InvocationTargetException
 *             if the property accessor method throws an exception
 * @throws NoSuchMethodException
 *             if an accessor method for this propety cannot be found
 */
public Class<?> getPropertyType(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'");
    }

    // Resolve nested references
    while (resolver.hasNested(name)) {
        final String next = resolver.next(name);
        final Object nestedBean = getProperty(bean, next);
        if (nestedBean == null) {
            throw new NestedNullException(
                    "Null property value for '" + next + "' on bean class '" + bean.getClass() + "'");
        }
        bean = nestedBean;
        name = resolver.remove(name);
    }

    // Remove any subscript from the final name value
    name = resolver.getProperty(name);

    final PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
    if (descriptor == null) {
        return null;
    } else if (descriptor instanceof IndexedPropertyDescriptor) {
        return ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
    } else if (descriptor instanceof MappedPropertyDescriptor) {
        return ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
    } else {
        return descriptor.getPropertyType();
    }

}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private static void processMethod(String className, PropertyDescriptor[] pds, Set<PropertyDescriptor> ids,
        Set<PropertyDescriptor> collections, Set<PropertyDescriptor> lazys, Set<PropertyDescriptor> eagers,
        Set<LinkFileInfo> linkedFiles, PropertyDescriptor pd) throws PersistenceException {
    Method readMethod = pd.getReadMethod();
    if (readMethod != null) {
        if (readMethod.isAnnotationPresent(Id.class)) {
            ids.add(pd);/*from w  w  w.j  ava2s.c  o m*/
            if (readMethod.isAnnotationPresent(GeneratedValue.class)) {
                generatedIdClasses.add(className);
            }
        }
        OneToMany oneToMany = readMethod.getAnnotation(OneToMany.class);
        if (oneToMany != null) {
            collections.add(pd);
        } else {
            ManyToMany manyToMany = readMethod.getAnnotation(ManyToMany.class);
            if (manyToMany != null) {
                collections.add(pd);
            } else if (INakedObject.class.isAssignableFrom(pd.getPropertyType())) {
                OneToOne oneToOne = readMethod.getAnnotation(OneToOne.class);
                if (oneToOne != null) {
                    if (oneToOne.fetch().equals(FetchType.LAZY))
                        lazys.add(pd);
                    else
                        eagers.add(pd);
                } else {
                    ManyToOne manyToOne = readMethod.getAnnotation(ManyToOne.class);
                    if (manyToOne != null) {
                        if (manyToOne.fetch().equals(FetchType.LAZY))
                            lazys.add(pd);
                        else
                            eagers.add(pd);
                    } else {
                        Basic basic = readMethod.getAnnotation(Basic.class);
                        if (basic != null) {
                            if (basic.fetch().equals(FetchType.LAZY))
                                lazys.add(pd);
                            else
                                eagers.add(pd);
                        }
                    }
                }
            }
        }
        //processLinkedFiles(pds, linkedFiles, pd);
    }
}

From source file:org.evergreen.web.utils.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>//w w w .  j  a  v a  2  s .c  o m
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {
    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String[] values = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    Resolver resolver = getPropertyUtils().getResolver();
    while (resolver.hasNested(name)) {
        try {
            target = getPropertyUtils().getProperty(target, resolver.next(name));
            name = resolver.remove(name);
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    Target bean = " + target);
        log.trace("    Target name = " + name);
    }

    // Declare local variables we will require
    String propName = resolver.getProperty(name); // Simple name of target property
    Class type = null; // Java type of target property
    int index = resolver.getIndex(name); // Indexed subscript value (if any)
    String key = resolver.getKey(name); // Mapped key value (if any)

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else if (target instanceof Map) {
        type = Object.class;
    } else if (target != null && target.getClass().isArray() && index >= 0) {
        type = Array.get(target, index).getClass();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else if (key != null) {
            if (descriptor.getReadMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = (value == null) ? Object.class : value.getClass();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String[] values = new String[1];
            values[0] = null;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            newValue = getConvertUtils().convert(value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = convert(value, type);
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String || value == null) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = convert(value, type.getComponentType());
        }
    } else { // Value into scalar
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else {
            newValue = convert(value, type);
        }
    }

    // Invoke the setter method
    try {
        getPropertyUtils().setProperty(target, name, newValue);
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java

/**
 * Constructs an attribute model for a property
 * /*w  w  w  . ja va2s .  c o m*/
 * @param descriptor
 *            the property descriptor
 * @param entityModel
 *            the entity model
 * @param parentClass
 *            the type of the direct parent of the attribute (relevant in case of embedded
 *            attributes)
 * @param nested
 *            whether this is a nested attribute
 * @param prefix
 *            the prefix to apply to the attribute name
 * @return
 */
private <T> List<AttributeModel> constructAttributeModel(PropertyDescriptor descriptor,
        EntityModelImpl<T> entityModel, Class<?> parentClass, boolean nested, String prefix) {
    List<AttributeModel> result = new ArrayList<AttributeModel>();

    // validation methods annotated with @AssertTrue or @AssertFalse have to
    // be ignored
    String fieldName = descriptor.getName();
    AssertTrue assertTrue = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, AssertTrue.class);
    AssertFalse assertFalse = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName,
            AssertFalse.class);

    if (assertTrue == null && assertFalse == null) {

        AttributeModelImpl model = new AttributeModelImpl();
        model.setEntityModel(entityModel);

        String displayName = DefaultFieldFactory.createCaptionByPropertyId(fieldName);

        // first, set the defaults
        model.setDisplayName(displayName);
        model.setDescription(displayName);
        model.setPrompt(displayName);
        model.setMainAttribute(descriptor.isPreferred());
        model.setSearchable(descriptor.isPreferred());
        model.setName((prefix == null ? "" : (prefix + ".")) + fieldName);
        model.setImage(false);

        model.setReadOnly(descriptor.isHidden());
        model.setSortable(true);
        model.setComplexEditable(false);
        model.setPrecision(SystemPropertyUtils.getDefaultDecimalPrecision());
        model.setSearchCaseSensitive(false);
        model.setSearchPrefixOnly(false);
        model.setUrl(false);
        model.setUseThousandsGrouping(true);

        Id idAttr = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, Id.class);
        if (idAttr != null) {
            entityModel.setIdAttributeModel(model);
            // the ID column is hidden. details collections are also hidden
            // by default
            model.setVisible(false);
        } else {
            model.setVisible(true);
        }
        model.setType(descriptor.getPropertyType());

        // determine the possible date type
        model.setDateType(determineDateType(model.getType(), entityModel.getEntityClass(), fieldName));

        // determine default display format
        model.setDisplayFormat(determineDefaultDisplayFormat(model.getType(), entityModel.getEntityClass(),
                fieldName, model.getDateType()));

        // determine if the attribute is required based on the @NotNull
        // annotation
        NotNull notNull = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, NotNull.class);
        model.setRequired(notNull != null);

        model.setAttributeType(determineAttributeType(parentClass, model));

        // minimum and maximum length based on the @Size annotation
        Size size = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, Size.class);
        if (AttributeType.BASIC.equals(model.getAttributeType()) && size != null) {
            model.setMaxLength(size.max());
            model.setMinLength(size.min());
        }

        setNestedEntityModel(model);

        // only basic attributes are shown in the table by default
        model.setVisibleInTable(
                !nested && model.isVisible() && (AttributeType.BASIC.equals(model.getAttributeType())));

        if (getMessageService() != null) {
            model.setTrueRepresentation(getMessageService().getMessage("ocs.true"));
            model.setFalseRepresentation(getMessageService().getMessage("ocs.false"));
        }

        // by default, use a combo box to look up
        model.setSelectMode(AttributeSelectMode.COMBO);
        model.setTextFieldMode(AttributeTextFieldMode.TEXTFIELD);
        model.setSearchSelectMode(AttributeSelectMode.COMBO);

        // is the field an email field?
        Email email = ClassUtils.getAnnotation(entityModel.getEntityClass(), fieldName, Email.class);
        model.setEmail(email != null);

        // override the defaults with annotation values
        setAnnotationOverrides(parentClass, model, descriptor, nested);

        // override any earlier version with message bundle contents
        setMessageBundleOverrides(entityModel, model);

        if (!model.isEmbedded()) {
            result.add(model);
        } else {
            // an embedded object is not directly added. Instead, its child
            // properties are added as attributes
            if (model.getType().equals(entityModel.getEntityClass())) {
                throw new IllegalStateException("Embedding a class in itself is not allowed");
            }
            PropertyDescriptor[] embeddedDescriptors = BeanUtils.getPropertyDescriptors(model.getType());
            for (PropertyDescriptor embeddedDescriptor : embeddedDescriptors) {
                String name = embeddedDescriptor.getName();
                if (!skipAttribute(name)) {
                    List<AttributeModel> embeddedModels = constructAttributeModel(embeddedDescriptor,
                            entityModel, model.getType(), nested, model.getName());
                    result.addAll(embeddedModels);
                }
            }
        }
    }
    return result;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public Object getFileId(String existingId, String idField, PropertyDescriptor[] pds)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, PersistenceException {
    Object id = null;/*from   w ww  . j a  v  a  2  s .  c o m*/
    for (PropertyDescriptor pd : pds) {
        if (pd.getName().equals(idField)) {
            Class<?> propertyType = pd.getPropertyType();
            if (Number.class.isAssignableFrom(propertyType))
                id = propertyType.getMethod("valueOf", String.class).invoke(propertyType, existingId);
            else if (propertyType.equals(String.class))
                id = existingId;
            else
                throw new PersistenceException("Type " + propertyType + " not supported");
        }
    }
    return id;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

public com.hiperf.common.ui.shared.util.Id getId(String s, String className) {
    if (s != null && s.length() > 0) {
        String[] ss = s.split(",");
        int l = ss.length;
        PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className);
        List<String> fieldNames = new ArrayList<String>(l);
        List<Object> fieldValues = new ArrayList<Object>(l);
        int j = 0;
        for (int i = 0; i < l; i++) {
            String[] ids = ss[i].split(":");
            String att = null;/*w ww.j  a  v a 2  s .  co m*/
            if (ids.length == 2) {
                j = 1;
                att = ids[0];
                fieldNames.add(att);
            } else if (l == 1) {
                j = 0;
                att = idsByClassName.get(className).iterator().next().getName();
                fieldNames.add(att);
            }
            if (att != null) {
                for (PropertyDescriptor pd : pds) {
                    if (pd.getName().equals(att)) {
                        if (pd.getPropertyType().equals(Long.class)
                                || pd.getPropertyType().equals(long.class)) {
                            fieldValues.add(Long.valueOf(ids[j]));
                        } else if (pd.getPropertyType().equals(Integer.class)
                                || pd.getPropertyType().equals(int.class)) {
                            fieldValues.add(Long.valueOf(ids[j]));
                        } else
                            fieldValues.add(ids[j].toString());
                    }
                }
            }
        }
        return new com.hiperf.common.ui.shared.util.Id(fieldNames, fieldValues);
    }
    return null;
}