List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:com.google.feedserver.util.BeanUtil.java
/** * Applies a collection of properties to a JavaBean. Converts String and * String[] values to correct property types * /*www. j a v a 2s . c om*/ * @param properties A map of the properties to set on the JavaBean * @param bean The JavaBean to set the properties on */ public void convertPropertiesToBean(Map<String, Object> properties, Object bean) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class); for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) { String name = p.getName(); Object value = properties.get(name); Method reader = p.getReadMethod(); Method writer = p.getWriteMethod(); // we only care about "complete" properties if (reader != null && writer != null && value != null) { Class<?> propertyType = writer.getParameterTypes()[0]; if (isBean(propertyType)) { // this is a bean if (propertyType.isArray()) { propertyType = propertyType.getComponentType(); Object beanArray = Array.newInstance(propertyType, 1); if (value.getClass().isArray()) { Object[] valueArrary = (Object[]) value; int length = valueArrary.length; beanArray = Array.newInstance(propertyType, length); for (int index = 0; index < valueArrary.length; ++index) { Object valueObject = valueArrary[index]; fillBeanInArray(propertyType, beanArray, index, valueObject); } } else { fillBeanInArray(propertyType, beanArray, 0, value); } value = beanArray; } else if (propertyType == Timestamp.class) { value = new Timestamp(TIMESTAMP_FORMAT.parse((String) value).getTime()); } else { Object beanObject = createBeanObject(propertyType, value); value = beanObject; } } else { Class<?> valueType = value.getClass(); if (!propertyType.isAssignableFrom(valueType)) { // convert string input values to property type try { if (valueType == String.class) { value = ConvertUtils.convert((String) value, propertyType); } else if (valueType == String[].class) { value = ConvertUtils.convert((String[]) value, propertyType); } else if (valueType == Object[].class) { // best effort conversion Object[] objectValues = (Object[]) value; String[] stringValues = new String[objectValues.length]; for (int i = 0; i < objectValues.length; i++) { stringValues[i] = objectValues[i] == null ? null : objectValues[i].toString(); } value = ConvertUtils.convert(stringValues, propertyType); } else { } } catch (ConversionException e) { throw new IllegalArgumentException( "Conversion failed for " + "property '" + name + "' with value '" + value + "'", e); } } } // We only write values that are present in the map. This allows // defaults or previously set values in the bean to be retained. writer.invoke(bean, value); } } }
From source file:org.mule.modules.zuora.ZuoraModule.java
@MetaDataRetriever public MetaData getMetadata(MetaDataKey key) throws Exception { Class<?> cls = getClassForType(key.getId()); PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(cls); Map<String, MetaDataModel> fieldMap = new HashMap<String, MetaDataModel>(); for (PropertyDescriptor pd : pds) { if (pd.getReadMethod() != null && pd.getWriteMethod() != null) { fieldMap.put(pd.getName(), getFieldMetadata(pd.getPropertyType())); }//from w ww . j a v a 2 s. com } DefaultDefinedMapMetaDataModel mapModel = new DefaultDefinedMapMetaDataModel(fieldMap, key.getId()); return new DefaultMetaData(mapModel); }
From source file:com.gdcn.modules.db.jdbc.processor.CamelBeanProcessor.java
/** * Calls the setter method on the target object for the given property. * If no setter method exists for the property, this method does nothing. * @param target The object to set the property on. * @param prop The property to set.// w w w. ja v a 2s.c o m * @param value The value to pass into the setter. * @throws SQLException if an error occurs setting the property. */ private void callSetter(Object target, PropertyDescriptor prop, Object value) throws SQLException { Method setter = prop.getWriteMethod(); if (setter == null) { return; } Class<?>[] params = setter.getParameterTypes(); try { // convert types for some popular ones if (value instanceof java.util.Date) { final String targetType = params[0].getName(); if ("java.sql.Date".equals(targetType)) { value = new java.sql.Date(((java.util.Date) value).getTime()); } else if ("java.sql.Time".equals(targetType)) { value = new java.sql.Time(((java.util.Date) value).getTime()); } else if ("java.sql.Timestamp".equals(targetType)) { value = new java.sql.Timestamp(((java.util.Date) value).getTime()); } } // Don't call setter if the value object isn't the right type if (this.isCompatibleType(value, params[0])) { setter.invoke(target, new Object[] { value }); } else { throw new SQLException("Cannot set " + prop.getName() + ": incompatible types, cannot convert " + value.getClass().getName() + " to " + params[0].getName()); // value cannot be null here because isCompatibleType allows null } } catch (IllegalArgumentException e) { throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage()); } catch (IllegalAccessException e) { throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage()); } catch (InvocationTargetException e) { throw new SQLException("Cannot set " + prop.getName() + ": " + e.getMessage()); } }
From source file:ca.sqlpower.object.undo.PropertyChangeEdit.java
/** * Sets the value of the property to be the old value *///from w w w .jav a2 s . com @Override public void undo() throws CannotUndoException { logger.debug("Undoing Property change: Setting " + sourceEvent.getPropertyName() + " from " + sourceEvent.getNewValue() + " to " + sourceEvent.getOldValue()); super.undo(); try { final PropertyDescriptor propertyDescriptor = PropertyUtils .getPropertyDescriptor(sourceEvent.getSource(), sourceEvent.getPropertyName()); logger.debug("Found property descriptor " + propertyDescriptor); if (logger.isDebugEnabled()) { PropertyDescriptor[] propertyDescriptors = PropertyUtils .getPropertyDescriptors(sourceEvent.getSource()); logger.debug("Descriptor has write method " + propertyDescriptor.getWriteMethod()); } Method setter = PropertyUtils.getWriteMethod(propertyDescriptor); logger.info("Found setter: " + setter.getName()); setter.invoke(sourceEvent.getSource(), sourceEvent.getOldValue()); } catch (Exception ex) { CannotUndoException wrapper = new CannotUndoException(); wrapper.initCause(ex); throw wrapper; } }
From source file:org.pentaho.reporting.engine.classic.core.util.beans.BeanUtility.java
public String[] getProperties() throws BeanException { final ArrayList<String> propertyNames = new ArrayList<String>(); final PropertyDescriptor[] pd = getPropertyInfos(); for (int i = 0; i < pd.length; i++) { final PropertyDescriptor property = pd[i]; if (property.isHidden()) { continue; }/* w w w . j a v a 2 s . co m*/ if (property.getReadMethod() == null || property.getWriteMethod() == null) { // it will make no sense to write a property now, that // we can't read in later... continue; } if (BeanUtility.getPropertyType(property).isArray()) { final int max = findMaximumIndex(property); for (int idx = 0; idx < max; idx++) { propertyNames.add(property.getName() + '[' + idx + ']'); } } else { propertyNames.add(property.getName()); } } return propertyNames.toArray(new String[propertyNames.size()]); }
From source file:org.malaguna.cmdit.service.reflection.ReflectionUtils.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void updateOldValue(Object oldObj, PropertyDescriptor desc, Object oldValue, Object newValue) { if (Collection.class.isAssignableFrom(desc.getPropertyType())) { Collection oldSetAux = (Collection) oldValue; Collection newSetAux = (Collection) newValue; if (oldSetAux == null) { setNewValue(oldObj, desc.getWriteMethod(), newSetAux); } else {//w w w.j a v a 2 s .c om //oldSetAux.clear(); if (newSetAux != null) { Collection<?> intersection = CollectionUtils.intersection(oldSetAux, newSetAux); Collection<?> nuevos = CollectionUtils.removeAll(newSetAux, intersection); Collection<?> borrados = CollectionUtils.removeAll(oldSetAux, intersection); oldSetAux.removeAll(borrados); oldSetAux.addAll(nuevos); } } } else { setNewValue(oldObj, desc.getWriteMethod(), newValue); } }
From source file:org.apache.tapestry.enhance.ComponentClassFactory.java
/** * Checks to see that that class either doesn't provide the property, or does * but the accessor(s) are abstract. Returns the name of the read accessor, * or null if there is no such accessor (this is helpful if the beanClass * defines a boolean property, where the name of the accessor may be isXXX or * getXXX).// w w w .j a v a 2s .c o m * **/ protected String checkAccessors(String propertyName, Class propertyType, ILocation location) { PropertyDescriptor d = getPropertyDescriptor(propertyName); if (d == null) return null; checkPropertyType(d, propertyType, location); Method write = d.getWriteMethod(); Method read = d.getReadMethod(); if (isImplemented(write)) throw new ApplicationRuntimeException(Tapestry.format("ComponentClassFactory.non-abstract-write", write.getDeclaringClass().getName(), propertyName), location, null); if (isImplemented(read)) throw new ApplicationRuntimeException(Tapestry.format("ComponentClassFactory.non-abstract-read", read.getDeclaringClass().getName(), propertyName), location, null); return read == null ? null : read.getName(); }
From source file:com.bstek.dorado.config.definition.Definition.java
/** * ?/* w ww. java2 s .co m*/ * * @param object * ? * @param property * ?? * @param value * @see {@link #getProperties()} * @param context * * @throws Exception */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected void setObjectProperty(Object object, String property, Object value, CreationContext context) throws Exception { if (object instanceof Map) { value = DefinitionUtils.getRealValue(value, context); if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { List collection = new ArrayList(); for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } value = collection; } if (value != ConfigUtils.IGNORE_VALUE) { ((Map) object).put(property, value); } } else { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(object, property); if (propertyDescriptor != null) { Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); Class<?> propertyType = propertyDescriptor.getPropertyType(); if (writeMethod != null) { Class<?> oldImpl = context.getDefaultImpl(); try { context.setDefaultImpl(propertyType); value = DefinitionUtils.getRealValue(value, context); } finally { context.setDefaultImpl(oldImpl); } if (!propertyType.equals(String.class) && value instanceof String) { if (propertyType.isEnum()) { value = Enum.valueOf((Class) propertyType, (String) value); } else if (StringUtils.isBlank((String) value)) { value = null; } } else if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { List collection = new ArrayList(); for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } value = collection; } if (value != ConfigUtils.IGNORE_VALUE) { writeMethod.invoke(object, new Object[] { ConvertUtils.convert(value, propertyType) }); } } else if (readMethod != null && Collection.class.isAssignableFrom(propertyType)) { Collection collection = (Collection) readMethod.invoke(object, EMPTY_ARGS); if (collection != null) { if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } } else { collection.addAll((Collection) value); } } } else { throw new NoSuchMethodException( "Property [" + property + "] of [" + object + "] is not writable."); } } else { throw new NoSuchMethodException("Property [" + property + "] not found in [" + object + "]."); } } }
From source file:org.thiesen.helenaorm.HelenaColumnDAO.java
private boolean safeIsAnnotationPresent(final PropertyDescriptor d, final Class<? extends Annotation> annotation) { return nullSafeAnnotationPresent(annotation, fields.get(d.getName())) || nullSafeAnnotationPresent(annotation, d.getReadMethod()) || nullSafeAnnotationPresent(annotation, d.getWriteMethod()); }