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.alfresco.repo.content.transform.ComplexContentTransformer.java

/**
 * Sets any transformation option overrides it can.
 */// w w  w .j a va2s.  c  o  m
private void overrideTransformationOptions(TransformationOptions options) {
    // Set any transformation options overrides if we can
    if (options != null && transformationOptionOverrides != null) {
        for (String key : transformationOptionOverrides.keySet()) {
            if (PropertyUtils.isWriteable(options, key)) {
                try {
                    PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(options, key);
                    Class<?> propertyClass = pd.getPropertyType();

                    Object value = transformationOptionOverrides.get(key);
                    if (value != null) {
                        if (propertyClass.isInstance(value)) {
                            // Nothing to do
                        } else if (value instanceof String && propertyClass.isInstance(Boolean.TRUE)) {
                            // Use relaxed converter
                            value = TransformationOptions.relaxedBooleanTypeConverter.convert((String) value);
                        } else {
                            value = DefaultTypeConverter.INSTANCE.convert(propertyClass, value);
                        }
                    }
                    PropertyUtils.setProperty(options, key, value);
                } catch (MethodNotFoundException mnfe) {
                } catch (NoSuchMethodException nsme) {
                } catch (InvocationTargetException ite) {
                } catch (IllegalAccessException iae) {
                }
            } else {
                logger.warn("Unable to set override Transformation Option " + key + " on " + options);
            }
        }
    }
}

From source file:org.walkmod.conf.entities.impl.ConfigurationImpl.java

private List<PropertyDefinition> getProperties(Object o) {
    List<PropertyDefinition> result = new LinkedList<PropertyDefinition>();
    PropertyDescriptor[] properties = BeanUtils.getPropertyDescriptors(o.getClass());
    if (properties != null) {
        for (PropertyDescriptor pd : properties) {
            if (pd.getWriteMethod() != null) {
                String name = pd.getDisplayName();
                Class<?> clazz = pd.getPropertyType();
                String type = clazz.getSimpleName();
                String value = "";
                if (String.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz)
                        || clazz.isPrimitive()) {
                    if (pd.getReadMethod() != null) {
                        try {
                            value = pd.getReadMethod().invoke(o).toString();
                        } catch (Exception e) {
                        }/*  w w  w .jav a2  s  .c om*/
                    } else {
                        Field[] fields = o.getClass().getDeclaredFields();
                        boolean found = false;
                        for (int i = 0; i < fields.length && !found; i++) {
                            if (fields[i].getName().equals(name)) {
                                found = true;
                                fields[i].setAccessible(true);
                                try {
                                    value = fields[i].get(o).toString();
                                } catch (Exception e) {
                                }
                            }
                        }
                    }
                }

                PropertyDefinition item = new PropertyDefinitionImpl(type, name, value);

                result.add(item);
            }
        }
    }
    return result;
}

From source file:org.grails.datastore.mapping.reflect.ClassPropertyFetcher.java

private void init() {

    List<Class> allClasses = resolveAllClasses(clazz);
    for (Class c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            processField(field);/*  w  w w . j av a  2 s  .com*/
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            processMethod(method);
        }
    }

    try {
        propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
    } catch (IntrospectionException e) {
        // ignore
    }

    if (propertyDescriptors == null) {
        return;
    }

    for (PropertyDescriptor desc : propertyDescriptors) {
        propertyDescriptorsByName.put(desc.getName(), desc);
        final Class<?> propertyType = desc.getPropertyType();
        if (propertyType == null)
            continue;
        List<PropertyDescriptor> pds = typeToPropertyMap.get(propertyType);
        if (pds == null) {
            pds = new ArrayList<PropertyDescriptor>();
            typeToPropertyMap.put(propertyType, pds);
        }
        pds.add(desc);

        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                List<PropertyFetcher> propertyFetchers = staticFetchers.get(desc.getName());
                if (propertyFetchers == null) {
                    staticFetchers.put(desc.getName(), propertyFetchers = new ArrayList<PropertyFetcher>());
                }
                propertyFetchers.add(new GetterPropertyFetcher(readMethod, true));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, false));
            }
        }
    }
}

