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.kuali.kfs.module.cam.util.AssetSeparatePaymentDistributor.java

/**
 * Sums up periodic amounts for a payment
 * //w  ww.  j a  va 2s .c o  m
 * @param currPayment Payment
 * @return Sum of payment
 */
public static KualiDecimal sumPeriodicDepreciationAmounts(AssetPayment currPayment) {
    KualiDecimal ytdAmount = KualiDecimal.ZERO;
    try {
        for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null
                    && Pattern.matches(CamsConstants.GET_PERIOD_DEPRECIATION_AMOUNT_REGEX,
                            readMethod.getName().toLowerCase())
                    && propertyDescriptor.getPropertyType() != null
                    && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                KualiDecimal amount = (KualiDecimal) readMethod.invoke(currPayment);
                if (amount != null) {
                    ytdAmount = ytdAmount.add(amount);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return ytdAmount;
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private static List<PropertySheetItem> loadProperties(Object obj) {
    Class<?> objClass = obj.getClass();
    List<PropertySheetItem> list = new ArrayList<>();
    while (objClass != Object.class) {
        try {/* ww w.java 2s  .com*/
            List<String> names = Arrays.stream(objClass.getDeclaredFields())
                    .map(field -> field.getName().replace("Prop", "")).collect(Collectors.toList());
            BeanInfo beanInfo = Introspector.getBeanInfo(objClass, objClass.getSuperclass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            Arrays.sort(propertyDescriptors,
                    (pd1, pd2) -> Integer.compare(names.indexOf(pd1.getName()), names.indexOf(pd2.getName())));
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                if ("metaClass".equals(descriptor.getName()))
                    continue;

                if (Collection.class.isAssignableFrom(descriptor.getPropertyType()))
                    continue;

                AnnotatedElement getter = descriptor.getReadMethod();
                if (getter.isAnnotationPresent(Deprecated.class) || getter.isAnnotationPresent(Hide.class))
                    continue;

                String description = "";
                if (getter.isAnnotationPresent(Description.class))
                    description = getter.getAnnotation(Description.class).value();
                Class<? extends PropertyEditor<?>> propertyEditorClass = null;
                if (descriptor.getPropertyType() == Boolean.class
                        || descriptor.getPropertyType() == Boolean.TYPE) {
                    propertyEditorClass = BooleanPropertyEditor.class;
                } else if (getter.isAnnotationPresent(Tex.class)) {
                    propertyEditorClass = TexturePropertyEditor.class;
                } else if (getter.isAnnotationPresent(Sysstr.class)) {
                    propertyEditorClass = SysstringPropertyEditor.class;
                }
                BeanProperty property = new BeanProperty(descriptor, objClass.getSimpleName(), description,
                        propertyEditorClass);
                list.add(property);
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        objClass = objClass.getSuperclass();
    }
    return list;
}

From source file:nl.strohalm.cyclos.utils.SpringHelper.java

/**
 * Injects beans on setters using the Inject annotation
 *//*from w  w w.j  a  v  a2  s. c  o m*/
public static void injectBeans(final BeanFactory beanFactory, final Object target) {
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(target);
    for (final PropertyDescriptor descriptor : propertyDescriptors) {
        final Method setter = descriptor.getWriteMethod();
        if (setter != null) {
            final Inject inject = setter.getAnnotation(Inject.class);
            if (inject != null) {
                String beanName = inject.value();
                // The bean name defaults to the property name
                if (StringUtils.isEmpty(beanName)) {
                    beanName = descriptor.getName();
                }
                // Retrieve the bean from spring
                Object bean = beanFactory.getBean(beanName);
                ensureSecurityService(bean, target);
                try {
                    bean = CoercionHelper.coerce(descriptor.getPropertyType(), bean);
                } catch (final ConversionException e) {
                    throw new IllegalStateException("Bean " + beanName + " is not of the expected type type: "
                            + descriptor.getPropertyType().getName());
                }
                // Set the bean
                try {
                    setter.invoke(target, bean);
                } catch (final Exception e) {
                    throw new IllegalStateException("Error setting bean " + bean + " on action " + target
                            + " by injecting property " + descriptor.getName() + ": " + e, e);
                }
            }
        }
    }
    if (target instanceof InitializingBean) {
        try {
            ((InitializingBean) target).afterPropertiesSet();
        } catch (final Exception e) {
            throw new IllegalStateException(
                    String.format("Error after properties set on %1$s: %2$s", target, e.getMessage()), e);
        }
    }
}

From source file:de.escalon.hypermedia.spring.uber.UberUtils.java

/**
 * Renders input fields for bean properties of bean to add or update or patch.
 *
 * @param uberFields/*ww w  . j  av a 2  s.c  om*/
 *         to add to
 * @param beanType
 *         to render
 * @param annotatedParameters
 *         which describes the method
 * @param annotatedParameter
 *         which requires the bean
 * @param currentCallValue
 *         sample call value
 */
private static void recurseBeanCreationParams(List<UberField> uberFields, Class<?> beanType,
        ActionDescriptor annotatedParameters, ActionInputParameter annotatedParameter, Object currentCallValue,
        String parentParamName, Set<String> knownFields) {
    // TODO collection, map and object node creation are only describable by an annotation, not via type reflection
    if (ObjectNode.class.isAssignableFrom(beanType) || Map.class.isAssignableFrom(beanType)
            || Collection.class.isAssignableFrom(beanType) || beanType.isArray()) {
        return; // use @Input(include) to list parameter names, at least? Or mix with hdiv's form builder?
    }
    try {
        Constructor[] constructors = beanType.getConstructors();
        // find default ctor
        Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
        // find ctor with JsonCreator ann
        if (constructor == null) {
            constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
        }
        Assert.notNull(constructor,
                "no default constructor or JsonCreator found for type " + beanType.getName());
        int parameterCount = constructor.getParameterTypes().length;

        if (parameterCount > 0) {
            Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

            Class[] parameters = constructor.getParameterTypes();
            int paramIndex = 0;
            for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
                for (Annotation annotation : annotationsOnParameter) {
                    if (JsonProperty.class == annotation.annotationType()) {
                        JsonProperty jsonProperty = (JsonProperty) annotation;

                        // TODO use required attribute of JsonProperty for required fields
                        String paramName = jsonProperty.value();
                        Class parameterType = parameters[paramIndex];
                        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                                paramName);
                        MethodParameter methodParameter = new MethodParameter(constructor, paramIndex);

                        addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter,
                                annotatedParameters, parentParamName, paramName, parameterType, propertyValue,
                                knownFields);
                        paramIndex++; // increase for each @JsonProperty
                    }
                }
            }
            Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                    + constructor.getName() + " are annotated with @JsonProperty");
        }

        Set<String> knownConstructorFields = new HashSet<String>(uberFields.size());
        for (UberField sirenField : uberFields) {
            knownConstructorFields.add(sirenField.getName());
        }

        // TODO support Option provider by other method args?
        Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);

        // add input field for every setter
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
            final Method writeMethod = propertyDescriptor.getWriteMethod();
            String propertyName = propertyDescriptor.getName();

            if (writeMethod == null || knownFields.contains(parentParamName + propertyName)) {
                continue;
            }
            final Class<?> propertyType = propertyDescriptor.getPropertyType();

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyName);
            MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);

            addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter,
                    annotatedParameters, parentParamName, propertyName, propertyType, propertyValue,
                    knownConstructorFields);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to write input fields for constructor", e);
    }
}

