List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:java2typescript.jackson.module.visitors.TSJsonObjectFormatVisitor.java
private boolean isAccessorMethod(Method method, BeanInfo beanInfo) { for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { if (method.equals(property.getReadMethod())) { return true; }/*www .ja v a 2 s . c o m*/ if (method.equals(property.getWriteMethod())) { return true; } } return false; }
From source file:de.extra.client.core.annotation.PropertyPlaceholderPluginConfigurer.java
private void setPluginProperties(final ConfigurableListableBeanFactory beanFactory, final Properties properties, final String beanName, final Class<?> clazz) { final PluginConfiguration annotationConfigutation = clazz.getAnnotation(PluginConfiguration.class); final MutablePropertyValues mutablePropertyValues = beanFactory.getBeanDefinition(beanName) .getPropertyValues();/* ww w . jav a2 s . c om*/ for (final PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) { final Method setter = property.getWriteMethod(); PluginValue valueAnnotation = null; if (setter != null && setter.isAnnotationPresent(PluginValue.class)) { valueAnnotation = setter.getAnnotation(PluginValue.class); } if (valueAnnotation != null) { final String key = extractKey(annotationConfigutation, valueAnnotation, clazz); final String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK); if (StringUtils.isEmpty(value)) { throw new BeanCreationException(beanName, "No such property=[" + key + "] found in properties."); } if (LOG.isDebugEnabled()) { LOG.debug("setting property=[" + clazz.getName() + "." + property.getName() + "] value=[" + key + "=" + value + "]"); } mutablePropertyValues.addPropertyValue(property.getName(), value); } } for (final Field field : clazz.getDeclaredFields()) { if (LOG.isDebugEnabled()) { LOG.debug("examining field=[" + clazz.getName() + "." + field.getName() + "]"); } if (field.isAnnotationPresent(PluginValue.class)) { final PluginValue valueAnnotation = field.getAnnotation(PluginValue.class); final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName()); if (property == null || property.getWriteMethod() == null) { throw new BeanCreationException(beanName, "setter for property=[" + clazz.getName() + "." + field.getName() + "] not available."); } final String key = extractKey(annotationConfigutation, valueAnnotation, clazz); String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK); if (value == null) { // DEFAULT Value suchen final int separatorIndex = key.indexOf(VALUE_SEPARATOR); if (separatorIndex != -1) { final String actualPlaceholder = key.substring(0, separatorIndex); final String defaultValue = key.substring(separatorIndex + VALUE_SEPARATOR.length()); value = resolvePlaceholder(actualPlaceholder, properties, SYSTEM_PROPERTIES_MODE_FALLBACK); if (value == null) { value = defaultValue; } } } if (value != null) { if (LOG.isDebugEnabled()) { LOG.debug("setting property=[" + clazz.getName() + "." + field.getName() + "] value=[" + key + "=" + value + "]"); } mutablePropertyValues.addPropertyValue(field.getName(), value); } else if (!ignoreNullValues) { throw new BeanCreationException(beanName, "No such property=[" + key + "] found in properties."); } } } }
From source file:org.apache.jcs.config.PropertySetter.java
/** * Set the named property given a {@link PropertyDescriptor}. * * @param prop/*from w w w . ja va 2 s .c om*/ * A PropertyDescriptor describing the characteristics of the * property to set. * @param name * The named of the property to set. * @param value * The value of the property. * @throws PropertySetterException */ public void setProperty(PropertyDescriptor prop, String name, String value) throws PropertySetterException { Method setter = prop.getWriteMethod(); if (setter == null) { throw new PropertySetterException("No setter for property"); } Class[] paramTypes = setter.getParameterTypes(); if (paramTypes.length != 1) { throw new PropertySetterException("#params for setter != 1"); } Object arg; try { arg = convertArg(value, paramTypes[0]); } catch (Throwable t) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed. Reason: " + t); } if (arg == null) { throw new PropertySetterException("Conversion to type [" + paramTypes[0] + "] failed."); } log.debug("Setting property [" + name + "] to [" + arg + "]."); try { setter.invoke(obj, new Object[] { arg }); } catch (Exception ex) { throw new PropertySetterException(ex); } }
From source file:cn.clickvalue.cv2.model.rowmapper.BeanPropertyRowMapper.java
/** * Initialize the mapping metadata for the given class. * @param mappedClass the mapped class./*from w w w.ja v a 2 s. com*/ */ protected void initialize(Class mappedClass) { this.mappedClass = mappedClass; this.mappedFields = new HashMap(); PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; if (pd.getWriteMethod() != null) { this.mappedFields.put(pd.getName().toLowerCase(), pd); String underscoredName = underscoreName(pd.getName()); if (!pd.getName().toLowerCase().equals(underscoredName)) { this.mappedFields.put(underscoredName, pd); } } } }
From source file:org.jspresso.framework.util.bean.PropertyHelper.java
private static PropertyDescriptor getPropertyDescriptorNoException(Class<?> beanClass, String property) { PropertyDescriptor descriptorToReturn = null; int nestedDotIndex = property.indexOf(IAccessor.NESTED_DELIM); if (nestedDotIndex > 0) { PropertyDescriptor rootDescriptor = getPropertyDescriptorNoException(beanClass, property.substring(0, nestedDotIndex)); if (rootDescriptor != null) { descriptorToReturn = getPropertyDescriptorNoException(rootDescriptor.getPropertyType(), property.substring(nestedDotIndex + 1)); }/*from ww w . java 2 s. c o m*/ } else { PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass); for (PropertyDescriptor descriptor : descriptors) { if (property.substring(0, 1).equalsIgnoreCase(descriptor.getName().substring(0, 1)) && property.substring(1).equals(descriptor.getName().substring(1))) { // 1st letter might be uppercase in descriptor and lowercase in // property when property name is like 'tEst'. descriptorToReturn = descriptor; } } } if (descriptorToReturn == null || descriptorToReturn.getWriteMethod() == null) { // If we reach this point, no property with the given name has been found. // or the found descriptor is read-only. // If beanClass is indeed an interface, we must also deal with all its // super-interfaces. List<Class<?>> superTypes = new ArrayList<>(); if (beanClass.getSuperclass() != null && beanClass.getSuperclass() != Object.class) { superTypes.add(beanClass.getSuperclass()); } Collections.addAll(superTypes, beanClass.getInterfaces()); for (Class<?> superType : superTypes) { PropertyDescriptor descriptor; descriptor = getPropertyDescriptorNoException(superType, property); if (descriptor != null) { if (descriptorToReturn != null) { try { descriptorToReturn.setWriteMethod(descriptor.getWriteMethod()); } catch (IntrospectionException ex) { throw new NestedRuntimeException(ex); } } else { descriptorToReturn = descriptor; } } } } return descriptorToReturn; }
From source file:br.bookmark.db.util.ResultSetUtils.java
/** * Populate the JavaBean properties of the specified bean, based on * the specified name/value pairs. This method uses Java reflection APIs * to identify corresponding "property setter" method names. The type of * the value in the Map must match the setter type. The setter must * expect a single arguement (the one on the Map). * <p>/*from w ww . j a v a2 s . co m*/ * The particular setter method to be called for each property is * determined using the usual JavaBeans introspection mechanisms. Thus, * you may identify custom setter methods using a BeanInfo class that is * associated with the class of the bean itself. If no such BeanInfo * class is available, the standard method name conversion ("set" plus * the capitalized name of the property in question) is used. * <p> * <strong>NOTE</strong>: It is contrary to the JavaBeans Specification * to have more than one setter method (with different argument * signatures) for the same property. * <p> * This method adopted from the Jakarta Commons BeanUtils.populate. * * @author Craig R. McClanahan * @author Ralph Schaer * @author Chris Audley * @author Rey Franois * @author Gregor Raman * @author Ted Husted * * @param bean JavaBean whose properties are being populated * @param properties Map keyed by property name, with the * corresponding value to be set * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @deprecated Use BeanUtils.CopyProperties instead. */ public static void setProperties(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException { if ((bean == null) || (properties == null)) return; /* if (debug >= 1) System.out.println("BeanUtils.populate(" + bean + ", " + properties + ")"); */ // 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) continue; // Get the property descriptor of the requested property (if any) PropertyDescriptor descriptor = null; try { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); } catch (Throwable t) { /* if (debug >= 1) System.out.println(" getPropertyDescriptor: " + t); */ descriptor = null; } if (descriptor == null) { /* if (debug >= 1) System.out.println(" No such property, skipping"); */ continue; } /* if (debug >= 1) System.out.println(" Property descriptor is '" + descriptor + "'"); */ // Identify the relevant setter method (if there is one) Method setter = descriptor.getWriteMethod(); if (setter == null) { /* if (debug >= 1) System.out.println(" No setter method, skipping"); */ continue; } // Obtain value to be set Object[] args = new Object[1]; args[0] = properties.get(name); // This MUST match setter type /* if (debug >= 1) System.out.println(" name='" + name + "', value.class='" + (value == null ? "NONE" : value.getClass().getName()) + "'"); */ /* if (debug >= 1) System.out.println(" Setting to " + (parameters[0] == null ? "NULL" : "'" + parameters[0] + "'")); */ // Invoke the setter method setter.invoke(bean, args); } /* if (debug >= 1) System.out.println("============================================"); */ }
From source file:org.apache.activemq.artemis.tests.integration.jms.connection.ConnectionFactorySerializationTest.java
private void populate(StringBuilder sb, BeanUtilsBean bean, ActiveMQConnectionFactory factory) throws IllegalAccessException, InvocationTargetException { PropertyDescriptor[] descriptors = bean.getPropertyUtils().getPropertyDescriptors(factory); for (PropertyDescriptor descriptor : descriptors) { if (descriptor.getWriteMethod() != null && descriptor.getReadMethod() != null) { if (descriptor.getPropertyType() == String.class) { String value = RandomUtil.randomString(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } else if (descriptor.getPropertyType() == int.class) { int value = RandomUtil.randomPositiveInt(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } else if (descriptor.getPropertyType() == long.class) { long value = RandomUtil.randomPositiveLong(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); } else if (descriptor.getPropertyType() == double.class) { double value = RandomUtil.randomDouble(); bean.setProperty(factory, descriptor.getName(), value); sb.append("&").append(descriptor.getName()).append("=").append(value); }/*from ww w . j a va2 s .c om*/ } } }
From source file:net.sf.dsig.Environment.java
/** * <p>Initialize an object's public properties, using any environmental * values that have been declared.//w w w . j av a 2 s . co m * * @param obj the object to initialize. * @param prefix the prefix to add while looking at the environmental values */ public void init(Object obj, String prefix) { // Iterate through all the properties declared for the applet class PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj); for (PropertyDescriptor descriptor : descriptors) { String propertyName = descriptor.getName(); logger.debug("Checking" + ": obj.class=" + obj.getClass() + ", propertyName=" + propertyName); if (descriptor.getWriteMethod() == null) { continue; } // Check if an environment parameter has been specified; if so, // override the value with the one supplied String key = (prefix != null) ? prefix + propertyName : propertyName; Object value; if (descriptor.getPropertyType().isArray()) { value = getValues(key); } else { value = getValue(key); } if (value != null) { logger.debug("Setting" + ": obj.class=" + obj.getClass() + ", propertyName=" + propertyName + ", value=" + value); try { BeanUtils.setProperty(obj, propertyName, value); } catch (Exception e) { logger.warn("Object initialization error", e); } } } }
From source file:com.twinsoft.convertigo.engine.admin.services.database_objects.Set.java
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception { Element root = document.getDocumentElement(); Document post = null;//ww w . j a v a 2s . com Element response = document.createElement("response"); try { Map<String, DatabaseObject> map = com.twinsoft.convertigo.engine.admin.services.projects.Get .getDatabaseObjectByQName(request); xpath = new TwsCachedXPathAPI(); post = XMLUtils.parseDOM(request.getInputStream()); postElt = document.importNode(post.getFirstChild(), true); String objectQName = xpath.selectSingleNode(postElt, "./@qname").getNodeValue(); DatabaseObject object = map.get(objectQName); // String comment = getPropertyValue(object, "comment").toString(); // object.setComment(comment); if (object instanceof Project) { Project project = (Project) object; String objectNewName = getPropertyValue(object, "name").toString(); Engine.theApp.databaseObjectsManager.renameProject(project, objectNewName); map.remove(objectQName); map.put(project.getQName(), project); } BeanInfo bi = CachedIntrospector.getBeanInfo(object.getClass()); PropertyDescriptor[] propertyDescriptors = bi.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); Method setter = propertyDescriptor.getWriteMethod(); Class<?> propertyTypeClass = propertyDescriptor.getReadMethod().getReturnType(); if (propertyTypeClass.isPrimitive()) { propertyTypeClass = ClassUtils.primitiveToWrapper(propertyTypeClass); } try { String propertyValue = getPropertyValue(object, propertyName).toString(); Object oPropertyValue = createObject(propertyTypeClass, propertyValue); if (object.isCipheredProperty(propertyName)) { Method getter = propertyDescriptor.getReadMethod(); String initialValue = (String) getter.invoke(object, (Object[]) null); if (oPropertyValue.equals(initialValue) || DatabaseObject.encryptPropertyValue(initialValue).equals(oPropertyValue)) { oPropertyValue = initialValue; } else { object.hasChanged = true; } } if (oPropertyValue != null) { Object args[] = { oPropertyValue }; setter.invoke(object, args); } } catch (IllegalArgumentException e) { } } Engine.theApp.databaseObjectsManager.exportProject(object.getProject()); response.setAttribute("state", "success"); response.setAttribute("message", "Project have been successfully updated!"); } catch (Exception e) { Engine.logAdmin.error("Error during saving the properties!\n" + e.getMessage()); response.setAttribute("state", "error"); response.setAttribute("message", "Error during saving the properties!"); Element stackTrace = document.createElement("stackTrace"); stackTrace.setTextContent(e.getMessage()); root.appendChild(stackTrace); } finally { xpath.resetCache(); } root.appendChild(response); }
From source file:org.toobsframework.data.beanutil.BeanMonkey.java
public static void populate(Object bean, Map properties, boolean validate) throws IllegalAccessException, InvocationTargetException, ValidationException, PermissionException { // Do nothing unless both arguments have been specified if ((bean == null) || (properties == null)) { return;/*from w w w. j a v a 2 s. c o m*/ } 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) { continue; } Object 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 { if (value != null) { 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 (validate && e.getErrorCount() > 0) { throw new ValidationException(e); } }