From source file:cat.albirar.framework.sets.impl.SetBuilderDefaultImpl.java

/**
 * Check if path is correct for the root model.
 * @param propertyPath The property path
 * @return true if correct and false if not
 *//*from  w ww .jav a 2 s.  co m*/
private boolean checkPath(String propertyPath) {
    StringTokenizer stk;
    ModelDescriptor pathFollower;
    PropertyDescriptor pdesc;
    String ppath;

    stk = new StringTokenizer(propertyPath, ".");
    pathFollower = currentModelDescriptor;
    while (stk.hasMoreTokens()) {
        ppath = stk.nextToken();
        if ((pdesc = pathFollower.getProperties().get(ppath)) != null) {
            if (stk.hasMoreTokens()) {
                pathFollower = new ModelDescriptor(pdesc.getPropertyType());
            }
        } else {
            // Error
            return false;
        }
    }
    return true;
}

From source file:org.malaguna.cmdit.service.reflection.ReflectionUtils.java

private String buildChangeMessage(PropertyDescriptor desc, String atributo, Object oldValue, Object newValue,
        String msgContext) {/*from w  ww.  j a  va  2  s.  co m*/
    String result = null;

    if (msgContext != null)
        atributo = msgContext + atributo;

    if (Collection.class.isAssignableFrom(desc.getPropertyType())) {
        StringBuffer msgBuff = null;
        Collection<?> oldSetAux = (Collection<?>) oldValue;
        Collection<?> newSetAux = (Collection<?>) newValue;

        if ((oldSetAux != null && !oldSetAux.isEmpty()) || (newSetAux != null && !newSetAux.isEmpty())) {
            msgBuff = new StringBuffer("{" + atributo + "}");
        }

        if (oldSetAux != null && newSetAux != null) {
            Collection<?> intersection = CollectionUtils.intersection(oldSetAux, newSetAux);
            Collection<?> nuevos = CollectionUtils.removeAll(newSetAux, intersection);
            Collection<?> borrados = CollectionUtils.removeAll(oldSetAux, intersection);

            if (nuevos != null && !nuevos.isEmpty()) {
                msgBuff.append("+++: ");
                for (Object element : nuevos)
                    msgBuff.append(String.format("[%s], ", element.toString()));
                msgBuff.delete(msgBuff.length() - 2, msgBuff.length());
            }

            if (borrados != null && !borrados.isEmpty()) {
                msgBuff.append("---: ");
                for (Object element : borrados)
                    msgBuff.append(String.format("[%s], ", element.toString()));
                msgBuff.delete(msgBuff.length() - 2, msgBuff.length());
            }
        } else if (oldSetAux != null && newSetAux == null) {
            if (!oldSetAux.isEmpty()) {
                msgBuff.append("+++: ");
                for (Object element : oldSetAux)
                    msgBuff.append(String.format("[%s], ", element.toString()));
                msgBuff.delete(msgBuff.length() - 2, msgBuff.length());
            }
        } else if (oldSetAux == null && newSetAux != null) {
            if (!newSetAux.isEmpty()) {
                msgBuff.append("---: ");
                for (Object element : newSetAux)
                    msgBuff.append(String.format("[%s], ", element.toString()));
                msgBuff.delete(msgBuff.length() - 2, msgBuff.length());
            }
        }

        if (msgBuff != null)
            result = msgBuff.toString();
    } else {
        String format = "['%s' :: (%s) -> (%s)]";
        result = String.format(format, atributo, (oldValue != null) ? oldValue.toString() : "null",
                (newValue != null) ? newValue.toString() : "null");
    }

    return result;
}

From source file:org.openmobster.core.mobileObject.TestBeanSyntax.java

