List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:ResultSetIterator.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.//from w w w . j a va 2 s.c om * @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 != null) { if (value instanceof java.util.Date) { if (params[0].getName().equals("java.sql.Date")) { value = new java.sql.Date(((java.util.Date) value).getTime()); } else if (params[0].getName().equals("java.sql.Time")) { value = new java.sql.Time(((java.util.Date) value).getTime()); } else if (params[0].getName().equals("java.sql.Timestamp")) { 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."); } } 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.matchmaker.swingui.SaveAndOpenWorkspaceActionTest.java
private void buildChildren(SPObject parent) { for (Class c : parent.getAllowedChildTypes()) { try {// www. j a v a 2 s . co m if (parent.getChildren(c).size() > 0) { logger.debug("It already had a " + c.getSimpleName() + "!"); continue; } SPObject child; child = ((SPObject) valueMaker.makeNewValue(c, null, "child")); parent.addChild(child, parent.getChildren(c).size()); } catch (Exception e) { logger.warn("Could not add a " + c.getSimpleName() + " to a " + parent.getClass().getSimpleName() + " because of a " + e.getClass().getName()); } try { Set<String> s = TestUtils.findPersistableBeanProperties(parent, false, false); List<PropertyDescriptor> settableProperties = Arrays .asList(PropertyUtils.getPropertyDescriptors(parent.getClass())); TableMergeRules testParent = null; // special case- the parent of all others //set all properties of the object for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!s.contains(property.getName())) continue; if (property.getName().equals("parent")) continue; //Changing the parent causes headaches. if (property.getName().equals("session")) continue; if (property.getName().equals("type")) continue; try { oldVal = PropertyUtils.getSimpleProperty(parent, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug("Skipping non-settable property " + property.getName() + " on " + parent.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); if (property.getName().equals("parentMergeRule")) { if (testParent == null) { newVal = null; testParent = (TableMergeRules) parent; } else { newVal = testParent; } } try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + (newVal == null ? "null" : newVal.getClass().getName()) + ")"); BeanUtils.copyProperty(parent, property.getName(), newVal); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + parent.getClass().getName()); } } } catch (Exception e) { throw new RuntimeException(e); } } for (SPObject spo : parent.getChildren()) { buildChildren(spo); } }
From source file:org.hawkular.inventory.impl.tinkerpop.sql.impl.SqlGraph.java
private void setupDataSource(DataSource dataSource, Configuration configuration) throws Exception { BeanInfo beanInfo = Introspector.getBeanInfo(dataSource.getClass()); PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors(); Map<String, PropertyDescriptor> propsByName = new HashMap<>(); for (PropertyDescriptor p : properties) { propsByName.put(p.getName().toLowerCase(), p); }//w w w . ja v a 2 s. c om Iterator it = configuration.getKeys("sql.datasource"); while (it.hasNext()) { String key = (String) it.next(); String property = key.substring("sql.datasource.".length()).toLowerCase(); PropertyDescriptor d = propsByName.get(property); if (d == null) { continue; } Method write = d.getWriteMethod(); if (write != null) { write.invoke(dataSource, configuration.getProperty(key)); } } }
From source file:com.google.code.pathlet.web.ognl.impl.OgnlUtil.java
/** * Copies the properties in the object "from" and sets them in the object "to" * using specified type converter, or {@link com.opensymphony.xwork2.conversion.impl.XWorkConverter} if none * is specified.//from w ww. ja v a2s .c o m * * @param from the source object * @param to the target object * @param context the action context we're running under * @param exclusions collection of method names to excluded from copying ( can be null) * @param inclusions collection of method names to included copying (can be null) * note if exclusions AND inclusions are supplied and not null nothing will get copied. */ public void copy(Object from, Object to, Map<String, Object> context, Collection<String> exclusions, Collection<String> inclusions) { if (from == null || to == null) { log.warn( "Attempting to copy from or to a null source. This is illegal and is bein skipped. This may be due to an error in an OGNL expression, action chaining, or some other event."); return; } TypeConverter conv = defaultConverter; Map contextFrom = Ognl.createDefaultContext(from); Ognl.setTypeConverter(contextFrom, conv); Map contextTo = Ognl.createDefaultContext(to); Ognl.setTypeConverter(contextTo, conv); PropertyDescriptor[] fromPds; PropertyDescriptor[] toPds; try { fromPds = this.reflectionProvider.getPropertyDescriptors(from); toPds = this.reflectionProvider.getPropertyDescriptors(to); } catch (IntrospectionException e) { log.error("An error occured", e); return; } Map<String, PropertyDescriptor> toPdHash = new HashMap<String, PropertyDescriptor>(); for (PropertyDescriptor toPd : toPds) { toPdHash.put(toPd.getName(), toPd); } for (PropertyDescriptor fromPd : fromPds) { if (fromPd.getReadMethod() != null) { boolean copy = true; if (exclusions != null && exclusions.contains(fromPd.getName())) { copy = false; } else if (inclusions != null && !inclusions.contains(fromPd.getName())) { copy = false; } if (copy == true) { PropertyDescriptor toPd = toPdHash.get(fromPd.getName()); if ((toPd != null) && (toPd.getWriteMethod() != null)) { try { Object expr = compile(fromPd.getName()); Object value = Ognl.getValue(expr, contextFrom, from); Ognl.setValue(expr, contextTo, to, value); } catch (OgnlException e) { // ignore, this is OK } } } } } }
From source file:no.sesat.search.datamodel.BeanDataObjectInvocationHandler.java
private Method findSupport(final String propertyName, final boolean setter) throws IntrospectionException { // If there's a support instance, use it first. Method m = null;/*from w w w. ja va 2 s . co m*/ if (null != support) { final PropertyDescriptor[] propDescriptors = Introspector .getBeanInfo(support.getClass().getInterfaces()[0]).getPropertyDescriptors(); for (PropertyDescriptor pd : propDescriptors) { if (propertyName.equalsIgnoreCase(pd.getName())) { if (pd instanceof MappedPropertyDescriptor) { final MappedPropertyDescriptor mpd = (MappedPropertyDescriptor) pd; m = setter ? mpd.getMappedWriteMethod() : mpd.getMappedReadMethod(); } else { m = setter ? pd.getWriteMethod() : pd.getReadMethod(); } break; } } } return m; }
From source file:org.kuali.kfs.module.cam.util.AssetSeparatePaymentDistributor.java
/** * Utility method which will negate the payment amounts for a given payment * /* w w w. ja v a 2s. c o m*/ * @param assetPayment Payment to be negated */ public void negatePaymentAmounts(AssetPayment assetPayment) { 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(assetPayment); Method writeMethod = propertyDescriptor.getWriteMethod(); if (writeMethod != null && amount != null) { writeMethod.invoke(assetPayment, (amount.negated())); } } } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java
@SuppressWarnings("rawtypes") private Column2Property getIdFromObject(Class clazz) throws Exception { // ???//from w ww .j a va 2s .co m for (Field field : clazz.getDeclaredFields()) { String columnName = null; Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation a : annotations) { if (a instanceof Id) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); Column2Property c = new Column2Property(); c.propertyName = pd.getName(); c.setterMethodName = pd.getWriteMethod().getName(); c.getterMethodName = pd.getReadMethod().getName(); c.columnName = columnName; return c; } } } return null; }
From source file:org.tinygroup.beanwrapper.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 *//*ww w . j av a2 s .c o m*/ private CachedIntrospectionResults(Class beanClass) throws BeansException { try { if (logger.isTraceEnabled()) { logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]"); } this.beanInfo = Introspector.getBeanInfo(beanClass); // 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 HashMap(); // This call is slow so we do it once. PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; 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 (JdkVersion.isAtLeastJava15()) { pd = new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(), pd.getWriteMethod(), pd.getPropertyEditorClass()); } this.propertyDescriptorCache.put(pd.getName(), pd); } } catch (IntrospectionException ex) { throw new FatalBeanException("Cannot get BeanInfo for object of class [" + beanClass.getName() + "]", ex); } }
From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java
/** * Gets class type of field parameters in a class for which setters are to * be found/*from ww w . j a v a 2 s.c o m*/ * * @param thisPojoClass * @param ctClass * @param ctMethodSet * can be a subset of setters for fields in this class * @return set of classes representing field types * @throws NotFoundException */ @SuppressWarnings("serial") private Set<Class<?>> getPropertyClassTypes(final Class<?> thisPojoClass, final CtClass ctClass, final Set<CtMethod> ctMethodSet) throws NotFoundException { Set<Class<?>> set = new LinkedHashSet<>(); try { final Object bean = thisPojoClass.newInstance(); // create an // instance for (Field field : thisPojoClass.getDeclaredFields()) { if (field.isSynthetic()) { LOGGER.warning(field.getName() + " is syntheticlly added, so ignoring"); continue; } PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, field.getName()); assert pd != null; if (pd != null) { if (pd.getPropertyType() != null) { set.add(pd.getPropertyType()); // irrespective of // CtMethod just add final Method mutator = pd.getWriteMethod(); if (mutator != null && ctMethodSet.add(ctClass.getDeclaredMethod(mutator.getName()))) { LOGGER.info(mutator.getName() + " is ADDED"); } } } else { LOGGER.warning("Unable to get Proprty (Field's class) Type for:" + field.getName()); } } } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new NotFoundException("Exception Not Found:", e); } return set; }
From source file:com.maomao.framework.dao.jdbc.JdbcDAO.java
@SuppressWarnings("rawtypes") private Column2Property getIdFromObject(Class clazz) throws Exception { // ???/*w w w . j a v a 2s . c o m*/ Column2Property c = null; for (Field field : clazz.getDeclaredFields()) { String columnName = null; Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation a : annotations) { if (a instanceof Id) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); c = new Column2Property(); c.propertyName = pd.getName(); c.setterMethodName = pd.getWriteMethod().getName(); c.getterMethodName = pd.getReadMethod().getName(); c.columnName = columnName; break; } } } if (c == null) { Class superClass = clazz.getSuperclass(); for (Field field : superClass.getDeclaredFields()) { String columnName = null; Annotation[] annotations = field.getDeclaredAnnotations(); for (Annotation a : annotations) { if (a instanceof Id) { PropertyDescriptor pd = new PropertyDescriptor(field.getName(), superClass); c = new Column2Property(); c.propertyName = pd.getName(); c.setterMethodName = pd.getWriteMethod().getName(); c.getterMethodName = pd.getReadMethod().getName(); c.columnName = columnName; break; } } } } return c; }