List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:org.kuali.kfs.module.cam.util.AssetSeparatePaymentDistributor.java
/** * Utility method which can compute the difference between source amount and consumed amounts, then will adjust the last amount * //from w w w . j ava 2s . c o m * @param source Source payments * @param consumedList Consumed Payments */ private void applyBalanceToPaymentAmounts(AssetPayment source, List<AssetPayment> consumedList) { try { for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && propertyDescriptor.getPropertyType() != null && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) { KualiDecimal amount = (KualiDecimal) readMethod.invoke(source); if (amount != null && amount.isNonZero()) { Method writeMethod = propertyDescriptor.getWriteMethod(); KualiDecimal consumedAmount = KualiDecimal.ZERO; KualiDecimal currAmt = KualiDecimal.ZERO; if (writeMethod != null) { for (int i = 0; i < consumedList.size(); i++) { currAmt = (KualiDecimal) readMethod.invoke(consumedList.get(i)); consumedAmount = consumedAmount.add(currAmt != null ? currAmt : KualiDecimal.ZERO); } } if (!consumedAmount.equals(amount)) { AssetPayment lastPayment = consumedList.get(consumedList.size() - 1); writeMethod.invoke(lastPayment, currAmt.add(amount.subtract(consumedAmount))); } } } } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.nway.spring.jdbc.bean.JavassistBeanProcessor.java
private <T> T createBeanByJavassist(ResultSet rs, Class<T> mappedClass, String key) throws SQLException { DbBeanFactory dynamicRse = DBBEANFACTORY_CACHE.get(key); // //from w w w . jav a 2 s . com if (dynamicRse != null) { return dynamicRse.createBean(rs, mappedClass); } T bean = this.newInstance(mappedClass); ResultSetMetaData rsmd = rs.getMetaData(); PropertyDescriptor[] props = BeanUtils.getPropertyDescriptors(mappedClass); int[] columnToProperty = this.mapColumnsToProperties(rsmd, props); StringBuilder handlerScript = new StringBuilder(); handlerScript.append("{").append(mappedClass.getName()).append(" bean = new ").append(mappedClass.getName()) .append("();\n"); PropertyDescriptor desc = null; for (int i = 1; i < columnToProperty.length; i++) { if (columnToProperty[i] == PROPERTY_NOT_FOUND) { continue; } desc = props[columnToProperty[i]]; Class<?> propType = desc.getPropertyType(); Object value = processColumn(rs, i, propType, desc.getWriteMethod().getName(), handlerScript); this.callSetter(bean, desc, value); } handlerScript.append("return bean;"); handlerScript.append("}"); try { ClassPool classPool = ClassPool.getDefault(); classPool.appendClassPath(new LoaderClassPath(ClassUtils.getDefaultClassLoader())); CtClass ctHandler = classPool.makeClass(DynamicClassUtils.getBeanProcessorName(mappedClass)); ctHandler.setSuperclass(classPool.get("com.nway.spring.jdbc.bean.DbBeanFactory")); CtMethod mapRow = CtNewMethod.make( "public Object createBean(java.sql.ResultSet rs, Class type) throws java.sql.SQLException{return null;}", ctHandler); mapRow.setGenericSignature("<T:Ljava/lang/Object;>(Ljava/sql/ResultSet;Ljava/lang/Class<TT;>;)TT;"); mapRow.setBody(handlerScript.toString()); ctHandler.addMethod(mapRow); DBBEANFACTORY_CACHE.put(key, (DbBeanFactory) ctHandler.toClass().newInstance()); } catch (Exception e) { throw new DynamicObjectException("javassist [ " + mappedClass.getName() + " ] ", e); } return bean; }
From source file:org.kuali.rice.krad.datadictionary.DataDictionary.java
/** * This method gets the property type of the given attributeName when the bo class is an interface * This method will also work if the bo class is not an interface, * but that case requires special handling, hence a separate method getAttributeClassWhenBOIsClass * * @param boClass//ww w . j a v a 2 s . c om * @param attributeName * @return property type */ private static Class<?> getAttributeClassWhenBOIsInterface(Class<?> boClass, String attributeName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(attributeName)) { throw new IllegalArgumentException("invalid (blank) attributeName"); } PropertyDescriptor propertyDescriptor = null; String[] intermediateProperties = attributeName.split("\\."); int lastLevel = intermediateProperties.length - 1; Class currentClass = boClass; for (int i = 0; i <= lastLevel; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class propertyType = propertyDescriptor.getPropertyType(); if (getLegacyDataAdapter().isExtensionAttribute(currentClass, currentPropertyName, propertyType)) { propertyType = getLegacyDataAdapter().getExtensionAttributeClass(currentClass, currentPropertyName); } if (Collection.class.isAssignableFrom(propertyType)) { // TODO: determine property type using generics type definition throw new AttributeValidationException( "Can't determine the Class of Collection elements because when the business object is an (possibly ExternalizableBusinessObject) interface."); } else { currentClass = propertyType; } } else { throw new AttributeValidationException( "Can't find getter method of " + boClass.getName() + " for property " + attributeName); } } return currentClass; }
From source file:org.codehaus.groovy.grails.web.taglib.RenderInputTag.java
@Override protected void doStartTagInternal() { GrailsDomainClass domainClass = (GrailsDomainClass) grailsApplication .getArtefact(DomainClassArtefactHandler.TYPE, bean.getClass().getName()); if (domainClass != null) { constrainedProperties = domainClass.getConstrainedProperties(); }//ww w . jav a 2s.com beanWrapper = new BeanWrapperImpl(bean); PropertyDescriptor pd = null; try { pd = beanWrapper.getPropertyDescriptor(property); } catch (BeansException e) { throw new GrailsTagException("Property [" + property + "] is not a valid bean property in tag [" + TAG_NAME + "]:" + e.getMessage(), e); } GroovyPagesTemplateEngine engine = (GroovyPagesTemplateEngine) servletContext .getAttribute(GrailsApplicationAttributes.GSP_TEMPLATE_ENGINE); Template t = null; try { String uri = findUriForType(pd.getPropertyType()); t = engine.createTemplate(uri); if (t == null) { throw new GrailsTagException("Type [" + pd.getPropertyType() + "] is unsupported by tag [" + TAG_NAME + "]. No template found."); } Map<String, Object> binding = new HashMap<String, Object>(); binding.put("name", pd.getName()); binding.put("value", beanWrapper.getPropertyValue(property)); if (constrainedProperties.containsKey(property)) { binding.put("constraints", constrainedProperties.get(property)); } else { binding.put("constraints", null); } t.make(binding).writeTo(out); } catch (IOException e) { throw new GrailsTagException("I/O error writing tag [" + getName() + "] to writer: " + e.getMessage(), e); } }
From source file:ca.sqlpower.matchmaker.MatchMakerTestCase.java
/** * Returns a new value that is not equal to oldVal. If oldVal is immutable, the * returned object will be a new instance compatible with oldVal. If oldVal is * mutable, it will be modified in some way so it is no longer equal to its original * value. {@link #getNewDifferentValue(MatchMakerObject, PropertyDescriptor, Object)} * is a similar method that does not take mutability into account and always returns * a new value./*from www. j av a2 s.com*/ * * @param mmo The object to which the property belongs. You might need this * if you have a special case for certain types of objects. * @param property The property that should be modified. It belongs to mmo. * @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, although it may * be the same instance as this one, but modified in some way. */ private Object modifyObject(MatchMakerObject mmo, PropertyDescriptor property, Object oldVal) throws IOException { if (property.getPropertyType() == Integer.TYPE || property.getPropertyType() == Integer.class) { return ((Integer) oldVal) + 1; } else if (property.getPropertyType() == Short.TYPE || property.getPropertyType() == Short.class) { return ((Short) oldVal) + 1; } else if (property.getPropertyType() == String.class) { if (oldVal == null) { return "new"; } else { return "new " + oldVal; } } else if (property.getPropertyType() == Boolean.class || property.getPropertyType() == Boolean.TYPE) { return new Boolean(!((Boolean) oldVal).booleanValue()); } else if (property.getPropertyType() == Long.class) { return new Long(((Long) oldVal).longValue() + 1L); } else if (property.getPropertyType() == BigDecimal.class) { return new BigDecimal(((BigDecimal) oldVal).longValue() + 1L); } else if (property.getPropertyType() == MungeSettings.class) { Integer processCount = ((MatchMakerSettings) oldVal).getProcessCount(); processCount = new Integer((processCount == null) ? new Integer(0) : processCount + 1); ((MatchMakerSettings) oldVal).setProcessCount(processCount); return oldVal; } else if (property.getPropertyType() == MergeSettings.class) { Integer processCount = ((MatchMakerSettings) oldVal).getProcessCount(); processCount = new Integer((processCount == null) ? new Integer(0) : processCount + 1); ((MatchMakerSettings) oldVal).setProcessCount(processCount); return oldVal; } else if (property.getPropertyType() == SQLTable.class) { ((SQLTable) oldVal).setRemarks("Testing Remarks"); return oldVal; } else if (property.getPropertyType() == ViewSpec.class) { ((ViewSpec) oldVal).setName("Testing New Name"); return oldVal; } else if (property.getPropertyType() == File.class) { oldVal = File.createTempFile("mmTest2", ".tmp"); ((File) oldVal).deleteOnExit(); return oldVal; } else if (property.getPropertyType() == ProjectMode.class) { if (oldVal == ProjectMode.BUILD_XREF) { return ProjectMode.FIND_DUPES; } else { return ProjectMode.BUILD_XREF; } } else if (property.getPropertyType() == MergeActionType.class) { if (oldVal == MergeActionType.AUGMENT) { return MergeActionType.SUM; } else { return MergeActionType.AUGMENT; } } else if (property.getPropertyType() == MatchMakerObject.class) { ((MatchMakerObject) oldVal).setName("Testing New Name"); return oldVal; } else if (property.getPropertyType() == MatchMakerTranslateGroup.class) { ((MatchMakerObject) oldVal).setName("Testing New Name2"); return oldVal; } else if (property.getPropertyType() == SQLColumn.class) { ((SQLColumn) oldVal).setRemarks("Testing Remarks"); return oldVal; } else if (property.getPropertyType() == Date.class) { ((Date) oldVal).setTime(((Date) oldVal).getTime() + 10000); return oldVal; } else if (property.getPropertyType() == List.class) { if (property.getName().equals("children")) { if (mmo instanceof TableMergeRules) { ((List) oldVal).add(new ColumnMergeRules()); } else { ((List) oldVal).add(new StubMatchMakerObject()); } } else { ((List) oldVal).add("Test"); } return oldVal; } else if (property.getPropertyType() == SQLIndex.class) { ((SQLIndex) oldVal).setName("modified index"); return oldVal; } else if (property.getPropertyType() == Color.class) { if (oldVal == null) { return new Color(0xFAC157); } else { Color oldColor = (Color) oldVal; return new Color((oldColor.getRGB() + 0xF00) % 0x1000000); } } else if (property.getPropertyType() == ChildMergeActionType.class) { if (oldVal != null && oldVal.equals(ChildMergeActionType.DELETE_ALL_DUP_CHILD)) { return ChildMergeActionType.UPDATE_DELETE_ON_CONFLICT; } else { return ChildMergeActionType.DELETE_ALL_DUP_CHILD; } } else if (property.getPropertyType() == TableMergeRules.class) { if (oldVal == null) { return mmo; } else { return null; } } else if (property.getPropertyType() == PoolFilterSetting.class) { if (oldVal != PoolFilterSetting.EVERYTHING) { return PoolFilterSetting.EVERYTHING; } else { return PoolFilterSetting.INVALID_ONLY; } } else if (property.getPropertyType() == AutoValidateSetting.class) { if (oldVal != AutoValidateSetting.NOTHING) { return AutoValidateSetting.NOTHING; } else { return AutoValidateSetting.SERP_CORRECTABLE; } } else if (property.getPropertyType() == TableIndex.class) { CachableTable cachableTable = new CachableTable("newValue"); TableIndex tableIndex = new TableIndex(cachableTable, "newValueIndex"); if (tableIndex.getTableIndex() == null) { tableIndex.setTableIndex(new SQLIndex()); } else { tableIndex.setTableIndex(null); } return tableIndex; } else if (property.getPropertyType() == CachableTable.class) { CachableTable cachableTable = new CachableTable("newValue"); return cachableTable; } else { throw new RuntimeException("This test case lacks the ability to modify values for " + property.getName() + " (type " + property.getPropertyType().getName() + ")"); } }
From source file:net.sourceforge.vulcan.web.struts.forms.PluginConfigForm.java
private void resetPrimitiveArraysAndBooleans() { final List<PropertyDescriptor> props = getAllProperties(); for (PropertyDescriptor pd : props) { final String name = pd.getName(); final String type = types.get(name); if (type.equals("primitive-array") || type.equals("choice-array")) { final Object emptyArray = Array.newInstance(pd.getPropertyType().getComponentType(), 0); try { BeanUtils.setProperty(this, name, emptyArray); } catch (Exception e) { throw new RuntimeException(e); }//from w w w . ja va2s . com } else if (type.equals("boolean")) { try { BeanUtils.setProperty(this, name, Boolean.FALSE); } catch (Exception e) { throw new RuntimeException(e); } } } }
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 . j ava 2s . c o m*/ */ 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:br.com.kproj.salesman.infrastructure.helpers.BeanUtils.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void copyProperty(Object dest, String fieldName, Object value, Identifiable orig) throws IllegalAccessException, InvocationTargetException { if (log.isTraceEnabled()) { createLogCopyProperty(dest, fieldName, value); }//from w w w. j a v a2 s . c o m if (!orig.getFields().contains(fieldName)) { return; } Object target = dest; int delim = fieldName.lastIndexOf(46); if (delim >= 0) { try { target = getPropertyUtils().getProperty(dest, fieldName.substring(0, delim)); } catch (NoSuchMethodException e) { return; } fieldName = fieldName.substring(delim + 1); if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + fieldName); } } String propName = null; Class type = null; int index = -1; String key = null; propName = fieldName; int i = propName.indexOf(91); if (i >= 0) { int k = propName.indexOf(93); try { index = Integer.parseInt(propName.substring(i + 1, k)); } catch (NumberFormatException e) { } propName = propName.substring(0, i); } int j = propName.indexOf(40); if (j >= 0) { int k = propName.indexOf(41); try { key = propName.substring(j + 1, k); } catch (IndexOutOfBoundsException e) { } propName = propName.substring(0, j); } if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; } type = dynaProperty.getType(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, fieldName); if (descriptor == null) return; } catch (NoSuchMethodException e) { return; } type = descriptor.getPropertyType(); if (type == null) { if (log.isTraceEnabled()) { log.trace(" target type for property '" + propName + "' is null, so skipping ths setter"); } return; } } if (log.isTraceEnabled()) { log.trace(" target propName=" + propName + ", type=" + type + ", index=" + index + ", key=" + key); } if (index >= 0) { Converter converter = getConvertUtils().lookup(type.getComponentType()); if (converter != null) { log.trace(" USING CONVERTER " + converter); value = converter.convert(type, value); } try { getPropertyUtils().setIndexedProperty(target, propName, index, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } else if (key != null) { try { getPropertyUtils().setMappedProperty(target, propName, key, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } else { Converter converter = getConvertUtils().lookup(type); if (converter != null && value != null) { log.trace(" USING CONVERTER " + converter); value = converter.convert(type, value); } try { if (value instanceof Map) { Map mapDest = (Map) getPropertyUtils().getSimpleProperty(dest, fieldName); if (mapDest != null) { Map mapOrig = (Map) value; Set entrySet = mapOrig.entrySet(); for (Object object : entrySet) { Entry entryOrig = (Entry) object; if (entryOrig.getValue() instanceof Identifiable) { if (mapDest.containsKey(entryOrig.getKey())) { Object destValue = mapDest.get(entryOrig.getKey()); new BeanUtils().copyProperties(destValue, entryOrig.getValue()); } else { mapDest.put(entryOrig.getKey(), entryOrig.getValue()); } } else { mapDest.put(entryOrig.getKey(), entryOrig.getValue()); } } } else { getPropertyUtils().setSimpleProperty(target, propName, value); } } else { getPropertyUtils().setSimpleProperty(target, propName, value); } } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } }
From source file:org.hopen.framework.rewrite.CachedIntrospectionResults.java
/** * Create a new CachedIntrospectionResults instance for the given class. * @param beanClass the bean class to analyze * @throws BeansException in case of introspection failure *//*w w w . j a v a2s . com*/ private CachedIntrospectionResults(Class beanClass, boolean cacheFullMetadata) throws BeansException { try { if (logger.isTraceEnabled()) { logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]"); } BeanInfo beanInfo = null; for (BeanInfoFactory beanInfoFactory : beanInfoFactories) { beanInfo = beanInfoFactory.getBeanInfo(beanClass); if (beanInfo != null) { break; } } if (beanInfo == null) { // If none of the factories supported the class, fall back to the default beanInfo = Introspector.getBeanInfo(beanClass); } this.beanInfo = beanInfo; // Immediately remove class from Introspector cache, to allow for proper // garbage collection on class loader shutdown - we cache it here anyway, // in a GC-friendly manner. In contrast to CachedIntrospectionResults, // Introspector does not use WeakReferences as values of its WeakHashMap! Class classToFlush = beanClass; do { Introspector.flushFromCaches(classToFlush); classToFlush = classToFlush.getSuperclass(); } while (classToFlush != null); if (logger.isTraceEnabled()) { logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]"); } this.propertyDescriptorCache = new LinkedHashMap<String, PropertyDescriptor>(); // This call is slow so we do it once. PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { if (Class.class.equals(beanClass) && "classLoader".equals(pd.getName())) { // Ignore Class.getClassLoader() method - nobody needs to bind to that continue; } if (logger.isTraceEnabled()) { logger.trace("Found bean property '" + pd.getName() + "'" + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]" : "") + (pd.getPropertyEditorClass() != null ? "; editor [" + pd.getPropertyEditorClass().getName() + "]" : "")); } if (cacheFullMetadata) { pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd); } this.propertyDescriptorCache.put(pd.getName(), pd); } } catch (IntrospectionException ex) { throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex); } }
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/* w ww .j a v a 2s . 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); 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; }