private void setNestedProperty(Object mobileBean, String nestedProperty, String value) throws Exception {
    StringTokenizer st = new StringTokenizer(nestedProperty, ".");
    Object courObj = mobileBean;//from  w  w w . j a v  a  2 s. c  om

    while (st.hasMoreTokens()) {
        String token = st.nextToken();

        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 (!st.hasMoreTokens()) {
            if (Collection.class.isAssignableFrom(metaData.getPropertyType())
                    || metaData.getPropertyType().isArray()) {
                //An IndexedProperty                  
                courObj = this.initializeIndexedProperty(courObj, token, metaData);
            }

            //Actually set the value of the property
            if (!metaData.getPropertyType().isArray()) {
                PropertyUtils.setNestedProperty(mobileBean, nestedProperty,
                        ConvertUtils.convert(value, metaData.getPropertyType()));
            } else {
                PropertyUtils.setNestedProperty(mobileBean, nestedProperty,
                        ConvertUtils.convert(value, metaData.getPropertyType().getComponentType()));
            }
        } else {
            if (Collection.class.isAssignableFrom(metaData.getPropertyType())
                    || metaData.getPropertyType().isArray()) {
                //An IndexedProperty                  
                courObj = this.initializeIndexedProperty(courObj, token, metaData);
            } else {
                //A Simple Property
                courObj = this.initializeSimpleProperty(courObj, token, metaData);
            }
        }
    }
}

From source file:ca.sqlpower.architect.swingui.TestPlayPenComponent.java

/**
 * Returns a new value that is not equal to oldVal. The
 * returned object will be a new instance compatible with oldVal.  
 * /*  w  ww  .j  av a  2  s  .  com*/
 * @param property The property that should be modified.
 * @param oldVal The existing value of the property to modify.  The returned value
 * will not equal this one at the time this method was first called.
 */
private Object getNewDifferentValue(PropertyDescriptor property, Object oldVal) throws SQLObjectException {
    Object newVal; // don't init here so compiler can warn if the
    // following code doesn't always give it a value
    if (property.getPropertyType() == String.class) {
        newVal = "new " + oldVal;
    } else if (property.getPropertyType() == Boolean.class || property.getPropertyType() == Boolean.TYPE) {
        if (oldVal == null) {
            newVal = new Boolean(false);
        } else {
            newVal = new Boolean(!((Boolean) oldVal).booleanValue());
        }
    } else if (property.getPropertyType() == Integer.class || property.getPropertyType() == Integer.TYPE) {
        if (oldVal == null) {
            newVal = new Integer(0);
        } else {
            newVal = new Integer(((Integer) oldVal).intValue() + 1);
        }
    } else if (property.getPropertyType() == Double.class || property.getPropertyType() == Double.TYPE) {
        if (oldVal == null) {
            newVal = new Double(0);
        } else {
            newVal = new Double(((Double) oldVal).doubleValue() + 1);
        }
    } else if (property.getPropertyType() == Color.class) {
        if (oldVal == null) {
            newVal = new Color(0xFAC157);
        } else {
            Color oldColor = (Color) oldVal;
            newVal = new Color((oldColor.getRGB() + 0xF00) % 0x1000000);
        }
    } else if (property.getPropertyType() == Font.class) {
        if (oldVal == null) {
            newVal = FontManager.getDefaultPhysicalFont();
        } else {
            Font oldFont = (Font) oldVal;
            newVal = new Font(oldFont.getFontName(), oldFont.getSize() + 2, oldFont.getStyle());
        }
    } else if (property.getPropertyType() == Point.class) {
        if (oldVal == null) {
            newVal = new Point();
        } else {
            Point oldPoint = (Point) oldVal;
            newVal = new Point(oldPoint.x + 10, oldPoint.y + 10);
        }
    } else if (property.getPropertyType() == Insets.class) {
        if (oldVal == null) {
            newVal = new Insets(0, 0, 0, 0);
        } else {
            Insets oldInsets = (Insets) oldVal;
            newVal = new Insets(oldInsets.top + 10, oldInsets.left + 10, oldInsets.bottom + 10,
                    oldInsets.right + 10);
        }
    } else if (property.getPropertyType() == Set.class) {
        newVal = new HashSet();
        if (property.getName().equals("hiddenColumns")) {
            ((Set) newVal).add(new SQLColumn());
        } else {
            ((Set) newVal).add("Test");
        }
    } else if (property.getPropertyType() == List.class) {
        newVal = new ArrayList();
        if (property.getName().equals("selectedColumns")) {
            ((List) newVal).add(new SQLColumn());
        } else {
            ((List) newVal).add("Test");
        }
    } else if (property.getPropertyType() == TablePane.class) {
        SQLTable t = new SQLTable();
        t.initFolders(true);
        newVal = new TablePane(t, pp.getContentPane());
    } else if (property.getPropertyType() == SQLTable.class) {
        newVal = new SQLTable();
        ((SQLTable) newVal).initFolders(true);
    } else if (property.getPropertyType() == Dimension.class) {
        newVal = new Dimension();
        if (oldVal != null) {
            ((Dimension) newVal).width = ((Dimension) oldVal).width + 1;
        }
    } else {
        throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
                + property.getPropertyType().getName() + ") in getNewDifferentValue()");
    }

    return newVal;
}

