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:net.kamhon.ieagle.dao.Jpa2Dao.java

private QueryParams translateExampleToQueryParams(Object example, String... orderBy) {
    Object newObj = example;/*from ww w.j a v a 2s.  c o m*/
    Entity entity = ((Entity) newObj.getClass().getAnnotation(Entity.class));
    if (entity == null)
        throw new DataException(newObj.getClass().getSimpleName() + " class is not valid JPA annotated bean");

    String entityName = StringUtils.isBlank(entity.name()) ? example.getClass().getSimpleName() : entity.name();
    String aliasName = StringUtils.isBlank(entity.name()) ? "obj" : entity.name();

    String hql = "SELECT " + aliasName + " FROM ";
    List<Object> params = new ArrayList<Object>();

    BeanWrapper beanO1 = new BeanWrapperImpl(newObj);
    PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors();
    int propertyLength = proDescriptorsO1.length;

    if (newObj != null) {
        hql += entityName + " " + aliasName;
    }

    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getJoinTables().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " JOIN " + key + " " + voBase.getJoinTables().get(key);
            }
        }
    }

    hql += " WHERE 1=1";

    int paramCount = 0;
    for (int i = 0; i < propertyLength; i++) {
        try {
            Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName());

            if ((propertyValueO1 instanceof String && StringUtils.isNotBlank((String) propertyValueO1))
                    || propertyValueO1 instanceof Long || propertyValueO1 instanceof Double
                    || propertyValueO1 instanceof Integer || propertyValueO1 instanceof Boolean
                    || propertyValueO1 instanceof Date || propertyValueO1.getClass().isPrimitive()) {

                Field field = null;
                try {
                    field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                } catch (NoSuchFieldException e) {
                    if (propertyValueO1 instanceof Boolean || propertyValueO1.getClass().isPrimitive()) {
                        String fieldName = "is"
                                + StringUtils.upperCase(proDescriptorsO1[i].getName().substring(0, 1))
                                + proDescriptorsO1[i].getName().substring(1);
                        field = example.getClass().getDeclaredField(fieldName);
                    }
                }

                if (proDescriptorsO1[i].getName() != null && field != null
                        && !field.isAnnotationPresent(Transient.class)) {
                    if (!Arrays.asList(VoBase.propertiesVer).contains(proDescriptorsO1[i].getName())) {
                        hql += " AND " + aliasName + "." + field.getName() + " = ?" + (++paramCount);
                        params.add(propertyValueO1);
                    }
                }
            } else if (propertyValueO1 != null) {
                Field field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName());
                if (field.isAnnotationPresent(javax.persistence.Id.class)
                        || field.isAnnotationPresent(javax.persistence.EmbeddedId.class)) {

                    BeanWrapper bean = new BeanWrapperImpl(propertyValueO1);
                    PropertyDescriptor[] proDescriptors = bean.getPropertyDescriptors();

                    for (PropertyDescriptor propertyDescriptor : proDescriptors) {
                        Object propertyValueId = bean.getPropertyValue(propertyDescriptor.getName());

                        if (propertyValueId != null && ReflectionUtil.isJavaDataType(propertyValueId)) {
                            hql += " AND " + aliasName + "." + proDescriptorsO1[i].getName() + "."
                                    + propertyDescriptor.getName() + " = ?" + (++paramCount);
                            params.add(bean.getPropertyValue(propertyDescriptor.getName()));
                        }
                    }
                }
            }

        } catch (Exception e) {
        }
    }

    // not condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getNotConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + "!= ?" + (++paramCount);
                params.add(voBase.getNotConditions().get(key));
            }
        }
    }

    // like condition
    if (example instanceof VoBase) {
        VoBase voBase = (VoBase) example;
        for (String key : voBase.getLikeConditions().keySet()) {
            if (StringUtils.isNotBlank(key)) {
                hql += " AND " + aliasName + "." + key + " LIKE ?" + (++paramCount);
                params.add(voBase.getLikeConditions().get(key));
            }
        }
    }

    if (orderBy != null && orderBy.length != 0) {
        hql += " ORDER BY ";
        long count = 1;
        for (String orderByStr : orderBy) {
            if (count != 1)
                hql += ",";
            hql += aliasName + "." + orderByStr;
            count += 1;
        }
    }

    log.debug("hql = " + hql);

    return new QueryParams(hql, params);
}