From source file:org.eclipse.wb.internal.rcp.databinding.emf.model.bindables.PropertiesSupport.java

private static void linkClassProperties(ClassInfo classInfo) throws Exception {
    if (classInfo.status != InfoStatus.LOADED && classInfo.thisClass != null) {
        classInfo.status = InfoStatus.LOADING;
        List<PropertyInfo> newProperties = Lists.newArrayList();
        for (PropertyDescriptor descriptor : BeanSupport.getPropertyDescriptors(classInfo.thisClass)) {
            String propertyName = EmfCodeGenUtil.format(descriptor.getName(), '_', null, false, false)
                    .toUpperCase(Locale.ENGLISH);
            for (PropertyInfo propertyInfo : classInfo.properties) {
                if (propertyName.equals(propertyInfo.internalName)) {
                    propertyInfo.name = descriptor.getName();
                    propertyInfo.type = descriptor.getPropertyType();
                    newProperties.add(propertyInfo);
                    classInfo.properties.remove(propertyInfo);
                    break;
                }//from w  ww  .j av  a2  s. c o  m
            }
        }
        Collections.sort(newProperties, new Comparator<PropertyInfo>() {
            public int compare(PropertyInfo property1, PropertyInfo property2) {
                return property1.name.compareTo(property2.name);
            }
        });
        //
        classInfo.properties = newProperties;
        classInfo.status = InfoStatus.LOADED;
    }
}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) {
    try {//from w  ww.ja  v a 2  s  . c o  m
        T item = clazz.newInstance();
        for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) {
            Method writeMethod = pd.getWriteMethod();
            if (writeMethod == null || pd.getReadMethod() == null || //
                    countrolParam.getExcludeFieldList() != null
                            && countrolParam.getExcludeFieldList().contains(pd.getName())//
            ) {//
                continue;
            }
            Class fieldClazz = pd.getPropertyType();
            Long numIndex = countrolParam.getNumIndex();
            // int enumIndex = countrolParam.getEnumIndex();
            Random random = countrolParam.getRandom();
            long strIndex = countrolParam.getStrIndex();
            int charIndex = countrolParam.getCharIndex();
            Calendar time = countrolParam.getTime();
            if (TypeUtil.isBaseType(fieldClazz)) {
                if (TypeUtil.isNumberType(fieldClazz)) {
                    if (fieldClazz == Byte.class) {
                        writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F)));
                    } else if (fieldClazz == Short.class) {
                        writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF)));
                    } else if (fieldClazz == Integer.class) {
                        writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF)));
                    } else if (fieldClazz == Long.class) {
                        writeMethod.invoke(item, Long.valueOf((long) numIndex));
                    } else if (fieldClazz == Float.class) {
                        writeMethod.invoke(item, Float.valueOf((float) numIndex));
                    } else if (fieldClazz == Double.class) {
                        writeMethod.invoke(item, Double.valueOf((double) numIndex));
                    } else if (fieldClazz == byte.class) {//
                        writeMethod.invoke(item, (byte) (numIndex & 0x7F));
                    } else if (fieldClazz == short.class) {
                        writeMethod.invoke(item, (short) (numIndex & 0x7FFF));
                    } else if (fieldClazz == int.class) {
                        writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF));
                    } else if (fieldClazz == long.class) {
                        writeMethod.invoke(item, (long) numIndex);
                    } else if (fieldClazz == float.class) {
                        writeMethod.invoke(item, (float) numIndex);
                    } else if (fieldClazz == double.class) {
                        writeMethod.invoke(item, (double) numIndex);
                    }
                    numIndex++;
                    if (numIndex < 0) {
                        numIndex &= 0x7FFFFFFFFFFFFFFFL;
                    }
                    countrolParam.setNumIndex(numIndex);
                } else if (fieldClazz == boolean.class) {
                    writeMethod.invoke(item, random.nextBoolean());
                } else if (fieldClazz == Boolean.class) {
                    writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean()));
                } else if (fieldClazz == char.class) {
                    writeMethod.invoke(item, CHAR_RANGE[charIndex]);
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == Character.class) {
                    writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex]));
                    charIndex++;
                    if (charIndex >= CHAR_RANGE.length) {
                        charIndex = 0;
                    }
                    countrolParam.setCharIndex(charIndex);
                } else if (fieldClazz == String.class) {
                    if (countrolParam.getUniqueFieldList() != null
                            && countrolParam.getUniqueFieldList().contains(pd.getName())) {
                        StringBuilder sb = new StringBuilder();
                        convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb);
                        writeMethod.invoke(item, sb.toString());
                        strIndex += countrolParam.getStrStep();
                        if (strIndex < 0) {
                            strIndex &= 0x7FFFFFFFFFFFFFFFL;
                        }
                        countrolParam.setStrIndex(strIndex);
                    } else {
                        writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex]));
                        charIndex++;
                        if (charIndex >= CHAR_RANGE.length) {
                            charIndex = 0;
                        }
                        countrolParam.setCharIndex(charIndex);
                    }

                } else if (fieldClazz == Date.class) {
                    writeMethod.invoke(item, time.getTime());
                    time.add(Calendar.DAY_OF_YEAR, 1);
                } else if (fieldClazz.isEnum()) {
                    int index = random.nextInt(fieldClazz.getEnumConstants().length);
                    writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]);
                } else {
                    //
                    throw new RuntimeException("out of countrol Class " + fieldClazz.getName());
                }
            } else {
                parseClassList.push(fieldClazz);
                // TODO ?
                Set<Class> set = new HashSet<Class>(parseClassList);
                if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) {
                    Object bean = produceBean(fieldClazz, countrolParam, parseClassList);
                    writeMethod.invoke(item, bean);
                }
                parseClassList.pop();
            }
        }
        return item;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Retrieves a property of the given class of the specified name and type
 * @param clazz The class to retrieve the property from
 * @param propertyName The name of the property
 * @param propertyType The type of the property
 *
 * @return A PropertyDescriptor instance or null if none exists
 */// w ww  . j  a  va2 s.  c o m
