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:org.openlmis.fulfillment.service.FulfillmentNotificationService.java

private String getContent(Object object, String messageKey, Map<String, String> messageParams) {
    String content = messageService.localize(new Message(messageKey)).getMessage();

    try {// w  w  w. j a v  a  2s .  co  m
        List<PropertyDescriptor> descriptors = Arrays.stream(getPropertyDescriptors(object.getClass()))
                .filter(d -> null != d.getReadMethod()).collect(Collectors.toList());

        for (PropertyDescriptor descriptor : descriptors) {
            String target = "{" + descriptor.getName() + "}";
            String replacement = String.valueOf(descriptor.getReadMethod().invoke(object));

            content = content.replace(target, replacement);
        }

        for (Map.Entry<String, String> entry : messageParams.entrySet()) {
            String target = "{" + entry.getKey() + "}";
            String replacement = entry.getValue();

            content = content.replace(target, replacement);
        }

    } catch (IllegalAccessException | InvocationTargetException exp) {
        throw new IllegalStateException("Can't get access to getter method", exp);
    }
    return content;
}

From source file:com.iorga.webappwatcher.util.BasicParameterHandler.java

private PropertyDescriptor findFieldPropertyDescriptor(final String fieldName) {
    final PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(ownerClass);
    for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        if (fieldName.equals(propertyDescriptor.getName())) {
            return propertyDescriptor;
        }/*w  ww.j  a  v  a2  s  .co  m*/
    }
    throw new IllegalStateException("Couldn't find getter/setter for " + ownerClass + "." + fieldName);
}

From source file:io.kahu.hawaii.domain.FieldChecker.java

private Set<String> getFieldNames(Object bean) {
    Class<?> beanClass = bean.getClass();

    Set<String> fieldNames = new HashSet<String>();

    /*/*w w  w .j  av  a2 s  .c  om*/
     * Add all properties from this class.
     */
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        fieldNames.add(propertyDescriptor.getName());
    }

    /*
     * Remove all properties from the interface 'ValueHolder'.
     */
    propertyDescriptors = PropertyUtils.getPropertyDescriptors(ValueHolder.class);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        fieldNames.remove(propertyDescriptor.getName());
    }
    /*
     * Remove all properties from the interface 'ValueHolder'.
     */
    propertyDescriptors = PropertyUtils.getPropertyDescriptors(ValidatableDomainObject.class);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        fieldNames.remove(propertyDescriptor.getName());
    }

    /*
     * Ignore class
     */
    fieldNames.remove("callbacks");
    fieldNames.remove("callback");
    fieldNames.remove("class");
    return fieldNames;
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

