List of usage examples for java.beans PropertyDescriptor getName
public String getName()
From source file:com.opengamma.language.object.ObjectFunctionProvider.java
protected void loadGetAndSet(final ObjectInfo object, final Collection<MetaFunction> definitions, final String category) { if (object.getLabel() != null) { final Class<?> clazz = object.getObjectClass(); final Set<String> attributes = new HashSet<String>(object.getDirectAttributes()); for (PropertyDescriptor prop : PropertyUtils.getPropertyDescriptors(clazz)) { final AttributeInfo attribute = object.getDirectAttribute(prop.getName()); if (attribute != null) { if (attribute.isReadable()) { final Method read = PropertyUtils.getReadMethod(prop); if (read != null) { loadObjectGetter(object, attribute, read, definitions, category); attributes.remove(prop.getName()); }//from www . j a va 2 s . com } if (attribute.isWriteable()) { final Method write = PropertyUtils.getWriteMethod(prop); if (write != null) { loadObjectSetter(object, attribute, write, definitions, category); attributes.remove(prop.getName()); } } } } if (!attributes.isEmpty()) { for (String attribute : attributes) { throw new OpenGammaRuntimeException( "Attribute " + attribute + " is not exposed on object " + object); } } } }
From source file:com.expedia.tesla.compiler.plugins.JavaTypeMapper.java
/** * Generate Tesla schema from Java class by reflection. * <p>/*from w ww . j ava 2 s .co m*/ * Tesla can generate schema from existing Java classes that follow the * JavaBeans Spec. Only properties with following attributes will be * included: * <li>public accessible.</li> * <li>writable (has both getter and setter).</li> * <li>has no {@code SkipField} annotation.</li> * <p> * Tesla will map Java type to it's closest Tesla type by default. * Developers can override this by either providing their own * {@code TypeMapper}, or with Tesla annoations. * <p> * Tesla will map all Java object types to nullable types only for class * properties. If you want an property to be not nullable, use annotation * {@code NotNullable}. * * @param schemaBuilder * All non-primitive Tesla types must be defined inside a schema. * This is the schema object into which the Tesla type will be * generated. * * @param javaType * The java class object. * * @return The Tesla type created from the java class by reflection. * * @throws TeslaSchemaException */ public Type fromJavaClass(Schema.SchemaBuilder schemaBuilder, java.lang.Class<?> javaType) throws TeslaSchemaException { String className = javaType.getCanonicalName(); if (className == null) { throw new TeslaSchemaException( String.format("Tesla cannot generate schema for local class '%s'.", javaType.getName())); } String classTypeId = Class.nameToId(className); Class clss = (Class) schemaBuilder.findType(classTypeId); if (clss != null) { return clss; } clss = (Class) schemaBuilder.addType(classTypeId); Class superClass = null; java.lang.Class<?> base = javaType.getSuperclass(); if (base != null && base != java.lang.Object.class) { superClass = (Class) fromJavaClass(schemaBuilder, javaType.getSuperclass()); } List<Field> fields = new ArrayList<>(); for (PropertyDescriptor propDesc : PropertyUtils.getPropertyDescriptors(javaType)) { Type fieldType = null; String fieldName = propDesc.getName(); Method readMethod = propDesc.getReadMethod(); Method writeMethod = propDesc.getWriteMethod(); // Ignore the property it missing getter or setter method. if (writeMethod == null || readMethod == null) { continue; } if ((superClass != null && superClass.hasField(fieldName)) || clss.hasField(fieldName)) { continue; } // Ignore the property if it is annotated with "SkipField". if (readMethod.getAnnotation(com.expedia.tesla.schema.annotation.SkipField.class) != null) { continue; } com.expedia.tesla.schema.annotation.TypeId tidAnnotation = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.TypeId.class); String typeId = null; if (tidAnnotation != null) { typeId = tidAnnotation.value(); } java.lang.reflect.Type propType = readMethod.getGenericReturnType(); fieldType = fromJava(schemaBuilder, propType); if (typeId != null) { fieldType = schemaBuilder.addType(typeId); } else { if (!(propType instanceof java.lang.Class<?> && ((java.lang.Class<?>) propType).isPrimitive())) { fieldType = schemaBuilder.addType(String.format("nullable<%s>", fieldType.getTypeId())); } com.expedia.tesla.schema.annotation.NotNullable anntNotNullable = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.NotNullable.class); com.expedia.tesla.schema.annotation.Nullable anntNullable = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.Nullable.class); if (anntNotNullable != null && anntNullable != null) { throw new TeslaSchemaException(String.format( "Property '%' of class '%s' has conflict annotations." + "'NotNullable' and 'Nullable'", fieldName)); } if (fieldType.isNullable() && anntNotNullable != null) { fieldType = ((Nullable) fieldType).getElementType(); } if (!fieldType.isReference() && readMethod.getAnnotation(com.expedia.tesla.schema.annotation.Reference.class) != null) { fieldType = schemaBuilder.addType(String.format("reference<%s>", fieldType.getTypeId())); } } com.expedia.tesla.schema.annotation.FieldName fnAnnotation = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.FieldName.class); if (fnAnnotation != null) { fieldName = fnAnnotation.value(); } String fieldDisplayName = propDesc.getDisplayName(); String getter = readMethod.getName(); String setter = propDesc.getWriteMethod().getName(); com.expedia.tesla.schema.annotation.DisplayName dnAnnotation = readMethod .getAnnotation(com.expedia.tesla.schema.annotation.DisplayName.class); if (dnAnnotation != null) { fieldDisplayName = dnAnnotation.value(); } java.util.Map<String, String> attributes = new java.util.HashMap<String, String>(); attributes.put("getter", getter); attributes.put("setter", setter); fields.add(new Field(fieldName, fieldDisplayName, fieldType, attributes, null)); } clss.define(superClass == null ? null : Arrays.asList(new Class[] { superClass }), fields, null); return clss; }
From source file:com.dexcoder.dal.spring.mapper.JdbcRowMapper.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 w w. jav a 2 s .co 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); String field = lowerCaseName(column.replaceAll(" ", "")); PropertyDescriptor pd = this.mappedFields.get(field); if (pd != null) { try { Object value = getColumnValue(rs, index, pd); if (rowNumber == 0 && logger.isDebugEnabled()) { logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type [" + ClassUtils.getQualifiedName(pd.getPropertyType()) + "]"); } try { bw.setPropertyValue(pd.getName(), value); } catch (TypeMismatchException ex) { if (value == null && this.primitivesDefaultedForNullValue) { if (logger.isDebugEnabled()) { logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '" + column + "' with null value when setting property '" + pd.getName() + "' of type [" + ClassUtils.getQualifiedName(pd.getPropertyType()) + "] on object: " + mappedObject, ex); } } else { throw ex; } } if (populatedProperties != null) { populatedProperties.add(pd.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column '" + column + "' to property '" + pd.getName() + "'", ex); } } else { // No PropertyDescriptor found if (rowNumber == 0 && logger.isDebugEnabled()) { logger.debug("No property found for column '" + column + "' mapped to field '" + field + "'"); } } } 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.getName() + "]: " + this.mappedProperties); } return mappedObject; }
From source file:io.lightlink.dao.mapping.BeanMapper.java
private void populateOwnFields(Object bean, Map<String, Object> data) { for (String field : ownFields) { String key = normalizePropertyName(field); PropertyDescriptor propertyDescriptor = descriptorMap.get(key); if (propertyDescriptor == null) { LOG.info("Cannot find property for " + field + " in class " + paramClass.getCanonicalName()); } else {//from ww w. ja va 2s.co m try { propertyDescriptor.getWriteMethod().invoke(bean, MappingUtils.convert( propertyDescriptor.getPropertyType(), data.get(key), propertyDescriptor.getName())); } catch (Exception e) { LOG.error(e.getMessage(), e); } } } }
From source file:net.jolm.JolmLdapTemplate.java
private void addAndFilter(AndFilter filter, PropertyDescriptor pd, Object value, boolean wildcardFilters) { if (wildcardFilters) { filter.and(new WhitespaceWildcardsFilter(pd.getName(), value.toString())); } else {//ww w . j a v a2s . c o m filter.and(new EqualsFilter(pd.getName(), value.toString())); } }
From source file:net.sourceforge.vulcan.spring.SpringBeanXmlEncoder.java
void encodeBean(Element root, String beanName, Object bean) { final BeanWrapper bw = new BeanWrapperImpl(bean); final PropertyDescriptor[] pds = bw.getPropertyDescriptors(); final Element beanNode = new Element("bean"); root.addContent(beanNode);//from www . j a va 2 s .c o m if (beanName != null) { beanNode.setAttribute("name", beanName); } if (factoryExpert.needsFactory(bean)) { encodeBeanByFactory(beanNode, bean); } else { beanNode.setAttribute("class", bean.getClass().getName()); } for (PropertyDescriptor pd : pds) { if (pd.getWriteMethod() == null) continue; final Method readMethod = pd.getReadMethod(); if (readMethod == null) continue; if (readMethod.getAnnotation(Transient.class) != null) { continue; } final String name = pd.getName(); final Object value = bw.getPropertyValue(name); if (value == null) continue; final Element propertyNode = new Element("property"); propertyNode.setAttribute("name", name); beanNode.addContent(propertyNode); encodeObject(propertyNode, value); } }
From source file:net.kamhon.ieagle.dao.HibernateDao.java
private QueryParams translateExampleToQueryParams(Object example, String... orderBy) { Object newObj = example;/*from w ww . j av a 2 s . c o m*/ Entity className = ((Entity) newObj.getClass().getAnnotation(Entity.class)); if (className == null) throw new DataException(newObj.getClass().getSimpleName() + " class is not valid JPA annotated bean"); String aliasName = StringUtils.isBlank(className.name()) ? "obj" : className.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 += aliasName; hql += " IN " + example.getClass(); } 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"; 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() + " = ?"; 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() + " = ?"; 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 + "!=? "; 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 ? "; 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:org.codehaus.griffon.commons.ClassPropertyFetcher.java
private void init() { FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() { public void doWith(Field field) { if (field.isSynthetic()) return; final int modifiers = field.getModifiers(); if (!Modifier.isPublic(modifiers)) return; final String name = field.getName(); if (name.indexOf('$') == -1) { boolean staticField = Modifier.isStatic(modifiers); if (staticField) { staticFetchers.put(name, new FieldReaderFetcher(field, staticField)); } else { instanceFetchers.put(name, new FieldReaderFetcher(field, staticField)); }// w w w. j a va 2 s. co m } } }; MethodCallback methodCallback = new ReflectionUtils.MethodCallback() { public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { if (method.isSynthetic()) return; if (!Modifier.isPublic(method.getModifiers())) return; if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) { if (method.getParameterTypes().length == 0) { String name = method.getName(); if (name.indexOf('$') == -1) { if (name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3))) { name = name.substring(3); } else if (name.length() > 2 && name.startsWith("is") && Character.isUpperCase(name.charAt(2)) && (method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class)) { name = name.substring(2); } PropertyFetcher fetcher = new GetterPropertyFetcher(method, true); staticFetchers.put(name, fetcher); staticFetchers.put(StringUtils.uncapitalize(name), fetcher); } } } } }; List<Class<?>> allClasses = resolveAllClasses(clazz); for (Class<?> c : allClasses) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { try { fieldCallback.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access field '" + field.getName() + "': " + ex); } } Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { try { methodCallback.doWith(method); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access method '" + method.getName() + "': " + ex); } } } propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor desc : propertyDescriptors) { Method readMethod = desc.getReadMethod(); if (readMethod != null) { boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers()); if (staticReadMethod) { staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } else { instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } } } }
From source file:cn.clickvalue.cv2.model.rowmapper.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 . jav a 2 s . com*/ */ public Object mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); Object mappedObject = BeanUtils.instantiateClass(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); for (int index = 1; index <= columnCount; index++) { String column = lookupColumnName(rsmd, index).toLowerCase(); PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column); 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()); } bw.setPropertyValue(pd.getName(), value); } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + column + " to property " + pd.getName(), ex); } } } return mappedObject; }
From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java
Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues, String parentParamName) { if (Map.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Map not supported"); } else if (Collection.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException("Collection not supported"); } else {/* ww w . ja v a 2s. c om*/ try { Constructor[] constructors = clazz.getConstructors(); Constructor constructor = PropertyUtils.findDefaultCtor(constructors); if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } Assert.notNull(constructor, "no default constructor or JsonCreator found"); int parameterCount = constructor.getParameterTypes().length; Object[] args = new Object[parameterCount]; 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; String paramName = jsonProperty.value(); List<String> formValue = formValues.get(parentParamName + paramName); Class<?> parameterType = parameters[paramIndex]; if (DataType.isSingleValueType(parameterType)) { if (formValue != null) { if (formValue.size() == 1) { args[paramIndex++] = DataType.asType(parameterType, formValue.get(0)); } else { // // TODO create proper collection type throw new IllegalArgumentException("variable list not supported"); // List<Object> listValue = new ArrayList<Object>(); // for (String item : formValue) { // listValue.add(DataType.asType(parameterType, formValue.get(0))); // } // args[paramIndex++] = listValue; } } else { args[paramIndex++] = null; } } else { args[paramIndex++] = recursivelyCreateObject(parameterType, formValues, parentParamName + paramName + "."); } } } } Assert.isTrue(args.length == paramIndex, "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty"); } Object ret = constructor.newInstance(args); BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method writeMethod = propertyDescriptor.getWriteMethod(); String name = propertyDescriptor.getName(); List<String> strings = formValues.get(name); if (writeMethod != null && strings != null && strings.size() == 1) { writeMethod.invoke(ret, DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor } } return ret; } catch (Exception e) { throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e); } } }