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.onebusaway.nyc.presentation.impl.NycConfigurationServiceImpl.java

private ConfigurationBean loadSettings() {

    if (_path == null || !_path.exists())
        return new ConfigurationBean();

    try {/*from w  w  w . j  a  v  a  2  s  .com*/

        Properties properties = new Properties();
        properties.load(new FileReader(_path));

        ConfigurationBean bean = new ConfigurationBean();
        BeanInfo beanInfo = Introspector.getBeanInfo(ConfigurationBean.class);

        for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
            String name = desc.getName();
            Object value = properties.getProperty(name);
            if (value != null) {
                Converter converter = ConvertUtils.lookup(desc.getPropertyType());
                value = converter.convert(desc.getPropertyType(), value);
                Method m = desc.getWriteMethod();
                m.invoke(bean, value);
            }
        }

        return bean;
    } catch (Exception ex) {
        throw new IllegalStateException("error loading configuration from properties file " + _path, ex);
    }
}

From source file:com.diversityarrays.kdxplore.editing.EntityPropertiesTable.java

@Override
public TableCellEditor getCellEditor(int row, int column) {
    EntityPropertiesTableModel<?> tatm = (EntityPropertiesTableModel<?>) getModel();
    PropertyDescriptor pd = tatm.getPropertyDescriptor(row);

    Class<?> pdClass = pd.getPropertyType();

    if (TraitNameStyle.class == pdClass) {
        if (Trial.class != tatm.entityClass) {
            throw new RuntimeException("Internal error: " + tatm.entityClass.getName());
        }/*  ww  w. j  ava2s  . c o m*/
        Trial trial = (Trial) tatm.getEntity();
        return TNS_Editor.create(trial);
    }

    if (Enum.class.isAssignableFrom(pdClass)) {
        if (PlotIdentOption.class.equals(pdClass)) {
            List<PlotIdentOption> list = new ArrayList<>();
            for (PlotIdentOption pio : PlotIdentOption.values()) {
                if (PlotIdentOption.NO_X_Y_OR_PLOT_ID != pio) {
                    list.add(pio);
                }
            }
            return new DefaultCellEditor(
                    new JComboBox<PlotIdentOption>(list.toArray(new PlotIdentOption[list.size()])));
        } else {
            @SuppressWarnings({ "rawtypes", "unchecked" })
            Class<Enum> eclass = (Class<Enum>) pdClass;
            @SuppressWarnings({ "rawtypes", "unchecked" })
            EnumSet allOf = EnumSet.allOf(eclass);
            return new DefaultCellEditor(new JComboBox<>(allOf.toArray()));
        }
    }
    return super.getCellEditor(row, column);
}

From source file:name.ikysil.beanpathdsl.codegen.CodeGen.java