public static ModelBean createModel(final Class<?> clazz, final OutputConfig outputConfig) {

    Assert.notNull(clazz, "clazz must not be null");
    Assert.notNull(outputConfig.getIncludeValidation(), "includeValidation must not be null");

    ModelCacheKey key = new ModelCacheKey(clazz.getName(), outputConfig);
    SoftReference<ModelBean> modelReference = modelCache.get(key);
    if (modelReference != null && modelReference.get() != null) {
        return modelReference.get();
    }/*from  www .j  av a 2s  .  c om*/

    Model modelAnnotation = clazz.getAnnotation(Model.class);

    final ModelBean model = new ModelBean();

    if (modelAnnotation != null && StringUtils.hasText(modelAnnotation.value())) {
        model.setName(modelAnnotation.value());
    } else {
        model.setName(clazz.getName());
    }

    if (modelAnnotation != null) {
        model.setAutodetectTypes(modelAnnotation.autodetectTypes());
    }

    if (modelAnnotation != null) {
        model.setExtend(modelAnnotation.extend());
        model.setIdProperty(modelAnnotation.idProperty());
        model.setVersionProperty(trimToNull(modelAnnotation.versionProperty()));
        model.setPaging(modelAnnotation.paging());
        model.setDisablePagingParameters(modelAnnotation.disablePagingParameters());
        model.setCreateMethod(trimToNull(modelAnnotation.createMethod()));
        model.setReadMethod(trimToNull(modelAnnotation.readMethod()));
        model.setUpdateMethod(trimToNull(modelAnnotation.updateMethod()));
        model.setDestroyMethod(trimToNull(modelAnnotation.destroyMethod()));
        model.setMessageProperty(trimToNull(modelAnnotation.messageProperty()));
        model.setWriter(trimToNull(modelAnnotation.writer()));
        model.setReader(trimToNull(modelAnnotation.reader()));
        model.setSuccessProperty(trimToNull(modelAnnotation.successProperty()));
        model.setTotalProperty(trimToNull(modelAnnotation.totalProperty()));
        model.setRootProperty(trimToNull(modelAnnotation.rootProperty()));
        model.setWriteAllFields(modelAnnotation.writeAllFields());
        model.setIdentifier(trimToNull(modelAnnotation.identifier()));
        String clientIdProperty = trimToNull(modelAnnotation.clientIdProperty());
        if (StringUtils.hasText(clientIdProperty)) {
            model.setClientIdProperty(clientIdProperty);
            model.setClientIdPropertyAddToWriter(true);
        } else {
            model.setClientIdProperty(null);
            model.setClientIdPropertyAddToWriter(false);
        }
    }

    final Set<String> hasReadMethod = new HashSet<String>();

    BeanInfo bi;
    try {
        bi = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }

    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getReadMethod() != null && pd.getReadMethod().getAnnotation(JsonIgnore.class) == null) {
            hasReadMethod.add(pd.getName());
        }
    }

    if (clazz.isInterface()) {
        final List<Method> methods = new ArrayList<Method>();

        ReflectionUtils.doWithMethods(clazz, new MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                methods.add(method);
            }
        });

        Collections.sort(methods, new Comparator<Method>() {
            @Override
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        for (Method method : methods) {
            createModelBean(model, method, outputConfig);
        }
    } else {

        final Set<String> fields = new HashSet<String>();

        Set<ModelField> modelFieldsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelFields.class,
                ModelField.class);
        for (ModelField modelField : modelFieldsOnType) {
            if (StringUtils.hasText(modelField.value())) {
                ModelFieldBean modelFieldBean;

                if (StringUtils.hasText(modelField.customType())) {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.customType());
                } else {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.type());
                }

                updateModelFieldBean(modelFieldBean, modelField);
                model.addField(modelFieldBean);
            }
        }

        Set<ModelAssociation> modelAssociationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelAssociations.class, ModelAssociation.class);
        for (ModelAssociation modelAssociationAnnotation : modelAssociationsOnType) {
            AbstractAssociation modelAssociation = AbstractAssociation
                    .createAssociation(modelAssociationAnnotation);
            if (modelAssociation != null) {
                model.addAssociation(modelAssociation);
            }
        }

        Set<ModelValidation> modelValidationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelValidations.class, ModelValidation.class);
        for (ModelValidation modelValidationAnnotation : modelValidationsOnType) {
            AbstractValidation modelValidation = AbstractValidation.createValidation(
                    modelValidationAnnotation.propertyName(), modelValidationAnnotation,
                    outputConfig.getIncludeValidation());
            if (modelValidation != null) {
                model.addValidation(modelValidation);
            }
        }

        ReflectionUtils.doWithFields(clazz, new FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (!fields.contains(field.getName()) && (field.getAnnotation(ModelField.class) != null
                        || field.getAnnotation(ModelAssociation.class) != null
                        || (Modifier.isPublic(field.getModifiers()) || hasReadMethod.contains(field.getName()))
                                && field.getAnnotation(JsonIgnore.class) == null)) {

                    // ignore superclass declarations of fields already
                    // found in a subclass
                    fields.add(field.getName());
                    createModelBean(model, field, outputConfig);

                }
            }

        });
    }

    modelCache.put(key, new SoftReference<ModelBean>(model));
    return model;
}

From source file:things.thing.ThingUtils.java

public Map<String, Map<String, String>> getRegisteredTypeProperties() {

    if (typePropertiesMap == null) {
        Map<String, Map<String, String>> temp = Maps.newTreeMap();
        for (String type : tr.getAllTypes()) {
            Class typeClass = tr.getTypeClass(type);
            BeanInfo info = null;
            try {
                info = Introspector.getBeanInfo(typeClass);
            } catch (IntrospectionException e) {
                throw new TypeRuntimeException("Can't generate info for type: " + type, type, e);
            }/*from   www  .  ja v  a2  s  .c o  m*/

            Map<String, String> properties = Maps.newTreeMap();

            for (PropertyDescriptor desc : info.getPropertyDescriptors()) {
                String name = desc.getName();
                if ("class".equals(name) || "id".equals(name)) {
                    continue;
                }
                Class propClass = desc.getPropertyType();
                properties.put(name, propClass.getSimpleName());
            }
            temp.put(type, properties);
        }
        typePropertiesMap = ImmutableMap.copyOf(temp);
    }
    return typePropertiesMap;

}

From source file:org.grails.datastore.mapping.model.config.DefaultMappingConfigurationStrategy.java

/**
 * @see #getPersistentProperties(Class, org.grails.datastore.mapping.model.MappingContext, org.grails.datastore.mapping.model.ClassMapping)
 *///  w  w w .j  av a2s.c  o  m
