BasicDynaBean.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.beanutils2;

  18. import java.lang.reflect.Array;
  19. import java.util.HashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Objects;

  23. /**
  24.  * <p>
  25.  * Minimal implementation of the {@code DynaBean} interface. Can be used as a convenience base class for more sophisticated implementations.
  26.  * </p>
  27.  *
  28.  * <p>
  29.  * <strong>IMPLEMENTATION NOTE</strong> - Instances of this class that are accessed from multiple threads simultaneously need to be synchronized.
  30.  * </p>
  31.  *
  32.  * <p>
  33.  * <strong>IMPLEMENTATION NOTE</strong> - Instances of this class can be successfully serialized and deserialized <strong>ONLY</strong> if all property values
  34.  * are {@code Serializable}.
  35.  * </p>
  36.  */
  37. public class BasicDynaBean implements DynaBean {

  38.     private static final Short SHORT_ZERO = Short.valueOf((short) 0);

  39.     private static final Long LONG_ZERO = Long.valueOf(0);

  40.     private static final Integer INTEGER_ZERO = Integer.valueOf(0);

  41.     private static final Float FLOAT_ZERO = Float.valueOf((float) 0.0);

  42.     private static final Double DOUBLE_ZERO = Double.valueOf(0.0);

  43.     private static final Character CHARACTER_ZERO = Character.valueOf((char) 0);

  44.     private static final Byte BYTE_ZERO = Byte.valueOf((byte) 0);

  45.     private static final long serialVersionUID = 1L;

  46.     /**
  47.      * The {@code DynaClass} "base class" that this DynaBean is associated with.
  48.      */
  49.     protected DynaClass dynaClass;

  50.     /**
  51.      * The set of property values for this DynaBean, keyed by property name.
  52.      */
  53.     protected HashMap<String, Object> values = new HashMap<>();

  54.     /** Map decorator for this DynaBean */
  55.     private transient Map<String, Object> mapDecorator;

  56.     /**
  57.      * Constructs a new {@code DynaBean} associated with the specified {@code DynaClass} instance.
  58.      *
  59.      * @param dynaClass The DynaClass we are associated with
  60.      */
  61.     public BasicDynaBean(final DynaClass dynaClass) {
  62.         this.dynaClass = dynaClass;
  63.     }

  64.     /**
  65.      * Does the specified mapped property contain a value for the specified key value?
  66.      *
  67.      * @param name Name of the property to check
  68.      * @param key  Name of the key to check
  69.      * @return {@code true} if the mapped property contains a value for the specified key, otherwise {@code false}
  70.      * @throws IllegalArgumentException if there is no property of the specified name
  71.      */
  72.     @Override
  73.     public boolean contains(final String name, final String key) {
  74.         final Object value = values.get(name);
  75.         requireMappedValue(name, key, value);
  76.         if (value instanceof Map) {
  77.             return ((Map<?, ?>) value).containsKey(key);
  78.         }
  79.         throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
  80.     }

  81.     /**
  82.      * Gets the value of a simple property with the specified name.
  83.      *
  84.      * @param name Name of the property whose value is to be retrieved
  85.      * @return The property's value
  86.      * @throws IllegalArgumentException if there is no property of the specified name
  87.      */
  88.     @Override
  89.     public Object get(final String name) {
  90.         // Return any non-null value for the specified property
  91.         final Object value = values.get(name);
  92.         if (value != null) {
  93.             return value;
  94.         }
  95.         // Return a null value for a non-primitive property
  96.         final Class<?> type = getDynaProperty(name).getType();
  97.         if (!type.isPrimitive()) {
  98.             return value;
  99.         }
  100.         // Manufacture default values for primitive properties
  101.         if (type == Boolean.TYPE) {
  102.             return Boolean.FALSE;
  103.         }
  104.         if (type == Byte.TYPE) {
  105.             return BYTE_ZERO;
  106.         }
  107.         if (type == Character.TYPE) {
  108.             return CHARACTER_ZERO;
  109.         }
  110.         if (type == Double.TYPE) {
  111.             return DOUBLE_ZERO;
  112.         }
  113.         if (type == Float.TYPE) {
  114.             return FLOAT_ZERO;
  115.         }
  116.         if (type == Integer.TYPE) {
  117.             return INTEGER_ZERO;
  118.         }
  119.         if (type == Long.TYPE) {
  120.             return LONG_ZERO;
  121.         }
  122.         if (type == Short.TYPE) {
  123.             return SHORT_ZERO;
  124.         }
  125.         return null;
  126.     }

  127.     /**
  128.      * Gets the value of an indexed property with the specified name.
  129.      *
  130.      * @param name  Name of the property whose value is to be retrieved
  131.      * @param index Index of the value to be retrieved
  132.      * @return The indexed property's value
  133.      * @throws IllegalArgumentException  if there is no property of the specified name
  134.      * @throws IllegalArgumentException  if the specified property exists, but is not indexed
  135.      * @throws IndexOutOfBoundsException if the specified index is outside the range of the underlying property
  136.      * @throws NullPointerException      if no array or List has been initialized for this property
  137.      */
  138.     @Override
  139.     public Object get(final String name, final int index) {
  140.         final Object value = values.get(name);
  141.         Objects.requireNonNull(value, "No indexed value for '" + name + "[" + index + "]'");
  142.         if (value.getClass().isArray()) {
  143.             return Array.get(value, index);
  144.         }
  145.         if (value instanceof List) {
  146.             return ((List<?>) value).get(index);
  147.         }
  148.         throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
  149.     }

  150.     /**
  151.      * Gets the value of a mapped property with the specified name, or {@code null} if there is no value for the specified key.
  152.      *
  153.      * @param name Name of the property whose value is to be retrieved
  154.      * @param key  Key of the value to be retrieved
  155.      * @return The mapped property's value
  156.      * @throws IllegalArgumentException if there is no property of the specified name
  157.      * @throws IllegalArgumentException if the specified property exists, but is not mapped
  158.      */
  159.     @Override
  160.     public Object get(final String name, final String key) {
  161.         final Object value = values.get(name);
  162.         requireMappedValue(name, key, value);
  163.         if (value instanceof Map) {
  164.             return ((Map<?, ?>) value).get(key);
  165.         }
  166.         throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");

  167.     }

  168.     /**
  169.      * Gets the {@code DynaClass} instance that describes the set of properties available for this DynaBean.
  170.      *
  171.      * @return The associated DynaClass
  172.      */
  173.     @Override
  174.     public DynaClass getDynaClass() {
  175.         return this.dynaClass;
  176.     }

  177.     /**
  178.      * Gets the property descriptor for the specified property name.
  179.      *
  180.      * @param name Name of the property for which to retrieve the descriptor
  181.      * @return The property descriptor
  182.      * @throws IllegalArgumentException if this is not a valid property name for our DynaClass
  183.      */
  184.     protected DynaProperty getDynaProperty(final String name) {
  185.         final DynaProperty descriptor = getDynaClass().getDynaProperty(name);
  186.         if (descriptor == null) {
  187.             throw new IllegalArgumentException("Invalid property name '" + name + "'");
  188.         }
  189.         return descriptor;

  190.     }

  191.     /**
  192.      * <p>
  193.      * Gets a Map representation of this DynaBean.
  194.      * <p>
  195.      * This, for example, could be used in JSTL in the following way to access a DynaBean's {@code fooProperty}:
  196.      * <ul>
  197.      * <li>{@code ${myDynaBean.<strong>map</strong>.fooProperty}}</li>
  198.      * </ul>
  199.      *
  200.      * @return a Map representation of this DynaBean
  201.      * @since 1.8.0
  202.      */
  203.     public Map<String, Object> getMap() {
  204.         // cache the Map
  205.         if (mapDecorator == null) {
  206.             mapDecorator = new DynaBeanPropertyMapDecorator(this);
  207.         }
  208.         return mapDecorator;

  209.     }

  210.     /**
  211.      * Is an object of the source class assignable to the destination class?
  212.      *
  213.      * @param dest   Destination class
  214.      * @param source Source class
  215.      * @return {@code true} if the source class is assignable to the destination class, otherwise {@code false}
  216.      */
  217.     protected boolean isAssignable(final Class<?> dest, final Class<?> source) {
  218.         // @formatter:off
  219.         return dest.isAssignableFrom(source) ||
  220.                dest == Boolean.TYPE && source == Boolean.class ||
  221.                dest == Byte.TYPE && source == Byte.class ||
  222.                dest == Character.TYPE && source == Character.class ||
  223.                dest == Double.TYPE && source == Double.class ||
  224.                dest == Float.TYPE && source == Float.class ||
  225.                dest == Integer.TYPE && source == Integer.class ||
  226.                dest == Long.TYPE && source == Long.class ||
  227.                dest == Short.TYPE && source == Short.class;
  228.         // @formatter:on
  229.     }

  230.     /**
  231.      * Remove any existing value for the specified key on the specified mapped property.
  232.      *
  233.      * @param name Name of the property for which a value is to be removed
  234.      * @param key  Key of the value to be removed
  235.      * @throws IllegalArgumentException if there is no property of the specified name
  236.      */
  237.     @Override
  238.     public void remove(final String name, final String key) {
  239.         final Object value = values.get(name);
  240.         requireMappedValue(name, key, value);
  241.         if (!(value instanceof Map)) {
  242.             throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
  243.         }
  244.         ((Map<?, ?>) value).remove(key);
  245.     }

  246.     private void requireMappedValue(final String name, final String key, final Object value) {
  247.         Objects.requireNonNull(value, () -> "No mapped value for '" + name + "(" + key + ")'");
  248.     }

  249.     /**
  250.      * Sets the value of an indexed property with the specified name.
  251.      *
  252.      * @param name  Name of the property whose value is to be set
  253.      * @param index Index of the property to be set
  254.      * @param value Value to which this property is to be set
  255.      * @throws ConversionException       if the specified value cannot be converted to the type required for this property
  256.      * @throws IllegalArgumentException  if there is no property of the specified name
  257.      * @throws IllegalArgumentException  if the specified property exists, but is not indexed
  258.      * @throws IndexOutOfBoundsException if the specified index is outside the range of the underlying property
  259.      */
  260.     @Override
  261.     public void set(final String name, final int index, final Object value) {
  262.         final Object prop = values.get(name);
  263.         Objects.requireNonNull(prop, "No indexed value for '" + name + "[" + index + "]'");
  264.         if (prop.getClass().isArray()) {
  265.             Array.set(prop, index, value);
  266.         } else if (prop instanceof List) {
  267.             try {
  268.                 @SuppressWarnings("unchecked")
  269.                 // This is safe to cast because list properties are always
  270.                 // of type Object
  271.                 final List<Object> list = (List<Object>) prop;
  272.                 list.set(index, value);
  273.             } catch (final ClassCastException e) {
  274.                 throw new ConversionException(e.getMessage());
  275.             }
  276.         } else {
  277.             throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
  278.         }
  279.     }

  280.     /**
  281.      * Sets the value of a simple property with the specified name.
  282.      *
  283.      * @param name  Name of the property whose value is to be set
  284.      * @param value Value to which this property is to be set
  285.      * @throws ConversionException      if the specified value cannot be converted to the type required for this property
  286.      * @throws IllegalArgumentException if there is no property of the specified name
  287.      * @throws NullPointerException     if an attempt is made to set a primitive property to null
  288.      */
  289.     @Override
  290.     public void set(final String name, final Object value) {
  291.         final DynaProperty descriptor = getDynaProperty(name);
  292.         if (value == null) {
  293.             if (descriptor.getType().isPrimitive()) {
  294.                 throw new NullPointerException("Primitive value for '" + name + "'");
  295.             }
  296.         } else if (!isAssignable(descriptor.getType(), value.getClass())) {
  297.             throw ConversionException.format("Cannot assign value of type '%s' to property '%s' of type '%s'", value.getClass().getName(), name,
  298.                     descriptor.getType().getName());
  299.         }
  300.         values.put(name, value);
  301.     }

  302.     /**
  303.      * Sets the value of a mapped property with the specified name.
  304.      *
  305.      * @param name  Name of the property whose value is to be set
  306.      * @param key   Key of the property to be set
  307.      * @param value Value to which this property is to be set
  308.      * @throws ConversionException      if the specified value cannot be converted to the type required for this property
  309.      * @throws IllegalArgumentException if there is no property of the specified name
  310.      * @throws IllegalArgumentException if the specified property exists, but is not mapped
  311.      */
  312.     @SuppressWarnings("unchecked")
  313.     @Override
  314.     public void set(final String name, final String key, final Object value) {
  315.         final Object prop = values.get(name);
  316.         requireMappedValue(name, key, prop);
  317.         if (!(prop instanceof Map)) {
  318.             throw new IllegalArgumentException("Non-mapped property for '" + name + "(" + key + ")'");
  319.         }
  320.         // This is safe to cast because mapped properties are always
  321.         // maps of types String -> Object
  322.         ((Map<String, Object>) prop).put(key, value);
  323.     }

  324. }