public static PropertyDescriptor getProperty(Class clazz, String propertyName, Class propertyType) {
    if (clazz == null || propertyName == null || propertyType == null)
        return null;

    try {
        BeanWrapper wrapper = new BeanWrapperImpl(clazz.newInstance());
        PropertyDescriptor pd = wrapper.getPropertyDescriptor(propertyName);
        if (pd.getPropertyType().equals(propertyType)) {
            return pd;
        } else {
            return null;
        }
    } catch (Exception e) {
        // if there are any errors in instantiating just return null for the moment
        return null;
    }
}

From source file:org.apache.jmeter.testbeans.gui.GenericTestBeanCustomizer.java

/**
 * Identify the property from the descriptor.
 * /*from  w w w  .jav  a2 s .c om*/
 * @param pd
 * @return the property details
 */
private static String getDetails(PropertyDescriptor pd) {
    StringBuilder sb = new StringBuilder();
    sb.append(pd.getReadMethod().getDeclaringClass().getName());
    sb.append('#');
    sb.append(pd.getName());
    sb.append('(');
    sb.append(pd.getPropertyType().getCanonicalName());
    sb.append(')');
    return sb.toString();
}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> void checkBeanValidity(Class<T> clazz, List<String> excludeFieldList,
        int recursiveCycleLimit) {
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz);
    boolean validBean = false;
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && pd.getReadMethod() != null && //
                (excludeFieldList != null && !excludeFieldList.contains(pd.getName())
                        || excludeFieldList == null) //
        ) {/*from  w  ww.j  ava2s  . co  m*/
            validBean = true;
            // just set write ,read for user control
            if (!Modifier.isPublic(pd.getWriteMethod().getDeclaringClass().getModifiers())) {
                pd.getWriteMethod().setAccessible(true);
            }

            Class fieldClazz = pd.getPropertyType();
            if (!TypeUtil.isBaseType(fieldClazz)) {
                try {
                    // ????
                    if (recursiveCycleLimit == 0 && fieldClazz == clazz) {
                        throw new RuntimeException("recursive cycle limit is 0! field[" + pd.getName()
                                + "] may cause recursive, please add this field[" + pd.getName()
                                + "] to exclude list or set recursiveCycleLimit more than 0 .");
                    } else if (!fieldClazz.isAssignableFrom(clazz)) {
                        checkBeanValidity(fieldClazz, null, 999999999);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Unknown Class " + fieldClazz.getName() + " for field "
                            + pd.getName() + " ! please add this field[" + pd.getName() + "] to exclude list.",
                            e);
                }
            }
        }
    }
    if (!validBean) {
        throw new RuntimeException(
                "Invalid Bean Class[" + clazz.getName() + "], for it has not getter setter methods!");
    }
}