From source file:org.eclipse.wb.internal.rcp.databinding.model.beans.bindables.BeanSupport.java

/**
 * @return {@link PropertyBindableInfo} properties for given bean {@link Class}.
 *//*from   w w  w.j  a v  a2  s. c  om*/
public List<PropertyBindableInfo> getProperties(BeanBindableInfo beanObjectInfo) {
    try {
        boolean topLevel = beanObjectInfo instanceof FieldBeanBindableInfo
                || beanObjectInfo instanceof MethodBeanBindableInfo
                || beanObjectInfo instanceof LocalVariableBindableInfo;
        IObserveInfo parent = topLevel ? null : beanObjectInfo;
        Class<?> beanClass = beanObjectInfo.getObjectType();
        // load properties
        List<PropertyBindableInfo> properties = Lists.newArrayList();
        boolean version_1_3 = Activator.getStore()
                .getBoolean(IPreferenceConstants.GENERATE_CODE_FOR_VERSION_1_3);
        // load properties
        for (PropertyDescriptor descriptor : getPropertyDescriptors(beanClass)) {
            Class<?> propertyType = descriptor.getPropertyType();
            //
            if (topLevel && propertyType != null && CoreUtils.isAssignableFrom(m_IObservable, propertyType)
                    && isGetter(descriptor)) {
                // property with observable (direct) type
                //
                // calculate type
                IObservableFactory.Type directType = getDirectType(propertyType);
                //
                if (directType == null) {
                    // unknown observable type
                    properties.add(new DirectPropertyBindableInfo(this, parent, descriptor));
                } else {
                    // create direct factory
                    IObservableFactory observableFactory = DirectObservableFactory.forProperty(directType);
                    // create direct property
                    DirectPropertyBindableInfo property = new DirectPropertyBindableInfo(this, parent,
                            descriptor, observableFactory);
                    properties.add(property);
                    // add direct observable
                    if (m_resolver != null) {
                        ObservableInfo directObservable = observableFactory.createObservable(beanObjectInfo,
                                property, directType, version_1_3);
                        m_resolver.addModelSupport(new DirectModelSupport(directObservable));
                    }
                }
            } else {
                // simple property
                properties.add(new BeanPropertyDescriptorBindableInfo(this, parent, descriptor));
            }
        }
        // sort properties
        Collections.sort(properties, ObserveComparator.INSTANCE);
        //
        // special cases for bean class
        //
        if (topLevel) {
            if (CoreUtils.isAssignableFrom(m_IObservable, beanClass)) {
                // bean class is observable
                //
                // calculate type
                IObservableFactory.Type directType = getDirectType(beanClass);
                //
                if (directType == null) {
                    // unknown observable type
                    properties.clear();
                } else {
                    // create direct factory
                    IObservableFactory observableFactory = DirectObservableFactory.forBean(directType);
                    // create fake direct property
                    DirectPropertyBindableInfo property = new DirectPropertyBindableInfo(this, parent,
                            getDirectName(directType), beanClass, StringReferenceProvider.EMPTY,
                            observableFactory);
                    //
                    properties.add(0, property);
                    // add direct observable
                    if (m_resolver != null) {
                        ObservableInfo directObservable = observableFactory.createObservable(beanObjectInfo,
                                property, directType, version_1_3);
                        m_resolver.addModelSupport(new DirectFieldModelSupport(directObservable));
                    }
                    //
                    if (directType == IObservableFactory.Type.OnlyValue) {
                        // add fake direct detail property
                        properties.add(1, new DirectPropertyBindableInfo(this, parent,
                                DirectObservableInfo.DETAIL_PROPERTY_NAME, beanClass,
                                StringReferenceProvider.EMPTY, DirectObservableFactory.forDetailBean()));
                    }
                }
            } else if (List.class.isAssignableFrom(beanClass)) {
                // bean class is List
                properties.add(0,
                        new CollectionPropertyBindableInfo(this, parent,
                                "Collection as WritableList/Properties.selfList()", beanClass,
                                beanObjectInfo.getReferenceProvider()));
            } else if (Set.class.isAssignableFrom(beanClass)) {
                // bean class is Set
                properties.add(0,
                        new CollectionPropertyBindableInfo(this, parent,
                                "Collection as WritableSet/Properties.selfSet()", beanClass,
                                beanObjectInfo.getReferenceProvider()));
            } else if (!CoreUtils.isAssignableFrom(m_Viewer, beanClass)) {
                boolean selection = false;
                if (CoreUtils.isAssignableFrom(m_ISelectionProvider, beanClass)) {
                    selection = true;
                    properties.add(0,
                            new ViewerObservablePropertyBindableInfo(this, parent, "single selection",
                                    TypeImageProvider.OBJECT_IMAGE, Object.class, "observeSingleSelection",
                                    ViewerObservableFactory.SINGLE_SELECTION, IObserveDecorator.BOLD));
                    properties.add(1,
                            new ViewerObservablePropertyBindableInfo(this, parent,
                                    PropertiesSupport.DETAIL_SINGLE_SELECTION_NAME,
                                    TypeImageProvider.OBJECT_IMAGE, Object.class, "observeSingleSelection",
                                    ViewerObservableFactory.DETAIL_SINGLE_SELECTION, IObserveDecorator.BOLD));
                    properties.add(2,
                            new ViewerObservablePropertyBindableInfo(this, parent, "multi selection",
                                    TypeImageProvider.COLLECTION_IMAGE, Object.class, "observeMultiSelection",
                                    ViewerObservableFactory.MULTI_SELECTION, IObserveDecorator.BOLD));
                }
                if (CoreUtils.isAssignableFrom(m_ICheckable, beanClass)) {
                    properties.add(selection ? 3 : 0,
                            new ViewerObservablePropertyBindableInfo(this, parent, "checked elements",
                                    TypeImageProvider.COLLECTION_IMAGE, Object.class, "observeCheckedElements",
                                    ViewerObservableFactory.CHECKED_ELEMENTS, IObserveDecorator.BOLD));
                }
            }
        }
        //
        return properties;
    } catch (Throwable e) {
        DesignerPlugin.log(e);
        return Collections.emptyList();
    }
}