public List<PersistentProperty> getPersistentProperties(PersistentEntity entity, MappingContext context,
        ClassMapping classMapping) {
    ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(entity.getJavaClass());
    PropertyDescriptor[] descriptors = cpf.getPropertyDescriptors();
    final ArrayList<PersistentProperty> persistentProperties = new ArrayList<PersistentProperty>();

    for (PropertyDescriptor descriptor : descriptors) {
        final String propertyName = descriptor.getName();
        if (isExcludedProperty(propertyName, classMapping, Collections.emptyList()))
            continue;
        Class<?> propertyType = descriptor.getPropertyType();
        if (propertyFactory.isSimpleType(propertyType)) {
            persistentProperties.add(propertyFactory.createSimple(entity, context, descriptor));
        } else if (MappingFactory.isCustomType(propertyType)) {
            persistentProperties.add(propertyFactory.createCustom(entity, context, descriptor));
        }
    }
    return persistentProperties;
}

From source file:com.mindquarry.persistence.jcr.model.DefaultProperty.java

private PropertyDescriptor getPropertyDescriptor() {

    PropertyDescriptor result = null;

    for (PropertyDescriptor descriptor : PropertyUtils.getPropertyDescriptors(getDeclaringClass())) {

        if (getName().equals(descriptor.getName())) {
            result = descriptor;//from w w  w  .  ja v a2s .c  om
            break;
        }
    }
    return result;
}

From source file:com.emc.ecs.sync.config.ConfigPropertyWrapper.java

public ConfigPropertyWrapper(PropertyDescriptor descriptor) {
    if (!descriptor.getReadMethod().isAnnotationPresent(Option.class))
        throw new IllegalArgumentException(descriptor.getName() + " is not an @Option");
    this.descriptor = descriptor;
    this.option = descriptor.getReadMethod().getAnnotation(Option.class);
    this.locations = new HashSet<>(Arrays.asList(this.option.locations()));
    this.cliOption = ConfigUtil.cliOptionFromAnnotation(descriptor, getAnnotation(), null);
}

From source file:org.echocat.redprecursor.annotations.utils.AccessAlsoProtectedMembersReflectivePropertyAccessor.java

@Nonnull
private Map<String, PropertyDescriptor> getPropertyNameToDescriptorFor(@Nonnull Class<?> clazz) {
    Map<String, PropertyDescriptor> propertyNameToDescriptor = TYPE_TO_PROPERTY_DESCRIPTORS.get(clazz);
    if (propertyNameToDescriptor == null) {
        propertyNameToDescriptor = new HashMap<String, PropertyDescriptor>();
        final BeanInfo beanInfo;
        try {// ww  w.  j ava  2  s  . c om
            beanInfo = Introspector.getBeanInfo(clazz);
        } catch (IntrospectionException e) {
            throw new RuntimeException("Could not load beanInfo of " + clazz.getName() + ".", e);
        }
        final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            propertyNameToDescriptor.put(propertyDescriptor.getName(), propertyDescriptor);
        }
        TYPE_TO_PROPERTY_DESCRIPTORS.put(clazz, propertyNameToDescriptor);
    }
    return propertyNameToDescriptor;
}

From source file:com.bstek.dorado.idesupport.robot.EntityDataTypeReflectionRobot.java

protected void reflectAndComplete(Element element, Class<?> cls) throws Exception {
    Context context = Context.getCurrent();
    DataTypeManager dataTypeManager = (DataTypeManager) context.getServiceBean("dataTypeManager");
    Document document = element.getOwnerDocument();

    Map<String, Element> propertyDefElementMap = new HashMap<String, Element>();
    for (Element propertyDefElement : DomUtils.getChildrenByTagName(element, DataXmlConstants.PROPERTY_DEF)) {
        String name = propertyDefElement.getAttribute(XmlConstants.ATTRIBUTE_NAME);
        propertyDefElementMap.put(name, propertyDefElement);
    }//from  ww w. jav a  2  s .  com

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(cls);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String name = propertyDescriptor.getName();
        if ("class".equals(name))
            continue;
        Element propertyDefElement = propertyDefElementMap.get(name);
        if (propertyDefElement == null) {
            String dataTypeName = null;

            DataType propertyDataType = dataTypeManager.getDataType(propertyDescriptor.getPropertyType());
            if (propertyDataType != null) {
                dataTypeName = propertyDataType.getName();
                if (IGNORE_DATATYPES.contains(dataTypeName)) {
                    continue;
                }
            }

            propertyDefElement = document.createElement(DataXmlConstants.PROPERTY_DEF);
            propertyDefElement.setAttribute(XmlConstants.ATTRIBUTE_NAME, name);
            createPropertyElement(propertyDefElement, DataXmlConstants.ATTRIBUTE_DATA_TYPE, dataTypeName);
            element.appendChild(propertyDefElement);
        }
    }
}