From source file:de.escalon.hypermedia.spring.uber.UberUtils.java

/**
 * Recursively converts object to nodes of uber data.
 *
 * @param objectNode/* w  ww .j a  v  a  2 s .com*/
 *         to append to
 * @param object
 *         to convert
 */
public static void toUberData(AbstractUberNode objectNode, Object object) {
    Set<String> filtered = FILTER_RESOURCE_SUPPORT;
    if (object == null) {
        return;
    }

    try {
        // TODO: move all returns to else branch of property descriptor handling
        if (object instanceof Resource) {
            Resource<?> resource = (Resource<?>) object;
            objectNode.addLinks(resource.getLinks());
            toUberData(objectNode, resource.getContent());
            return;
        } else if (object instanceof Resources) {
            Resources<?> resources = (Resources<?>) object;

            // TODO set name using EVO see HypermediaSupportBeanDefinitionRegistrar

            objectNode.addLinks(resources.getLinks());

            Collection<?> content = resources.getContent();
            toUberData(objectNode, content);
            return;
        } else if (object instanceof ResourceSupport) {
            ResourceSupport resource = (ResourceSupport) object;

            objectNode.addLinks(resource.getLinks());

            // wrap object attributes below to avoid endless loop

        } else if (object instanceof Collection) {
            Collection<?> collection = (Collection<?>) object;
            for (Object item : collection) {
                // TODO name must be repeated for each collection item
                UberNode itemNode = new UberNode();
                objectNode.addData(itemNode);
                toUberData(itemNode, item);
            }
            return;
        }
        if (object instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) object;
            for (Entry<?, ?> entry : map.entrySet()) {
                String key = entry.getKey().toString();
                Object content = entry.getValue();
                Object value = getContentAsScalarValue(content);
                UberNode entryNode = new UberNode();
                objectNode.addData(entryNode);
                entryNode.setName(key);
                if (value != null) {
                    entryNode.setValue(value);
                } else {
                    toUberData(entryNode, content);
                }
            }
        } else {
            Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(object);
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
                String name = propertyDescriptor.getName();
                if (filtered.contains(name)) {
                    continue;
                }
                UberNode propertyNode = new UberNode();
                Object content = propertyDescriptor.getReadMethod().invoke(object);

                if (isEmptyCollectionOrMap(content, propertyDescriptor.getPropertyType())) {
                    continue;
                }

                Object value = getContentAsScalarValue(content);
                propertyNode.setName(name);
                objectNode.addData(propertyNode);
                if (value != null) {
                    // for each scalar property of a simple bean, add valuepair nodes to data
                    propertyNode.setValue(value);
                } else {
                    toUberData(propertyNode, content);
                }
            }

            Field[] fields = object.getClass().getFields();
            for (Field field : fields) {
                String name = field.getName();
                if (!propertyDescriptors.containsKey(name)) {
                    Object content = field.get(object);
                    Class<?> type = field.getType();
                    if (isEmptyCollectionOrMap(content, type)) {
                        continue;
                    }
                    UberNode propertyNode = new UberNode();

                    Object value = getContentAsScalarValue(content);
                    propertyNode.setName(name);
                    objectNode.addData(propertyNode);
                    if (value != null) {
                        // for each scalar property of a simple bean, add valuepair nodes to data
                        propertyNode.setValue(value);
                    } else {
                        toUberData(propertyNode, content);
                    }

                }
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("failed to transform object " + object, ex);
    }
}