From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java

/**
 * Create new handler.//from   w  ww .  ja v a 2s .c  o m
 *
 * @param validatorFactory Validator factory.
 * @param beanClass User input bean class.
 * @param validationGroups Validation groups to apply during bean
 * validation, or empty array to use the default group.
 *
 * @throws UnavailableException If an error happens.
 */
UserInputControllerMethodArgHandler(final ValidatorFactory validatorFactory, final Class<?> beanClass,
        final Class<?>[] validationGroups) throws UnavailableException {

    this.validatorFactory = validatorFactory;

    this.beanClass = beanClass;
    this.validationGroups = validationGroups;

    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(this.beanClass);
        final PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();
        final List<FieldDesc> beanFields = new ArrayList<>();
        for (final PropertyDescriptor propDesc : propDescs) {
            final String propName = propDesc.getName();
            final Class<?> propType = propDesc.getPropertyType();
            final Method propGetter = propDesc.getReadMethod();
            final Method propSetter = propDesc.getWriteMethod();

            if ((propGetter == null) || (propSetter == null))
                continue;

            Field propField = null;
            for (Class<?> c = this.beanClass; !c.equals(Object.class); c = c.getSuperclass()) {
                try {
                    propField = c.getDeclaredField(propName);
                    break;
                } catch (final NoSuchFieldException e) {
                    // nothing, continue the loop
                }
            }
            final boolean noTrim = (((propField != null) && propField.isAnnotationPresent(NoTrim.class))
                    || (propGetter.isAnnotationPresent(NoTrim.class)));

            Class<? extends Binder> binderClass = null;
            String format = null;
            String errorMessage = Bind.DEFAULT_MESSAGE;
            Bind bindAnno = null;
            if (propField != null)
                bindAnno = propField.getAnnotation(Bind.class);
            if (bindAnno == null)
                bindAnno = propGetter.getAnnotation(Bind.class);
            if (bindAnno != null) {
                binderClass = bindAnno.binder();
                format = bindAnno.format();
                errorMessage = bindAnno.message();
            }
            if (binderClass == null) {
                if ((String.class).isAssignableFrom(propType))
                    binderClass = StringBinder.class;
                else if ((Boolean.class).isAssignableFrom(propType) || propType.equals(Boolean.TYPE))
                    binderClass = BooleanBinder.class;
                else if ((Integer.class).isAssignableFrom(propType) || propType.equals(Integer.TYPE))
                    binderClass = IntegerBinder.class;
                else if (propType.isEnum())
                    binderClass = EnumBinder.class;
                else // TODO: add more standard binders
                    throw new UnavailableException(
                            "Unsupported user input bean field type " + propType.getName() + ".");
            }

            beanFields.add(new FieldDesc(propDesc, noTrim, binderClass.newInstance(), format, errorMessage));
        }
        this.beanFields = beanFields.toArray(new FieldDesc[beanFields.size()]);
    } catch (final IntrospectionException e) {
        this.log.error("error introspecting user input bean", e);
        throw new UnavailableException("Specified user input bean" + " class could not be introspected.");
    } catch (final IllegalAccessException | InstantiationException e) {
        this.log.error("error instatiating binder", e);
        throw new UnavailableException("Used user input bean field binder" + " could not be instantiated.");
    }

    this.beanPool = new FastPool<>(new PoolableObjectFactory<PoolableUserInput>() {

        @Override
        public PoolableUserInput makeNew(final FastPool<PoolableUserInput> pool, final int pooledObjectId) {

            try {
                return new PoolableUserInput(pool, pooledObjectId, beanClass.newInstance());
            } catch (final InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Error instatiating user input bean.", e);
            }
        }
    }, "UserInputBeansPool_" + beanClass.getSimpleName());
}

From source file:io.lightlink.dao.mapping.BeanMapper.java

private void populateOwnFields(Object bean, Map<String, Object> data) {
    for (String field : ownFields) {
        String key = normalizePropertyName(field);
        PropertyDescriptor propertyDescriptor = descriptorMap.get(key);
        if (propertyDescriptor == null) {
            LOG.info("Cannot find property for " + field + " in class " + paramClass.getCanonicalName());
        } else {/*from   w  w w. ja v a  2s  .com*/
            try {
                propertyDescriptor.getWriteMethod().invoke(bean, MappingUtils.convert(
                        propertyDescriptor.getPropertyType(), data.get(key), propertyDescriptor.getName()));
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }
}