Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:com.premiumminds.wicket.crudifier.form.elements.ListControlGroups.java

private Set<String> getPropertiesByOrder(Class<?> modelClass) {
    Set<String> properties = new LinkedHashSet<String>();

    for (String property : entitySettings.getOrderOfFields()) {
        if (!entitySettings.getHiddenFields().contains(property))
            properties.add(property);//from w w w  .j  a  v  a2  s .  c  o m
    }
    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(modelClass)) {
        if (!entitySettings.getHiddenFields().contains(descriptor.getName())
                && !properties.contains(descriptor.getName()) && !descriptor.getName().equals("class"))
            properties.add(descriptor.getName());
    }

    return properties;
}

From source file:ca.sqlpower.matchmaker.swingui.SaveAndOpenWorkspaceActionTest.java

/**
 * Takes two SPObjects and recursively determines if all persistable properties
 * are equal. This is used in testing before-states and after-states for
 * persistence tests./*from w w  w  .  ja  v a2s. c o m*/
 */
private boolean checkEquality(SPObject spo1, SPObject spo2) {

    try {
        Set<String> s = TestUtils.findPersistableBeanProperties(spo1, false, false);
        List<PropertyDescriptor> settableProperties = Arrays
                .asList(PropertyUtils.getPropertyDescriptors(spo1.getClass()));

        for (PropertyDescriptor property : settableProperties) {
            @SuppressWarnings("unused")
            Object oldVal;
            if (!s.contains(property.getName()))
                continue;
            if (property.getName().equals("parent"))
                continue; //Changing the parent causes headaches.
            if (property.getName().equals("session"))
                continue;
            if (property.getName().equals("type"))
                continue;
            try {
                oldVal = PropertyUtils.getSimpleProperty(spo1, property.getName());
                // check for a getter
                if (property.getReadMethod() == null)
                    continue;

            } catch (NoSuchMethodException e) {
                logger.debug("Skipping non-settable property " + property.getName() + " on "
                        + spo1.getClass().getName());
                continue;
            }
            Object spo1Property = PropertyUtils.getSimpleProperty(spo1, property.getName());
            Object spo2Property = PropertyUtils.getSimpleProperty(spo2, property.getName());

            assertEquals("Failed to equate " + property.getName() + " on object of type " + spo1.getClass(),
                    spo1Property, spo2Property);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // look at children
    Iterator<? extends SPObject> i = (spo1.getChildren().iterator());
    Iterator<? extends SPObject> j = (spo2.getChildren().iterator());
    while (i.hasNext() && j.hasNext()) {
        SPObject ii = i.next();
        SPObject jj = j.next();
        logger.debug("Comparing: " + ii.getClass().getSimpleName() + "," + jj.getClass().getSimpleName());
        checkEquality(ii, jj);
    }
    return (!(i.hasNext() || j.hasNext()));
}

From source file:org.terasoluna.gfw.web.el.ObjectToMapConverter.java

/**
 * Convert the given object to the flattened map.
 * <p>//from   w w w.ja  v  a2s.  c om
 * Return empty map if the object is null.
 * </p>
 * @param prefix prefix of the key
 * @param object object to convert
 * @return converted map. all keys are prefixed with the given key
 * @see ObjectToMapConverter
 */
public Map<String, String> convert(String prefix, Object object) {
    Map<String, String> map = new LinkedHashMap<String, String>();

    // at first, try to flatten the given object
    if (flatten(map, "", prefix, object, null)) {
        return map;
    }

    // the given object is a Java Bean
    BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
    PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();

    // flatten properties in the given object
    for (PropertyDescriptor pd : pds) {
        String name = pd.getName();
        if ("class".equals(name) || !beanWrapper.isReadableProperty(name)) {
            continue;
        }
        Object value = beanWrapper.getPropertyValue(name);
        TypeDescriptor sourceType = beanWrapper.getPropertyTypeDescriptor(name);

        if (!flatten(map, prefix, name, value, sourceType)) {
            // the property can be a Java Bean
            // convert recursively
            Map<String, String> subMap = this.convert(name, value);
            map.putAll(subMap);
        }
    }

    return map;
}

From source file:com.manydesigns.elements.reflection.JavaPropertyAccessor.java

public JavaPropertyAccessor(PropertyDescriptor propertyDescriptor) {
    this.propertyDescriptor = propertyDescriptor;
    getter = propertyDescriptor.getReadMethod();
    setter = propertyDescriptor.getWriteMethod();
    if (setter == null) {
        logger.debug("Setter not available for: {}", propertyDescriptor.getName());
    }/* www  .j a v a 2 s  .c  o  m*/
}

From source file:org.neovera.jdiablo.environment.SpringEnvironment.java

private void setValue(PropertyDescriptor pd, Object target, String value) {
    Method writeMethod = pd.getWriteMethod();
    if (writeMethod == null) {
        throw new RuntimeException("No write method found for property " + pd.getName());
    }//from w  w  w. jav  a 2s.c o  m
    try {
        if (writeMethod.getParameterTypes()[0].equals(Boolean.class)
                || "boolean".equals(writeMethod.getParameterTypes()[0].getName())) {
            writeMethod.invoke(target, value == null ? false : "true".equals(value));
        } else if (writeMethod.getParameterTypes()[0].equals(Integer.class)
                || "int".equals(writeMethod.getParameterTypes()[0].getName())) {
            writeMethod.invoke(target, value == null ? 0 : Integer.parseInt(value));
        } else if (writeMethod.getParameterTypes()[0].equals(Long.class)
                || "long".equals(writeMethod.getParameterTypes()[0].getName())) {
            writeMethod.invoke(target, value == null ? 0 : Long.parseLong(value));
        } else if (writeMethod.getParameterTypes()[0].equals(BigDecimal.class)) {
            writeMethod.invoke(target, value == null ? null : new BigDecimal(value));
        } else if (writeMethod.getParameterTypes()[0].equals(String.class)) {
            writeMethod.invoke(target, value);
        } else if (writeMethod.getParameterTypes()[0].isArray()
                && writeMethod.getParameterTypes()[0].getName().contains(String.class.getName())) {
            writeMethod.invoke(target, (Object[]) value.split(","));
        } else {
            throw new RuntimeException("Could not resolve parameter type for " + writeMethod.toString());
        }
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.spring.initializr.generator.CommandLineHelpGenerator.java

protected Map<String, Object> buildParametersDescription(InitializrMetadata metadata) {
    Map<String, Object> result = new LinkedHashMap<>();
    BeanWrapperImpl wrapper = new BeanWrapperImpl(metadata);
    for (PropertyDescriptor descriptor : wrapper.getPropertyDescriptors()) {
        Object value = wrapper.getPropertyValue(descriptor.getName());
        BeanWrapperImpl nested = new BeanWrapperImpl(value);
        if (nested.isReadableProperty("description") && nested.isReadableProperty("id")) {
            result.put((String) nested.getPropertyValue("id"), nested.getPropertyValue("description"));
        }/* w  ww. j a v  a  2  s .co m*/
    }
    result.put("applicationName", "application name");
    result.put("baseDir", "base directory to create in the archive");
    return result;
}

From source file:com.zero.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }//from   w  w w.  j a v  a 2s  .  c  om
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:org.okj.commons.annotations.ServiceReferenceInjectionBeanPostProcessor.java

public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        ServiceReference s = hasServiceProperty(pd);
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug(//from   w  ww.  ja va  2 s.com
                            "Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Cardinality.C_0__1);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            } catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}

From source file:com.alibaba.stonelab.toolkit.sqltester.BeanInitBuilder.java

/**
 * <pre>/*from   w ww .  j ava2 s.  c  o m*/
 * build logic 
 * TODO:
 * 1.?,
 * 2.JDK Enum?
 * 
 * </pre>
 * 
 * @param count
 * @return
 */
private List<T> doBuild(int count) {
    List<T> ret = new ArrayList<T>();
    for (int i = 0; i < count; i++) {
        T t = null;
        try {
            t = clz.newInstance();
        } catch (Exception e) {
            throw new BuildException("new instance error.", e);
        }
        PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(clz);
        for (PropertyDescriptor des : descriptors) {
            try {
                // ?
                if (Number.class.isAssignableFrom(des.getPropertyType())) {
                    PropertyUtils.setProperty(t, des.getName(),
                            DEFAULT_VALUE_NUMBER.get(des.getPropertyType()));
                }
                // String?
                if (String.class.isAssignableFrom(des.getPropertyType())) {
                    if (count == 1) {
                        PropertyUtils.setProperty(t, des.getName(), des.getName());
                    } else {
                        PropertyUtils.setProperty(t, des.getName(), des.getName() + i);
                    }
                }
                // date?
                if (Date.class.isAssignableFrom(des.getPropertyType())) {
                    PropertyUtils.setProperty(t, des.getName(), DEFAULT_VALUE_DATE);
                }
                // JDK?
                if (Enum.class.isAssignableFrom(des.getPropertyType())) {
                    if (des.getPropertyType().getEnumConstants().length >= 1) {
                        PropertyUtils.setProperty(t, des.getName(),
                                des.getPropertyType().getEnumConstants()[0]);
                    }
                }
            } catch (Exception e) {
                throw new BuildException("build error.", e);
            }
        }
        // 
        ret.add(t);
    }
    return ret;
}

From source file:org.springmodules.validation.bean.conf.loader.annotation.handler.CascadeValidationAnnotationHandler.java

/**
 * Registers the annotated property for cascade validation.
 *
 * @see PropertyValidationAnnotationHandler#handleAnnotation(java.lang.annotation.Annotation, Class, java.beans.PropertyDescriptor, org.springmodules.validation.bean.conf.MutableBeanValidationConfiguration)
 *///w  ww  .  j  a  v  a 2  s. co  m
public void handleAnnotation(Annotation annotation, Class clazz, PropertyDescriptor descriptor,
        MutableBeanValidationConfiguration configuration) {
    CascadeValidation cascadeValidationAnnotation = (CascadeValidation) annotation;
    org.springmodules.validation.bean.conf.CascadeValidation cascadeValidation = new org.springmodules.validation.bean.conf.CascadeValidation(
            descriptor.getName());
    if (StringUtils.hasText(cascadeValidationAnnotation.value())) {
        cascadeValidation.setApplicabilityCondition(
                conditionExpressionParser.parse(cascadeValidationAnnotation.value()));
    }
    configuration.addCascadeValidation(cascadeValidation);
}