private void generateBeanPathSource(Context context, Map<Class<?>, IncludedClass> transitiveClosure,
        Class<?> clazz, ClassName targetClassName) {
    logger.info("Generating {} for {}", targetClassName, clazz.getName());

    AnnotationSpec generatedSpec = AnnotationSpec.builder(Generated.class).addMember("value", "$S",
            String.format("Generated by beanpath-codegen for %s", ClassName.get(clazz))).build();

    AnnotationSpec navigatorSpec = AnnotationSpec.builder(Navigator.class).addMember("value", "$T.class", clazz)
            .build();// w  w w. j  av a 2s.  c  o  m

    PropertyDescriptor[] pds = context.getPropertyDescriptors(clazz);
    Arrays.sort(pds, new Comparator<PropertyDescriptor>() {

        @Override
        public int compare(PropertyDescriptor o1, PropertyDescriptor o2) {
            return o1.getName().compareTo(o2.getName());
        }

    });

    Collection<FieldSpec> fieldSpecs = new ArrayList<>();
    Collection<MethodSpec> methodSpecs = new ArrayList<>();

    FieldSpec fieldSpec = FieldSpec.builder(targetClassName, getInstanceAccessor(clazz))
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
            .initializer("new $T()", targetClassName).build();
    fieldSpecs.add(fieldSpec);

    final ParameterizedTypeName fieldTypeName = ParameterizedTypeName.get(ClassName.get(Class.class),
            ClassName.get(clazz));
    fieldSpec = FieldSpec.builder(fieldTypeName, SOURCE_CLASS_FIELD_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("$T.class", clazz)
            .build();
    fieldSpecs.add(fieldSpec);

    for (PropertyDescriptor pd : pds) {
        final String name = getNavigationMethodName(pd);
        Class<?> pdClass = pd.getPropertyType();
        if ((pdClass == null) && (pd instanceof IndexedPropertyDescriptor)) {
            pdClass = ((IndexedPropertyDescriptor) pd).getIndexedPropertyType();
        }
        ClassName bpAccessorClassName = classNames.get(pdClass);
        if (bpAccessorClassName == null) {
            pdClass = BaseNavigator.class;
            bpAccessorClassName = ClassName.get(pdClass);
        }
        MethodSpec pdMethodSpec = MethodSpec.methodBuilder(name).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .returns(bpAccessorClassName)
                .addCode(CodeBlock.builder().addStatement("navigate($S)", pd.getName())
                        .addStatement("return $T.$N", bpAccessorClassName, getInstanceAccessor(pdClass))
                        .build())
                .build();
        methodSpecs.add(pdMethodSpec);

        pdMethodSpec = MethodSpec.methodBuilder(name).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addParameter(ClassName.get(String.class), "propertyName", Modifier.FINAL)
                .returns(bpAccessorClassName)
                .addCode(CodeBlock.builder().addStatement("navigate($N)", "propertyName")
                        .addStatement("return $T.$N", bpAccessorClassName, getInstanceAccessor(pdClass))
                        .build())
                .build();
        methodSpecs.add(pdMethodSpec);
    }

    MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build();
    methodSpecs.add(constructor);

    TypeSpec typeSpec = TypeSpec.classBuilder(targetClassName).superclass(ClassName.get(BaseNavigator.class))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL).addAnnotation(generatedSpec)
            .addAnnotation(navigatorSpec).addFields(fieldSpecs).addMethods(methodSpecs).build();

    JavaFile javaFile = JavaFile.builder(targetClassName.packageName(), typeSpec).skipJavaLangImports(true)
            .indent("    ").build();

    try {
        javaFile.writeTo(Paths.get(configuration.getOutputDirectory()));
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

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

private boolean compareObjects(PropertyDescriptor desc, Object orig, Object nuevo) {
    boolean result = false;

    if (Date.class.isAssignableFrom(desc.getPropertyType())) {
        try {/*from www  .  j  ava 2  s  . com*/
            Method compare = Date.class.getMethod("compareTo", Date.class);
            int aux = (nuevo != null) ? (int) compare.invoke((Date) orig, (Date) nuevo) : -1;
            result = (aux == 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (Collection.class.isAssignableFrom(desc.getPropertyType())) {
        result = (nuevo != null)
                ? CollectionUtils.isEqualCollection((Collection<?>) orig, (Collection<?>) nuevo)
                : false;
    } else {
        result = orig.equals(nuevo);
    }

    return result;
}

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

/**
 * Validate the descriptor attributes./*from w  ww  .ja va  2  s .  c  o  m*/
 * 
 * @param pd the descriptor
 * @param pe the propertyEditor
 */
private static void validateAttributes(PropertyDescriptor pd, PropertyEditor pe) {
    final Object deflt = pd.getValue(DEFAULT);
    if (deflt == null) {
        if (notNull(pd)) {
            log.warn(getDetails(pd) + " requires a value but does not provide a default.");
        }
        if (noSaveDefault(pd)) {
            log.warn(getDetails(pd) + " specifies DEFAULT_NO_SAVE but does not provide a default.");
        }
    } else {
        final Class<?> defltClass = deflt.getClass(); // the DEFAULT class
        // Convert int to Integer etc:
        final Class<?> propClass = ClassUtils.primitiveToWrapper(pd.getPropertyType());
        if (!propClass.isAssignableFrom(defltClass)) {
            log.warn(getDetails(pd) + " has a DEFAULT of class " + defltClass.getCanonicalName());
        }
    }
    if (notOther(pd) && pd.getValue(TAGS) == null && pe.getTags() == null) {
        log.warn(getDetails(pd) + " does not have tags but other values are not allowed.");
    }
    if (!notNull(pd)) {
        Class<?> propertyType = pd.getPropertyType();
        if (propertyType.isPrimitive()) {
            log.warn(getDetails(pd) + " allows null but is a primitive type");
        }
    }
    if (!pd.attributeNames().hasMoreElements()) {
        log.warn(getDetails(pd) + " does not appear to have been configured");
    }
}

From source file:com.blackbear.flatworm.converters.ConversionHelper.java

/**
 * Use an alternate method that attempts to use reflection to figure out which conversion routine to use.
 *
 * @param bean         The {@link Object} that contains the property.
 * @param beanName     The name of the bean as configured.
 * @param propertyName The name of the property that is to be set.
 * @param fieldChars   The value./*from   w w w.  ja  va  2s.co  m*/
 * @param options      The {@link ConversionOptionBO}s.
 * @return The {@link Object} constructed from the {@code fieldChars} value.
 * @throws FlatwormParserException should parsing the value to a {@link Object} fail for any reason.
 */
public Object convert(Object bean, String beanName, String propertyName, String fieldChars,
        Map<String, ConversionOptionBO> options) throws FlatwormParserException {
    Object value;
    try {
        PropertyDescriptor propDescriptor = PropertyUtils.getPropertyDescriptor(bean, propertyName);
        value = ConverterFunctionCache.convertFromString(propDescriptor.getPropertyType(), fieldChars, options);
    } catch (Exception e) {
        throw new FlatwormParserException(
                String.format("Failed to convert and set value '%s' on bean %s [%s] for property %s.",
                        fieldChars, beanName, bean.getClass().getName(), propertyName),
                e);
    }
    return value;
}

From source file:com.blackbear.flatworm.ParseUtils.java

/**
 * Determine how best to add the {@code toAdd} instance to the collection found in {@code target} by seeing if either the {@code
 * Segment.addMethod} has a value or if {@code Segment.propertyName} has a value. If neither values exist then no action is taken.
 *
 * @param cardinality The {@link CardinalityBO} instance containing the configuration information.
 * @param target      The instance with the collection to which the {@code toAdd} instance is to be added.
 * @param toAdd       The instance to be added to the specified collection.
 * @throws FlatwormParserException should the attempt to add the {@code toAdd} instance to the specified collection fail for any
 *                                 reason.
 *///www.  j a  v  a2  s. co  m
public static void addValueToCollection(CardinalityBO cardinality, Object target, Object toAdd)
        throws FlatwormParserException {
    if (cardinality.getCardinalityMode() != CardinalityMode.SINGLE) {

        boolean addToCollection = true;
        PropertyDescriptor propDesc;

        try {
            propDesc = PropertyUtils.getPropertyDescriptor(target, cardinality.getPropertyName());
        } catch (Exception e) {
            // This should only happen via the XML configuration as the annotation configuration uses reflection to 
            // determine the property name. 
            throw new FlatwormParserException(String.format(
                    "Failed to read property %s on bean %s. Make sure the specified "
                            + "property-name is correct in the configuration for the record-element.",
                    cardinality.getPropertyName(), target.getClass().getName()), e);
        }

        if (cardinality.getCardinalityMode() == CardinalityMode.STRICT
                || cardinality.getCardinalityMode() == CardinalityMode.RESTRICTED) {

            try {
                Object currentValue = PropertyUtils.getProperty(target, cardinality.getPropertyName());
                int currentSize;

                if (Collection.class.isAssignableFrom(propDesc.getPropertyType())) {
                    currentSize = Collection.class.cast(currentValue).size();
                } else if (propDesc.getPropertyType().isArray()) {
                    currentSize = Array.getLength(currentValue);
                } else {
                    throw new FlatwormParserException(String.format(
                            "Bean %s has a Cardinality Mode of %s for property %s, "
                                    + "suggesting that it is an Array or some instance of java.util.Collection. However, the property type "
                                    + "is %s, which is not currently supported.",
                            target.getClass().getName(), cardinality.getCardinalityMode().name(),
                            cardinality.getPropertyName(), propDesc.getPropertyType().getName()));
                }

                addToCollection = currentSize < cardinality.getMaxCount() || cardinality.getMaxCount() < 0;

            } catch (Exception e) {
                throw new FlatwormParserException(String.format(
                        "Failed to load property %s on bean %s when determining if a "
                                + "value could be added to the collection.",
                        cardinality.getPropertyName(), target.getClass().getName()), e);
            }

            if (!addToCollection && cardinality.getCardinalityMode() == CardinalityMode.STRICT) {
                throw new FlatwormParserException(String.format(
                        "Cardinality limit of %d exceeded for property %s of bean %s "
                                + "with Cardinality Mode set to %s.",
                        cardinality.getMaxCount(), cardinality.getPropertyName(), target.getClass().getName(),
                        cardinality.getCardinalityMode().name()));
            }
        }

        // Add it if we have determined that's allowed.
        if (addToCollection) {

            // Need to make sure we have an add method for Arrays.
            // TODO - add ability to automatically expand an array - for now, use an addMethod or collections.
            if (StringUtils.isBlank(cardinality.getAddMethod()) && propDesc.getPropertyType().isArray()) {
                throw new FlatwormParserException(String.format(
                        "Bean %s with property %s is an Array and therefore an Add Method "
                                + "must be specified in the configuration so that an element can be properly added to the array. "
                                + "Auto-expanding an array is not yet supported.",
                        target.getClass().getName(), cardinality.getPropertyName()));
            }

            if (!StringUtils.isBlank(cardinality.getAddMethod())) {
                invokeAddMethod(target, cardinality.getAddMethod(), toAdd);
            } else if (!StringUtils.isBlank(cardinality.getPropertyName())) {
                addValueToCollection(target, cardinality.getPropertyName(), toAdd);
            }
        }
    } else {
        throw new FlatwormParserException(String.format(
                "Object %s attempted to be added to Object %s as part of a collection,"
                        + " but the configuration has it configured as a %s Cardinality Mode.",
                toAdd.getClass().getName(), target.getClass().getName(),
                cardinality.getCardinalityMode().name()));
    }
}

From source file:gov.nih.nci.caarray.application.permissions.PermissionsManagementServiceBean.java

private void convertToLikeProperty(User u, User newUser, PropertyDescriptor pd)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (pd.getPropertyType().equals(String.class)) {
        final String value = (String) PropertyUtils.getSimpleProperty(newUser, pd.getName());
        if (value != null) {
            PropertyUtils.setSimpleProperty(newUser, pd.getName(), value + "%");
        }/*from   ww w.ja v  a  2s  .  co  m*/
    }
}

From source file:org.codehaus.groovy.grails.scaffolding.DefaultScaffoldDomain.java

public void setIdentityPropertyName(String identityPropertyName) {
    PropertyDescriptor identityProp = this.bean.getPropertyDescriptor(identityPropertyName);
    identityClass = identityProp.getPropertyType();
    this.identityPropertyName = identityPropertyName;
}

From source file:info.magnolia.content2bean.impl.TypeMappingImpl.java

/**
 * Cache the already resolved types.// ww  w  .  j  a va2  s  .  c o  m
 *
 */
@Override
public PropertyTypeDescriptor getPropertyTypeDescriptor(Class<?> beanClass, String propName) {
    PropertyTypeDescriptor dscr;
    String key = beanClass.getName() + "." + propName;

    dscr = propertyTypes.get(key);
    if (dscr != null) {
        return dscr;
    }

    //TypeMapping defaultMapping = TypeMapping.Factory.getDefaultMapping();
    // TODO - is this used - or is the comparison correct ?
    //        if (this != defaultMapping) {
    //            dscr = defaultMapping.getPropertyTypeDescriptor(beanClass, propName);
    //            if (dscr.getType()  != null) {
    //                return dscr;
    //            }
    //        }

    dscr = new PropertyTypeDescriptor();
    dscr.setName(propName);

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    for (int i = 0; i < descriptors.length; i++) {
        PropertyDescriptor descriptor = descriptors[i];
        if (descriptor.getName().equals(propName)) {
            Class<?> propertytype = descriptor.getPropertyType(); // may be null for indexed properties
            if (propertytype != null) {
                dscr.setType(getTypeDescriptor(propertytype));
            }
            break;
        }
    }

    if (dscr.getType() != null) {
        if (dscr.isMap() || dscr.isCollection()) {
            int numberOfParameters = dscr.isMap() ? 2 : 1;
            Method method = getAddMethod(beanClass, propName, numberOfParameters);
            if (method != null) {
                dscr.setAddMethod(method);
                if (dscr.isMap()) {
                    dscr.setCollectionKeyType(getTypeDescriptor(method.getParameterTypes()[0]));
                    dscr.setCollectionEntryType(getTypeDescriptor(method.getParameterTypes()[1]));
                } else {
                    dscr.setCollectionEntryType(getTypeDescriptor(method.getParameterTypes()[0]));
                }
            }
        }
    }

    // remember me
    propertyTypes.put(key, dscr);

    return dscr;
}