From source file:com.duowan.common.spring.jdbc.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/*from  w ww .  j a v  a2s .c  o  m*/
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.insframework.common.spring.jdbc.mapper.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/* w  w w. jav a 2s .c o m*/
 */
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                try {
                    //add by guom
                    if (pd.getPropertyType() != null
                            && "java.lang.String".equals(pd.getPropertyType().getName())) {
                        if (value != null) {
                            bw.setPropertyValue(pd.getName(), String.valueOf(value));
                        } else {
                            bw.setPropertyValue(pd.getName(), "");
                        }
                    } else if (pd.getPropertyType() != null
                            && "double".equals(pd.getPropertyType().getName())) {
                        if (value != null) {
                            bw.setPropertyValue(pd.getName(), value);
                        } else {
                            bw.setPropertyValue(pd.getName(), 0d);
                        }
                    } else {
                        bw.setPropertyValue(pd.getName(), value);
                    }

                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.info("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:org.jdal.vaadin.data.ContainerDataSource.java

/**
 * {@inheritDoc}//from  w  w  w . j  a  v a2 s  .  co m
 */
public Collection<?> getSortableContainerPropertyIds() {
    if (sortableProperties != null)
        return sortableProperties;

    if (entityClass != null) {
        List<String> properties = new LinkedList<String>();
        PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(entityClass);
        for (PropertyDescriptor pd : pds)
            properties.add(pd.getName());

        return properties;
    }

    // if we have data will try introspection
    if (page.getData().size() > 0) {
        BeanItem<T> item = items.get(0);
        return item.getItemPropertyIds();
    }

    return new LinkedList<Object>();
}

From source file:gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportTreeTest.java

/**
 * Figures out the next domain object type down from the descriptor given.
 *///from   ww w  . j a  v  a 2 s  .  c  o  m
private Class<?> getPropertyType(PropertyDescriptor descriptor) {
    if (Map.class.isAssignableFrom(descriptor.getPropertyType())) {
        Type returnType = descriptor.getReadMethod().getGenericReturnType();
        if (returnType instanceof ParameterizedType) {
            return (Class<?>) ((ParameterizedType) returnType).getActualTypeArguments()[1];
        } else {
            fail("Could not extract type of value for map property " + descriptor.getName());
        }
    } else if (List.class.isAssignableFrom(descriptor.getPropertyType())) {
        Type returnType = descriptor.getReadMethod().getGenericReturnType();
        if (returnType instanceof ParameterizedType) {
            return (Class<?>) ((ParameterizedType) returnType).getActualTypeArguments()[0];
        } else {
            fail("Could not extract type of value for list property " + descriptor.getName());
        }
    } else {
        return descriptor.getPropertyType();
    }
    throw new CaaersError("That's unpossible");
}

From source file:QueryRunner.java

/**
 * Fill the <code>PreparedStatement</code> replacement parameters with the
 * given object's bean property values./*ww w.j  ava  2 s. c  o  m*/
 * 
 * @param stmt
 *            PreparedStatement to fill
 * @param bean
 *            a JavaBean object
 * @param propertyNames
 *            an ordered array of property names (these should match the
 *            getters/setters); this gives the order to insert values in the
 *            statement
 * @throws SQLException
 *             if a database access error occurs
 */
public void fillStatementWithBean(PreparedStatement stmt, Object bean, String[] propertyNames)
        throws SQLException {
    PropertyDescriptor[] descriptors;
    try {
        descriptors = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
    } catch (IntrospectionException e) {
        throw new RuntimeException("Couldn't introspect bean " + bean.getClass().toString(), e);
    }
    PropertyDescriptor[] sorted = new PropertyDescriptor[propertyNames.length];
    for (int i = 0; i < propertyNames.length; i++) {
        String propertyName = propertyNames[i];
        if (propertyName == null) {
            throw new NullPointerException("propertyName can't be null: " + i);
        }
        boolean found = false;
        for (int j = 0; j < descriptors.length; j++) {
            PropertyDescriptor descriptor = descriptors[j];
            if (propertyName.equals(descriptor.getName())) {
                sorted[i] = descriptor;
                found = true;
                break;
            }
        }
        if (!found) {
            throw new RuntimeException("Couldn't find bean property: " + bean.getClass() + " " + propertyName);
        }
    }
    fillStatementWithBean(stmt, bean, sorted);
}

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

@Override
protected void onInitialize() {
    super.onInitialize();

    Class<?> modelClass = getModel().getObject().getClass();

    Set<String> properties = getPropertiesByOrder(modelClass);

    Validator validator = HibernateValidatorProperty.validatorFactory.getValidator();
    BeanDescriptor constraintDescriptors = validator.getConstraintsForClass(modelClass);
    for (String property : properties) {
        PropertyDescriptor descriptor;
        try {/*from www  .j a  v a  2 s .  c  om*/
            descriptor = PropertyUtils.getPropertyDescriptor(getModel().getObject(), property);
        } catch (Exception e) {
            throw new RuntimeException("error getting property " + property, e);
        }

        boolean required = false;

        ElementDescriptor constraintDescriptor = constraintDescriptors
                .getConstraintsForProperty(descriptor.getName());
        if (constraintDescriptor != null) {
            Set<ConstraintDescriptor<?>> constraintsSet = constraintDescriptor.getConstraintDescriptors();
            for (ConstraintDescriptor<?> constraint : constraintsSet) {
                if (constraint.getAnnotation() instanceof NotNull
                        || constraint.getAnnotation() instanceof NotEmpty
                        || constraint.getAnnotation() instanceof NotBlank)
                    required = true;
            }
        }

        objectProperties.add(new ObjectProperties(descriptor, required));
    }

    RepeatingView view = new RepeatingView("controlGroup");
    for (ObjectProperties objectProperty : objectProperties) {
        try {
            AbstractControlGroup<?> controlGroup;
            if (!controlGroupProviders.containsKey(objectProperty.type)) {
                Constructor<?> constructor;
                Class<? extends Panel> typesControlGroup = getControlGroupByType(objectProperty.type);
                if (typesControlGroup == null) {
                    if (objectProperty.type.isEnum())
                        typesControlGroup = EnumControlGroup.class;
                    else
                        typesControlGroup = ObjectChoiceControlGroup.class;
                }

                constructor = typesControlGroup.getConstructor(String.class, IModel.class);

                controlGroup = (AbstractControlGroup<?>) constructor.newInstance(view.newChildId(),
                        new PropertyModel<Object>(ListControlGroups.this.getModel(), objectProperty.name));
                controlGroup.init(objectProperty.name, getResourceBase(), objectProperty.required,
                        objectProperty.type, entitySettings);
                controlGroup.setEnabled(objectProperty.enabled);

                if (typesControlGroup == ObjectChoiceControlGroup.class) {
                    IObjectRenderer<?> renderer = renderers.get(objectProperty.type);
                    if (renderer == null) {
                        renderer = new IObjectRenderer<Object>() {
                            private static final long serialVersionUID = -6171655578529011405L;

                            public String render(Object object) {
                                return object.toString();
                            }
                        };
                    }
                    ((ObjectChoiceControlGroup<?>) controlGroup)
                            .setConfiguration(getEntityProvider(objectProperty.name), renderer);
                } else if (typesControlGroup == CollectionControlGroup.class) {
                    ((CollectionControlGroup<?>) controlGroup)
                            .setConfiguration(getEntityProvider(objectProperty.name), renderers);
                }

            } else {
                controlGroup = controlGroupProviders.get(objectProperty.type)
                        .createControlGroup(view.newChildId(),
                                new PropertyModel<Object>(ListControlGroups.this.getModel(),
                                        objectProperty.name),
                                objectProperty.name, getResourceBase(), objectProperty.required,
                                objectProperty.type, entitySettings);
            }
            view.add(controlGroup);

            fieldComponents.put(objectProperty.name, controlGroup);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    add(view);
}

From source file:org.grails.jpa.domain.JpaGrailsDomainClass.java

private void evaluateClassProperties(PropertyDescriptor[] descriptors) {
    for (PropertyDescriptor descriptor : descriptors) {

        final JpaDomainClassProperty property = new JpaDomainClassProperty(this, descriptor);

        if (property.isAnnotatedWith(Id.class)) {
            this.identifier = property;
        } else if (property.isAnnotatedWith(Version.class)) {
            this.version = property;
        } else {//from  w  w w  .  j  a  v a  2 s.co m
            propertyMap.put(descriptor.getName(), property);
            if (property.isPersistent()) {
                persistentProperties.put(descriptor.getName(), property);
            }
        }
    }

    this.constrainedProperties = (Map) new ConstraintsEvaluatingDynamicProperty(getPersistentProperties())
            .get(getReference().getWrappedInstance());
}

From source file:com.palantir.ptoss.cinch.core.BindingContext.java

private Map<String, ObjectFieldMethod> indexBindableProperties(Function<PropertyDescriptor, Method> methodFn)
        throws IntrospectionException {
    final Map<ObjectFieldMethod, String> getterOfms = Maps.newHashMap();
    for (Field field : Sets.newHashSet(bindableModels.values())) {
        BeanInfo beanInfo = Introspector.getBeanInfo(field.getType());
        PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : props) {
            Method method = methodFn.apply(descriptor);
            if (method == null) {
                continue;
            }//from w w w  .  j  ava2  s . co m
            BindableModel model = getFieldObject(field, BindableModel.class);
            getterOfms.put(new ObjectFieldMethod(model, field, method), descriptor.getName());
        }
    }
    return dotIndex(getterOfms.keySet(), ObjectFieldMethod.TO_FIELD_NAME, Functions.forMap(getterOfms));
}