BeanUtilsBean.java

Index Score
org.apache.commons.beanutils
Commons BeanUtils

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
DOC_COMMENTNumber of javadoc comment lines
SIZESize of the file in bytes
COMMENTSComment lines
RETURNSNumber of return points from functions
BLOCKSNumber of blocks
INTERFACE_COMPLEXITYInterface complexity
LINESNumber of lines in the source file
CYCLOMATICCyclomatic complexity
EXEC_COMMENTSComments in executable code
DECL_COMMENTSComments in declarations
EXITSProcedure exits
OPERATORSNumber of operators
PROGRAM_LENGTHHalstead program length
LINE_COMMENTNumber of line comments
LOOPSNumber of loops
ELOCEffective lines of code
COMPARISONSNumber of comparison operators
OPERANDSNumber of operands
LOCLines of code
LOGICAL_LINESNumber of statements
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
UNIQUE_OPERANDSNumber of unique operands
JAVA0034JAVA0034 Missing braces in if statement
PROGRAM_VOCABHalstead program vocabulary
JAVA0254JAVA0254 Use enhanced for loop construct instead of Iterator
PARAMSNumber of formal parameter declarations
JAVA0170JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0117JAVA0117 Missing javadoc: method 'method'
JAVA0166JAVA0166 Generic exception caught
PROGRAM_VOLUMEHalstead program volume
UNIQUE_OPERATORSNumber of unique operators
JAVA0136JAVA0136 N methods defined in class (maximum: M)
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
NEST_DEPTHMaximum nesting depth
JAVA0145JAVA0145 Tab character used in source file
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; import java.beans.IndexedPropertyDescriptor; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.beanutils.expression.Resolver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * <p>JavaBean property population methods.</p> * * <p>This class provides implementations for the utility methods in * {@link BeanUtils}. * Different instances can be used to isolate caches between classloaders * and to vary the value converters registered.</p> * * @author Craig R. McClanahan * @author Ralph Schaer * @author Chris Audley * @author Rey Francois * @author Gregor Rayman * @version $Revision: 687117 $ $Date: 2008-08-19 14:19:36 -0400 (Tue, 19 Aug 2008) $ * @see BeanUtils * @since 1.7 */ public class BeanUtilsBean { // ------------------------------------------------------ Private Class Variables /** * Contains <code>BeanUtilsBean</code> instances indexed by context classloader. */ private static final ContextClassLoaderLocal BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal() { // Creates the default instance used when the context classloader is unavailable protected Object initialValue() { return new BeanUtilsBean(); } }; /** * Gets the instance which provides the functionality for {@link BeanUtils}. * This is a pseudo-singleton - an single instance is provided per (thread) context classloader. * This mechanism provides isolation for web apps deployed in the same container. * * @return The (pseudo-singleton) BeanUtils bean instance */ public static BeanUtilsBean getInstance() { return (BeanUtilsBean) BEANS_BY_CLASSLOADER.get(); } /** * Sets the instance which provides the functionality for {@link BeanUtils}. * This is a pseudo-singleton - an single instance is provided per (thread) context classloader. * This mechanism provides isolation for web apps deployed in the same container. * * @param newInstance The (pseudo-singleton) BeanUtils bean instance */ public static void setInstance(BeanUtilsBean newInstance) { BEANS_BY_CLASSLOADER.set(newInstance); } // --------------------------------------------------------- Attributes /** * Logging for this instance */ private Log log = LogFactory.getLog(BeanUtils.class); /** Used to perform conversions between object types when setting properties */ private ConvertUtilsBean convertUtilsBean; /** Used to access properties*/ private PropertyUtilsBean propertyUtilsBean; /** A reference to Throwable's initCause method, or null if it's not there in this JVM */ private static final Method INIT_CAUSE_METHOD = getInitCauseMethod(); // --------------------------------------------------------- Constuctors /** * <p>Constructs an instance using new property * and conversion instances.</p> */ public BeanUtilsBean() { this(new ConvertUtilsBean(), new PropertyUtilsBean()); } /** * <p>Constructs an instance using given conversion instances * and new {@link PropertyUtilsBean} instance.</p> * * @param convertUtilsBean use this <code>ConvertUtilsBean</code> * to perform conversions from one object to another * * @since 1.8.0 */ public BeanUtilsBean(ConvertUtilsBean convertUtilsBean) { this(convertUtilsBean, new PropertyUtilsBean()); } /** * <p>Constructs an instance using given property and conversion instances.</p> * * @param convertUtilsBean use this <code>ConvertUtilsBean</code> * to perform conversions from one object to another * @param propertyUtilsBean use this <code>PropertyUtilsBean</code> * to access properties */ public BeanUtilsBean( ConvertUtilsBean convertUtilsBean, PropertyUtilsBean propertyUtilsBean) { this.convertUtilsBean = convertUtilsBean; this.propertyUtilsBean = propertyUtilsBean; } // --------------------------------------------------------- Public Methods /** * <p>Clone a bean based on the available property getters and setters, * even if the bean class itself does not implement Cloneable.</p> * * <p> * <strong>Note:</strong> this method creates a <strong>shallow</strong> clone. * In other words, any objects referred to by the bean are shared with the clone * rather than being cloned in turn. * </p> * * @param bean Bean to be cloned * @return the cloned bean * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InstantiationException if a new instance of the bean's * class cannot be instantiated * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public Object cloneBean(Object bean) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { if (log.isDebugEnabled()) { log.debug("Cloning bean: " + bean.getClass().getName()); } Object newBean = null; if (bean instanceof DynaBean) { newBean = ((DynaBean) bean).getDynaClass().newInstance(); } else { newBean = bean.getClass().newInstance(); } getPropertyUtils().copyProperties(newBean, bean); return (newBean); } /** * <p>Copy property values from the origin bean to the destination bean * for all cases where the property names are the same. For each * property, a conversion is attempted as necessary. All combinations of * standard JavaBeans and DynaBeans as origin and destination are * supported. Properties that exist in the origin bean, but do not exist * in the destination bean (or are read-only in the destination bean) are * silently ignored.</p> * * <p>If the origin "bean" is actually a <code>Map</code>, it is assumed * to contain String-valued <strong>simple</strong> property names as the keys, pointing at * the corresponding property values that will be converted (if necessary) * and set in the destination bean. <strong>Note</strong> that this method * is intended to perform a "shallow copy" of the properties and so complex * properties (for example, nested ones) will not be copied.</p> * * <p>This method differs from <code>populate()</code>, which * was primarily designed for populating JavaBeans from the map of request * parameters retrieved on an HTTP request, is that no scalar->indexed * or indexed->scalar manipulations are performed. If the origin property * is indexed, the destination property must be also.</p> * * <p>If you know that no type conversions are required, the * <code>copyProperties()</code> method in {@link PropertyUtils} will * execute faster than this method.</p> * * <p><strong>FIXME</strong> - Indexed and mapped properties that do not * have getter and setter methods for the underlying array or Map are not * copied by this method.</p> * * @param dest Destination bean whose properties are modified * @param orig Origin bean whose properties are retrieved * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if the <code>dest</code> or * <code>orig</code> argument is null or if the <code>dest</code> * property type is different from the source type and the relevant * converter has not been registered. * @exception InvocationTargetException if the property accessor method * throws an exception */ public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException { // Validate existence of the specified beans if (dest == null) { throw new IllegalArgumentException ("No destination bean specified"); } if (orig == null) { throw new IllegalArgumentException("No origin bean specified"); } if (log.isDebugEnabled()) { log.debug("BeanUtils.copyProperties(" + dest + ", " + orig + ")"); } // Copy the properties, converting as necessary if (orig instanceof DynaBean) { DynaProperty[] origDescriptors = ((DynaBean) orig).getDynaClass().getDynaProperties(); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); // Need to check isReadable() for WrapDynaBean // (see Jira issue# BEANUTILS-61) if (getPropertyUtils().isReadable(orig, name) && getPropertyUtils().isWriteable(dest, name)) { Object value = ((DynaBean) orig).get(name); copyProperty(dest, name, value); } } } else if (orig instanceof Map) { Iterator entries = ((Map) orig).entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); String name = (String)entry.getKey(); if (getPropertyUtils().isWriteable(dest, name)) { copyProperty(dest, name, entry.getValue()); } } } else /* if (orig is a standard JavaBean) */ { PropertyDescriptor[] origDescriptors = getPropertyUtils().getPropertyDescriptors(orig); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if ("class".equals(name)) { continue; // No point in trying to set an object's class } if (getPropertyUtils().isReadable(orig, name) && getPropertyUtils().isWriteable(dest, name)) { try { Object value = getPropertyUtils().getSimpleProperty(orig, name); copyProperty(dest, name, value); } catch (NoSuchMethodException e) { // Should not happen } } } } } /** * <p>Copy the specified property value to the specified destination bean, * performing any type conversion that is required. If the specified * bean does not have a property of the specified name, or the property * is read only on the destination bean, return without * doing anything. If you have custom destination property types, register * {@link Converter}s for them by calling the <code>register()</code> * method of {@link ConvertUtils}.</p> * * <p><strong>IMPLEMENTATION RESTRICTIONS</strong>:</p> * <ul> * <li>Does not support destination properties that are indexed, * but only an indexed setter (as opposed to an array setter) * is available.</li> * <li>Does not support destination properties that are mapped, * but only a keyed setter (as opposed to a Map setter) * is available.</li> * <li>The desired property type of a mapped setter cannot be * determined (since Maps support any data type), so no conversion * will be performed.</li> * </ul> * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value 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 */ public void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) if (log.isTraceEnabled()) { StringBuffer sb = new StringBuffer(" copyProperty("); sb.append(bean); sb.append(", "); sb.append(name); sb.append(", "); if (value == null) { sb.append("<NULL>"); } else if (value instanceof String) { sb.append((String) value); } else if (value instanceof String[]) { String[] values = (String[]) value; sb.append('['); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(','); } sb.append(values[i]); } sb.append(']'); } else { sb.append(value.toString()); } sb.append(')'); log.trace(sb.toString()); } // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); name = resolver.remove(name); } catch (NoSuchMethodException e) { return; // Skip this property setter } } if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property Class type = null; // Java type of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) // Calculate the target property type if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; // Skip this property setter } type = dynaProperty.getType(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (NoSuchMethodException e) { return; // Skip this property setter } type = descriptor.getPropertyType(); if (type == null) { // Most likely an indexed setter on a POJB only 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); } // Convert the specified value to the required type and store it if (index >= 0) { // Destination must be indexed value = convert(value, type.getComponentType()); try { getPropertyUtils().setIndexedProperty(target, propName, index, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } else if (key != null) { // Destination must be mapped // Maps do not know what the preferred data type is, // so perform no conversions at all // FIXME - should we create or support a TypedMap? try { getPropertyUtils().setMappedProperty(target, propName, key, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } else { // Destination must be simple value = convert(value, type); try { getPropertyUtils().setSimpleProperty(target, propName, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } } /** * <p>Return the entire set of properties for which the specified bean * provides a read method. This map contains the to <code>String</code> * converted property values for all properties for which a read method * is provided (i.e. where the getReadMethod() returns non-null).</p> * * <p>This map can be fed back to a call to * <code>BeanUtils.populate()</code> to reconsitute the same set of * properties, modulo differences for read-only and write-only * properties, but only if there are no indexed properties.</p> * * <p><strong>Warning:</strong> if any of the bean property implementations * contain (directly or indirectly) a call to this method then * a stack overflow may result. For example: * <code><pre> * class MyBean * { * public Map getParameterMap() * { * BeanUtils.describe(this); * } * } * </pre></code> * will result in an infinite regression when <code>getParametersMap</code> * is called. It is recommended that such methods are given alternative * names (for example, <code>parametersMap</code>). * </p> * @param bean Bean whose properties are to be extracted * @return Map of property descriptors * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { // return (Collections.EMPTY_MAP); return (new java.util.HashMap()); } if (log.isDebugEnabled()) { log.debug("Describing bean: " + bean.getClass().getName()); } Map description = new HashMap(); if (bean instanceof DynaBean) { DynaProperty[] descriptors = ((DynaBean) bean).getDynaClass().getDynaProperties(); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); description.put(name, getProperty(bean, name)); } } else { PropertyDescriptor[] descriptors = getPropertyUtils().getPropertyDescriptors(bean); Class clazz = bean.getClass(); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if (getPropertyUtils().getReadMethod(clazz, descriptors[i]) != null) { description.put(name, getProperty(bean, name)); } } } return (description); } /** * Return the value of the specified array property of the specified * bean, as a String array. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The array property value * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String[] getArrayProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getProperty(bean, name); if (value == null) { return (null); } else if (value instanceof Collection) { ArrayList values = new ArrayList(); Iterator items = ((Collection) value).iterator(); while (items.hasNext()) { Object item = items.next(); if (item == null) { values.add((String) null); } else { // convert to string using convert utils values.add(getConvertUtils().convert(item)); } } return ((String[]) values.toArray(new String[values.size()])); } else if (value.getClass().isArray()) { int n = Array.getLength(value); String[] results = new String[n]; for (int i = 0; i < n; i++) { Object item = Array.get(value, i); if (item == null) { results[i] = null; } else { // convert to string using convert utils results[i] = getConvertUtils().convert(item); } } return (results); } else { String[] results = new String[1]; results[0] = getConvertUtils().convert(value); return (results); } } /** * Return the value of the specified indexed property of the specified * bean, as a String. The zero-relative index of the * required value must be included (in square brackets) as a suffix to * the property name, or <code>IllegalArgumentException</code> will be * thrown. * * @param bean Bean whose property is to be extracted * @param name <code>propertyname[index]</code> of the property value * to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getIndexedProperty(bean, name); return (getConvertUtils().convert(value)); } /** * Return the value of the specified indexed property of the specified * bean, as a String. The index is specified as a method parameter and * must *not* be included in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * @return The indexed property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getIndexedProperty(bean, name, index); return (getConvertUtils().convert(value)); } /** * Return the value of the specified indexed property of the specified * bean, as a String. The String-valued key of the required value * must be included (in parentheses) as a suffix to * the property name, or <code>IllegalArgumentException</code> will be * thrown. * * @param bean Bean whose property is to be extracted * @param name <code>propertyname(index)</code> of the property value * to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getMappedProperty(bean, name); return (getConvertUtils().convert(value)); } /** * Return the value of the specified mapped property of the specified * bean, as a String. The key is specified as a method parameter and * must *not* be included in the property name expression * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param key Lookup key of the property value to be extracted * @return The mapped property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getMappedProperty(bean, name, key); return (getConvertUtils().convert(value)); } /** * Return the value of the (possibly nested) property of the specified * name, for the specified bean, as a String. * * @param bean Bean whose property is to be extracted * @param name Possibly nested name of the property to be extracted * @return The nested property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getNestedProperty(bean, name); return (getConvertUtils().convert(value)); } /** * Return the value of the specified property of the specified bean, * no matter which property reference format is used, as a String. * * @param bean Bean whose property is to be extracted * @param name Possibly indexed and/or nested name of the property * to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (getNestedProperty(bean, name)); } /** * Return the value of the specified simple property of the specified * bean, converted to a String. * * @param bean Bean whose property is to be extracted * @param name Name of the property to be extracted * @return The property's value, converted to a String * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * property cannot be found */ public String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = getPropertyUtils().getSimpleProperty(bean, name); return (getConvertUtils().convert(value)); } /** * <p>Populate the JavaBeans 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, and deals * with setter arguments of type <code>String</code>, <code>boolean</code>, * <code>int</code>, <code>long</code>, <code>float</code>, and * <code>double</code>. In addition, array setters for these types (or the * corresponding primitive types) can also be identified.</p> * * <p>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> * * <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> * * <p><strong>WARNING</strong> - The logic of this method is customized * for extracting String-based request parameters from an HTTP request. * It is probably not what you want for general property copying with * type conversion. For that purpose, check out the * <code>copyProperties()</code> method instead.</p> * * @param bean JavaBean whose properties are being populated * @param properties Map keyed by property name, with the * corresponding (String or String[]) value(s) 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 */ public void populate(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException { // Do nothing unless both arguments have been specified if ((bean == null) || (properties == null)) { return; } if (log.isDebugEnabled()) { log.debug("BeanUtils.populate(" + bean + ", " + properties + ")"); } // Loop through the property name/value pairs to be set Iterator entries = properties.entrySet().iterator(); while (entries.hasNext()) { // Identify the property name and value(s) to be assigned Map.Entry entry = (Map.Entry)entries.next(); String name = (String) entry.getKey(); if (name == null) { continue; } // Perform the assignment for this property setProperty(bean, name, entry.getValue()); } } /** * <p>Set the specified property value, performing type conversions as * required to conform to the type of the destination property.</p> * * <p>If the property is read only then the method returns * without throwing an exception.</p> * * <p>If <code>null</code> is passed into a property expecting a primitive value, * then this will be converted as if it were a <code>null</code> string.</p> * * <p><strong>WARNING</strong> - The logic of this method is customized * to meet the needs of <code>populate()</code>, and is probably not what * you want for general property copying with type conversion. For that * purpose, check out the <code>copyProperty()</code> method instead.</p> * * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this * method without consulting with the Struts developer community. There * are some subtleties to its functionality that are not documented in the * Javadoc description above, yet are vital to the way that Struts utilizes * this method.</p> * * @param bean Bean on which setting is to be performed * @param name Property name (can be nested/indexed/mapped/combo) * @param value 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 */ public void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { // Trace logging (if enabled) if (log.isTraceEnabled()) { StringBuffer sb = new StringBuffer(" setProperty("); sb.append(bean); sb.append(", "); sb.append(name); sb.append(", "); if (value == null) { sb.append("<NULL>"); } else if (value instanceof String) { sb.append((String) value); } else if (value instanceof String[]) { String[] values = (String[]) value; sb.append('['); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(','); } sb.append(values[i]); } sb.append(']'); } else { sb.append(value.toString()); } sb.append(')'); log.trace(sb.toString()); } // Resolve any nested expression to get the actual target bean Object target = bean; Resolver resolver = getPropertyUtils().getResolver(); while (resolver.hasNested(name)) { try { target = getPropertyUtils().getProperty(target, resolver.next(name)); name = resolver.remove(name); } catch (NoSuchMethodException e) { return; // Skip this property setter } } if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + name); } // Declare local variables we will require String propName = resolver.getProperty(name); // Simple name of target property Class type = null; // Java type of target property int index = resolver.getIndex(name); // Indexed subscript value (if any) String key = resolver.getKey(name); // Mapped key value (if any) // Calculate the property type if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; // Skip this property setter } type = dynaProperty.getType(); } else if (target instanceof Map) { type = Object.class; } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, name); if (descriptor == null) { return; // Skip this property setter } } catch (NoSuchMethodException e) { return; // Skip this property setter } if (descriptor instanceof MappedPropertyDescriptor) { if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((MappedPropertyDescriptor) descriptor). getMappedPropertyType(); } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) { if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = ((IndexedPropertyDescriptor) descriptor). getIndexedPropertyType(); } else if (key != null) { if (descriptor.getReadMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = (value == null) ? Object.class : value.getClass(); } else { if (descriptor.getWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } return; // Read-only, skip this property setter } type = descriptor.getPropertyType(); } } // Convert the specified value to the required type Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value == null) { String[] values = new String[1]; values[0] = (String) value; newValue = getConvertUtils().convert((String[]) values, type); } else if (value instanceof String) { newValue = getConvertUtils().convert(value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert((String[]) value, type); } else { newValue = convert(value, type); } } else if (type.isArray()) { // Indexed value into array if (value instanceof String || value == null) { newValue = getConvertUtils().convert((String) value, type.getComponentType()); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType()); } else { newValue = convert(value, type.getComponentType()); } } else { // Value into scalar if ((value instanceof String) || (value == null)) { newValue = getConvertUtils().convert((String) value, type); } else if (value instanceof String[]) { newValue = getConvertUtils().convert(((String[]) value)[0], type); } else { newValue = convert(value, type); } } // Invoke the setter method try { getPropertyUtils().setProperty(target, name, newValue); } catch (NoSuchMethodException e) { throw new InvocationTargetException (e, "Cannot set " + propName); } } /** * Gets the <code>ConvertUtilsBean</code> instance used to perform the conversions. * * @return The ConvertUtils bean instance */ public ConvertUtilsBean getConvertUtils() { return convertUtilsBean; } /** * Gets the <code>PropertyUtilsBean</code> instance used to access properties. * * @return The ConvertUtils bean instance */ public PropertyUtilsBean getPropertyUtils() { return propertyUtilsBean; } /** * If we're running on JDK 1.4 or later, initialize the cause for the given throwable. * * @param throwable The throwable. * @param cause The cause of the throwable. * @return true if the cause was initialized, otherwise false. */ public boolean initCause(Throwable throwable, Throwable cause) { if (INIT_CAUSE_METHOD != null && cause != null) { try { INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause }); return true; } catch (Throwable e) { return false; // can't initialize cause } } return false; } /** * <p>Convert the value to an object of the specified class (if * possible).</p> * * @param value Value to be converted (may be null) * @param type Class of the value to be converted to * @return The converted value * * @exception ConversionException if thrown by an underlying Converter */ protected Object convert(Object value, Class type) { Converter converter = getConvertUtils().lookup(type); if (converter != null) { log.trace(" USING CONVERTER " + converter); return converter.convert(type, value); } else { return value; } } /** * Returns a <code>Method<code> allowing access to * {@link Throwable#initCause(Throwable)} method of {@link Throwable}, * or <code>null</code> if the method * does not exist. * * @return A <code>Method<code> for <code>Throwable.initCause</code>, or * <code>null</code> if unavailable. */ private static Method getInitCauseMethod() { try { Class[] paramsClasses = new Class[] { Throwable.class }; return Throwable.class.getMethod("initCause", paramsClasses); } catch (NoSuchMethodException e) { Log log = LogFactory.getLog(BeanUtils.class); if (log.isWarnEnabled()) { log.warn("Throwable does not have initCause() method in JDK 1.3"); } return null; } catch (Throwable e) { Log log = LogFactory.getLog(BeanUtils.class); if (log.isWarnEnabled()) { log.warn("Error getting the Throwable initCause() method", e); } return null; } } }

The table below shows all metrics for BeanUtilsBean.java.

MetricValueDescription
BLOCKS148.00Number of blocks
BLOCK_COMMENT16.00Number of block comment lines
COMMENTS477.00Comment lines
COMMENT_DENSITY 1.12Comment density
COMPARISONS75.00Number of comparison operators
CYCLOMATIC129.00Cyclomatic complexity
DECL_COMMENTS36.00Comments in declarations
DOC_COMMENT429.00Number of javadoc comment lines
ELOC426.00Effective lines of code
EXEC_COMMENTS24.00Comments in executable code
EXITS91.00Procedure exits
FUNCTIONS25.00Number of function declarations
HALSTEAD_DIFFICULTY93.28Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY159.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA0034 0.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 0.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 1.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 0.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 0.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 0.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 0.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 0.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 0.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 1.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA0145 0.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 2.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 2.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 0.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 3.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 4.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES1107.00Number of lines in the source file
LINE_COMMENT32.00Number of line comments
LOC530.00Lines of code
LOGICAL_LINES236.00Number of statements
LOOPS12.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS1201.00Number of operands
OPERATORS2449.00Number of operators
PARAMS38.00Number of formal parameter declarations
PROGRAM_LENGTH3650.00Halstead program length
PROGRAM_VOCAB357.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS121.00Number of return points from functions
SIZE45468.00Size of the file in bytes
UNIQUE_OPERANDS309.00Number of unique operands
UNIQUE_OPERATORS48.00Number of unique operators
WHITESPACE100.00Number of whitespace lines