List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
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/*from w w w .ja v a2 s . 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.toobsframework.data.beanutil.BeanMonkey.java
public static Collection populateCollection(IValidator v, String beanClazz, String indexPropertyName, Map properties, boolean validate, boolean noload) throws IllegalAccessException, InvocationTargetException, ValidationException, ClassNotFoundException, InstantiationException, PermissionException { // Do nothing unless all arguments have been specified if ((beanClazz == null) || (properties == null) || (indexPropertyName == null)) { log.warn("Proper parameters not present."); return null; }//w w w. j a v a 2 s . c o m ArrayList returnObjs = new ArrayList(); Object[] indexProperty = (Object[]) properties.get(indexPropertyName); if (indexProperty == null) { log.warn("indexProperty [" + indexProperty + "] does not exist in the map."); return returnObjs; } Class beanClass = Class.forName(beanClazz); String beanClazzName = beanClass.getSimpleName(); // beanClazz.substring(beanClazz.lastIndexOf(".") + 1); IObjectLoader odao = null; ICollectionLoader cdao = null; if (objectClass.isAssignableFrom(beanClass)) { odao = (IObjectLoader) beanFactory.getBean( Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao"); if (odao == null) { throw new InvocationTargetException(new Exception("Object DAO class " + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded")); } } else { cdao = (ICollectionLoader) beanFactory.getBean( Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao"); if (cdao == null) { throw new InvocationTargetException(new Exception("Collection DAO class " + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded")); } } boolean namespaceStrict = properties.containsKey("namespaceStrict"); for (int index = 0; index < indexProperty.length; index++) { String guid = (String) indexProperty[index]; boolean newBean = false; Object bean = null; if (!noload && guid != null && guid.length() > 0) { bean = (odao != null) ? odao.load(guid) : cdao.load(Integer.parseInt(guid)); } if (bean == null) { bean = Class.forName(beanClazz).newInstance(); newBean = true; } if (v != null) { v.prePopulate(bean, properties); } if (log.isDebugEnabled()) { log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")"); } Errors e = null; if (validate) { String beanClassName = null; beanClassName = bean.getClass().getName(); beanClassName = beanClassName.substring(beanClassName.lastIndexOf(".") + 1); e = new BindException(bean, beanClassName); } String namespace = null; if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) { namespace = (String) properties.get("namespace") + "."; } // Loop through the property name/value pairs to be set Iterator names = properties.keySet().iterator(); while (names.hasNext()) { // Identify the property name and value(s) to be assigned String name = (String) names.next(); if (name == null || (indexPropertyName.equals(name) && !noload) || (namespaceStrict && !name.startsWith(namespace))) { continue; } Object value = null; if (properties.get(name) == null) { log.warn("Property [" + name + "] does not have a value in the map."); continue; } if (properties.get(name).getClass().isArray() && index < ((Object[]) properties.get(name)).length) { value = ((Object[]) properties.get(name))[index]; } else if (properties.get(name).getClass().isArray()) { value = ((Object[]) properties.get(name))[0]; } else { value = properties.get(name); } if (namespace != null) { name = name.replace(namespace, ""); } PropertyDescriptor descriptor = null; Class type = null; // Java type of target property try { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); if (descriptor == null) { continue; // Skip this property setter } } catch (NoSuchMethodException nsm) { continue; // Skip this property setter } catch (IllegalArgumentException iae) { continue; // Skip null nested property } if (descriptor.getWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } continue; // Read-only, skip this property setter } type = descriptor.getPropertyType(); String className = type.getName(); try { value = evaluatePropertyValue(name, className, namespace, value, properties, bean); } catch (NoSuchMethodException nsm) { continue; } try { BeanUtils.setProperty(bean, name, value); } catch (ConversionException ce) { log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] "); if (validate) { e.rejectValue(name, name + ".conversionError", ce.getMessage()); } else { throw new ValidationException(bean, className, name, ce.getMessage()); } } catch (Exception be) { log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] "); if (validate) { e.rejectValue(name, name + ".error", be.getMessage()); } else { throw new ValidationException(bean, className, name, be.getMessage()); } } } /* if (newBean && cdao != null) { BeanUtils.setProperty(bean, "id", -1); } */ if (validate && e.getErrorCount() > 0) { throw new ValidationException(e); } returnObjs.add(bean); } return returnObjs; }
From source file:com.nortal.petit.beanmapper.BeanMappingFactoryImpl.java
@SuppressWarnings("unchecked") private <B> void initProperty(Map<String, Property<B, Object>> props, List<Property<B, Object>> idProps, String name, Class<B> type) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name); if (!isPropertyReadableAndWritable(pd)) { return;/*from w w w . ja va2s. co m*/ } List<Annotation> ans = BeanMappingReflectionUtils.readAnnotations(type, pd.getName()); if (BeanMappingReflectionUtils.getAnnotation(ans, Transient.class) != null) { return; } Column column = BeanMappingReflectionUtils.getAnnotation(ans, Column.class); ReflectionProperty<B, Object> prop = new ReflectionProperty<B, Object>(name, (Class<Object>) pd.getPropertyType(), inferColumn(name, column), pd.getWriteMethod(), pd.getReadMethod()); if (column != null) { prop.readOnly(!column.insertable()); } if (BeanMappingReflectionUtils.getAnnotation(ans, Id.class) != null) { idProps.add(prop); } if (useAdditionalConfiguration()) { prop.getConfiguration().setAnnotations(ans); if (Collection.class.isAssignableFrom(pd.getPropertyType())) { prop.getConfiguration().setCollectionTypeArguments( ((ParameterizedType) pd.getReadMethod().getGenericReturnType()).getActualTypeArguments()); } } if (BeanMappingReflectionUtils.getAnnotation(ans, Embedded.class) != null) { props.putAll(getCompositeProperties(prop, ans)); } else { props.put(prop.name(), prop); } }
From source file:org.openengsb.core.ekb.common.EDBConverter.java
/** * Converts an EDBObject to a model by analyzing the object and trying to call the corresponding setters of the * model./*from w ww .java 2s. co m*/ */ private Object convertEDBObjectToUncheckedModel(Class<?> model, EDBObject object) { if (!checkEDBObjectModelType(object, model)) { return null; } EDBConverterUtils.filterEngineeringObjectInformation(object, model); List<OpenEngSBModelEntry> entries = new ArrayList<OpenEngSBModelEntry>(); for (PropertyDescriptor propertyDescriptor : ModelUtils.getPropertyDescriptorsForClass(model)) { if (propertyDescriptor.getWriteMethod() == null || propertyDescriptor.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) { continue; } Object value = getValueForProperty(propertyDescriptor, object); Class<?> propertyClass = propertyDescriptor.getPropertyType(); if (propertyClass.isPrimitive()) { entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, ClassUtils.primitiveToWrapper(propertyClass))); } else { entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, propertyClass)); } } for (Map.Entry<String, EDBObjectEntry> objectEntry : object.entrySet()) { EDBObjectEntry entry = objectEntry.getValue(); Class<?> entryType; try { entryType = model.getClassLoader().loadClass(entry.getType()); entries.add(new OpenEngSBModelEntry(entry.getKey(), entry.getValue(), entryType)); } catch (ClassNotFoundException e) { LOGGER.error("Unable to load class {} of the model tail", entry.getType()); } } return ModelUtils.createModel(model, entries); }
From source file:org.ajax4jsf.templatecompiler.elements.vcp.FCallTemplateElement.java
public FCallTemplateElement(final Node element, final CompilationContext componentBean) throws CompilationException { super(element, componentBean); this.useOnlyEnumeratingParaments = false; NamedNodeMap nnm = element.getAttributes(); Node functionNameNode = nnm.getNamedItem(FUNCTION_NAME_ATTRIBUTE_NAME); if (functionNameNode != null) { this.functionName = functionNameNode.getNodeValue(); } else {/*w ww . ja v a 2 s . c o m*/ throw new CompilationException("function name is not set"); } Node nodeUseOnlyThisParameters = nnm.getNamedItem(USE_ONLY_THIS_PARAMETERS); if (nodeUseOnlyThisParameters != null) { this.useOnlyEnumeratingParaments = Boolean.getBoolean(nodeUseOnlyThisParameters.getNodeValue()); } // if // read name of variable if need Node variableName = nnm.getNamedItem(VAR_ATTRIBUTE_NAME); if (variableName != null) { this.variable = variableName.getNodeValue(); } // if // read name of parameters if need ParameterProcessor parameterProcessor = new ParameterProcessor(element, componentBean); this.parameters = parameterProcessor.getParameters(); log.debug(this.parameters); List decodeFunctionName = null; decodeFunctionName = Arrays.asList(this.functionName.split(FUNCTION_DELIMITER)); if (null == decodeFunctionName) { decodeFunctionName = new ArrayList(); decodeFunctionName.add(this.functionName); } ArrayList functionNames = new ArrayList(); String lastClassName = componentBean.getFullBaseclass(); for (Iterator iter = decodeFunctionName.iterator(); iter.hasNext();) { String elementFunction = (String) iter.next(); try { log.debug("Try to load class : " + lastClassName); Class clazz = componentBean.loadClass(lastClassName); if (!iter.hasNext()) { String method = getMethod(clazz, elementFunction); if (method != null) { log.debug(method); functionNames.add(method); } else { log.error("Method " + elementFunction + " not found in class : " + lastClassName); throw new CompilationException(); } } else { // // Probing properties !!!! // PropertyDescriptor propertyDescriptor = getPropertyDescriptor(clazz, elementFunction); if (propertyDescriptor != null) { functionNames.add(propertyDescriptor.getReadMethod().getName() + "()"); log.debug("Property " + elementFunction + " mapped to function : " + propertyDescriptor.getReadMethod().getName()); lastClassName = propertyDescriptor.getPropertyType().getName(); } else { log.error("Property " + elementFunction + " not found in class : " + lastClassName); throw new CompilationException(); } } } catch (Throwable e) { log.error("Error load class : " + lastClassName + ", " + e.getLocalizedMessage()); e.printStackTrace(); throw new CompilationException("Error load class : " + lastClassName, e); } } StringBuffer tmpbuf = new StringBuffer(); for (Iterator iter = functionNames.iterator(); iter.hasNext();) { String tmpElement = (String) iter.next(); if (tmpbuf.length() != 0) { tmpbuf.append("."); } tmpbuf.append(tmpElement); } this.fullFunctionName = tmpbuf.toString(); }
From source file:com.expressui.core.dao.query.EntityQuery.java
/** * Clear this query so that all filters (query parameters) and sort-criteria are removed (except for defaults). * The method uses reflection to clear any filters defined as bean properties by subclasses. Once cleared, * re-execution of query results in all records being found or a default list of default filters are specified. * * @see #initializeDefaults/*w w w.jav a 2 s. c om*/ */ public void clear() { try { for (PropertyDescriptor descriptor : descriptors) { Method writeMethod = descriptor.getWriteMethod(); Method readMethod = descriptor.getReadMethod(); if (readMethod != null && writeMethod != null && !writeMethod.getDeclaringClass().equals(EntityQuery.class) && !writeMethod.getDeclaringClass().equals(Object.class)) { Class type = descriptor.getPropertyType(); if (type.isPrimitive() && !type.isArray()) { if (ReflectionUtil.isNumberType(type)) { writeMethod.invoke(this, 0); } else if (Boolean.class.isAssignableFrom(type)) { writeMethod.invoke(this, false); } } else { writeMethod.invoke(this, new Object[] { null }); } } } } catch (IllegalAccessException e) { Assert.PROGRAMMING.fail(e); } catch (InvocationTargetException e) { Assert.PROGRAMMING.fail(e); } initializeDefaults(); }
From source file:ca.sqlpower.architect.swingui.TestPlayPen.java
/** * Returns a new value that is not equal to oldVal. The * returned object will be a new instance compatible with oldVal. * /*from w w w .j a v a 2 s.com*/ * @param property The property that should be modified. * @param oldVal The existing value of the property to modify. The returned value * will not equal this one at the time this method was first called. */ private Object getNewDifferentValue(PropertyDescriptor property, Object oldVal) { Object newVal; // don't init here so compiler can warn if the // following code doesn't always give it a value if (property.getPropertyType() == String.class) { newVal = "new " + oldVal; } else if (property.getPropertyType() == Boolean.class || property.getPropertyType() == Boolean.TYPE) { if (oldVal == null) { newVal = new Boolean(false); } else { newVal = new Boolean(!((Boolean) oldVal).booleanValue()); } } else if (property.getPropertyType() == Double.class || property.getPropertyType() == Double.TYPE) { if (oldVal == null) { newVal = new Double(0); } else { newVal = new Double(((Double) oldVal).doubleValue() + 1); } } else if (property.getPropertyType() == Integer.class || property.getPropertyType() == Integer.TYPE) { if (oldVal == null) { newVal = new Integer(0); } else { newVal = new Integer(((Integer) oldVal).intValue() + 1); } } else if (property.getPropertyType() == Color.class) { if (oldVal == null) { newVal = new Color(0xFAC157); } else { Color oldColor = (Color) oldVal; newVal = new Color((oldColor.getRGB() + 0xF00) % 0x1000000); } } else if (property.getPropertyType() == Font.class) { if (oldVal == null) { newVal = FontManager.getDefaultPhysicalFont(); } else { Font oldFont = (Font) oldVal; newVal = new Font(oldFont.getFontName(), oldFont.getSize() + 2, oldFont.getStyle()); } } else if (property.getPropertyType() == Set.class) { newVal = new HashSet(); ((Set) newVal).add("test"); } else if (property.getPropertyType() == List.class) { newVal = new ArrayList(); ((List) newVal).add("test"); } else if (property.getPropertyType() == Point.class) { newVal = new Point(1, 3); } else { throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type " + property.getPropertyType().getName() + ") in getNewDifferentValue()"); } return newVal; }
From source file:org.getobjects.foundation.kvc.KVCWrapper.java
/** * Uses JavaBeans introspection to find all the properties of the * bean class. This method sets the {@link #accessors} variable (it will * have been null), and adds all the well-defined JavaBeans properties. * * <p>Subclasses may invoke this method before adding thier own accessors. * * <p>This method is invoked from within a synchronized block. Subclasses * do not have to worry about synchronization. **///from w ww. j a v a 2 s. c o m protected void buildPropertyAccessors() { /* * Acquire all usable field accessors first. */ if (this.accessors != null) return; /** * Construct field accessors for names which aren't occupied * by properties, yet. Imagine this as a "last resort". */ final Map<String, FieldAccessor> propertyFieldAccessorMap = new HashMap<String, FieldAccessor>(); final Field fields[] = this.clazz.getFields(); for (Field field : fields) { final int mods = field.getModifiers(); // Skip static variables and non-public instance variables. if ((Modifier.isPublic(mods) == false) || (Modifier.isStatic(mods))) continue; propertyFieldAccessorMap.put(field.getName(), new FieldAccessor(field)); } /** * Retrieve all property descriptors now */ PropertyDescriptor[] props; try { props = this.getPropertyDescriptors(this.clazz); } catch (Exception e) { logger.error("Error during getPropertyDescriptors()", e); throw new DynamicInvocationException(e); } // TBD: instead build the table locally, and then apply to an // atomic reference?! this.accessors = new ConcurrentHashMap<String, IPropertyAccessor>(16); if (logger.isDebugEnabled()) logger.debug("Recording properties for \"" + this.clazz.getName() + "\""); for (PropertyDescriptor pd : props) { final String name = pd.getName(); if (logger.isDebugEnabled()) logger.debug("Recording property \"" + name + "\""); final Method getter = pd.getReadMethod(); final Method setter = pd.getWriteMethod(); final FieldAccessor fa = propertyFieldAccessorMap.get(name); final Class type = pd.getPropertyType(); final PropertyAccessor pa = PropertyAccessor.getPropertyAccessor(name, type, getter, setter, fa); this.accessors.put(name, pa); } /** * Use field accessors for names which are not occupied, yet. * This is the default fallback. */ for (String name : propertyFieldAccessorMap.keySet()) { if (!this.accessors.containsKey(name)) this.accessors.put(name, propertyFieldAccessorMap.get(name)); } }
From source file:org.obiba.magma.beans.BeanVariableValueSourceFactory.java
/** * Finds the type ({@code Class}) for a given {@code propertyName} which may denote a nested property (property path * e.g: a.b.c) or mapped property (attribute[key]) or a combination of both (e.g.: a.b[c].d). * * @param propertyName/* w w w. j a v a 2 s .co m*/ * @return */ @SuppressWarnings({ "OverlyLongMethod", "PMD.NcssMethodCount" }) protected Class<?> getPropertyType(String propertyName) { // Has a property type been explicitly declared? If so, use it. Class<?> declaredPropertyType = propertyNameToPropertyType.get(propertyName); if (declaredPropertyType != null) { return declaredPropertyType; } Class<?> currentType = getBeanClass(); String propertyPath = propertyName; // Loop as long as the propertyPath designates a nested property while (PropertyAccessorUtils.isNestedOrIndexedProperty(propertyPath)) { int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath); String nestedProperty = pos > -1 ? propertyPath.substring(0, pos) : propertyPath; // Check whether this is a mapped property (a[b]) if (PropertyAccessorUtils.isNestedOrIndexedProperty(nestedProperty)) { // We cannot determine the type of these properties through reflection (even when they contain type parameters // i.e. Map<String, String>). // The type of these properties has to be specified through configuration currentType = getMapAttributeType(PropertyAccessorUtils.getPropertyName(nestedProperty)); if (pos == -1) { return currentType; } propertyPath = propertyPath.substring(pos + 1); } else { PropertyDescriptor currentProperty = BeanUtils.getPropertyDescriptor(currentType, nestedProperty); if (currentProperty == null) { throw new IllegalArgumentException("Invalid path '" + propertyName + "' for type " + getBeanClass().getName() + ": nested property '" + nestedProperty + "' does not exist on type " + currentType.getName()); } // Change the current type so it points to the nested type currentType = currentProperty.getPropertyType(); // Extract the nested type's property path from the original path propertyPath = propertyPath.substring(pos + 1); } } // propertyPath is a direct reference to a property of the currentType (no longer a path) PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(currentType, propertyPath); if (descriptor == null) { throw new IllegalArgumentException( "Invalid path '" + propertyName + "' for type " + getBeanClass().getName() + ": property '" + propertyPath + "' does not exist on type " + currentType.getName()); } return descriptor.getPropertyType(); }
From source file:org.androidtransfuse.processor.Merger.java
private <T extends Mergeable> T mergeMergeable(Class<? extends T> targetClass, T target, T source) throws MergerException { try {//from w ww. j a va 2s . c o m BeanInfo beanInfo = Introspector.getBeanInfo(targetClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method getter = propertyDescriptor.getReadMethod(); Method setter = propertyDescriptor.getWriteMethod(); String propertyName = propertyDescriptor.getDisplayName(); if (PropertyUtils.isWriteable(target, propertyName)) { //check for mergeCollection MergeCollection mergeCollection = findAnnotation(MergeCollection.class, getter, setter); if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { PropertyUtils.setProperty(target, propertyName, mergeList(mergeCollection, propertyName, target, source)); } //check for merge Merge mergeAnnotation = findAnnotation(Merge.class, getter, setter); PropertyUtils.setProperty(target, propertyName, mergeProperties(mergeAnnotation, propertyName, target, source)); } } } catch (NoSuchMethodException e) { throw new MergerException("NoSuchMethodException while trying to merge", e); } catch (IntrospectionException e) { throw new MergerException("IntrospectionException while trying to merge", e); } catch (IllegalAccessException e) { throw new MergerException("IllegalAccessException while trying to merge", e); } catch (InvocationTargetException e) { throw new MergerException("InvocationTargetException while trying to merge", e); } return target; }