LazyDynaMap.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.util.Map;
  19. import java.util.Objects;

  20. /**
  21.  * <p>
  22.  * Provides a <em>light weight</em> {@code DynaBean</code> facade to a <code>Map}
  23.  *  with <em>lazy</em> map/list processing.</p>
  24.  *
  25.  * <p>Its a <em>light weight</em> {@code DynaBean} implementation because there is no
  26.  *    actual {@code DynaClass</code> associated with this <code>DynaBean} - in fact
  27.  *    it implements the {@code DynaClass} interface itself providing <em>pseudo</em> DynaClass
  28.  *    behavior from the actual values stored in the {@code Map}.</p>
  29.  *
  30.  * <p>As well providing rhe standard {@code DynaBean</code> access to the <code>Map}'s properties
  31.  *    this class also provides the usual <em>Lazy</em> behavior:</p>
  32.  *    <ul>
  33.  *       <li>Properties don't need to be pre-defined in a {@code DynaClass}</li>
  34.  *       <li>Indexed properties ({@code Lists</code> or <code>Arrays}) are automatically instantiated
  35.  *           and <em>grown</em> so that they are large enough to cater for the index being set.</li>
  36.  *       <li>Mapped properties are automatically instantiated.</li>
  37.  *    </ul>
  38.  *
  39.  * <p><strong><u><em>Restricted</em> DynaClass</u></strong></p>
  40.  *    <p>This class implements the {@code MutableDynaClass} interface.
  41.  *       {@code MutableDynaClass</code> have a facility to <em>restrict</em> the <code>DynaClass} so that its properties cannot be modified. If the
  42.  * {@code MutableDynaClass} is restricted then calling any of the {@code set()} methods for a property which doesn't exist will result in a
  43.  * {@code IllegalArgumentException} being thrown.
  44.  * </p>
  45.  */
  46. public class LazyDynaMap extends LazyDynaBean implements MutableDynaClass {

  47.     private static final long serialVersionUID = 1L;

  48.     /**
  49.      * The name of this DynaClass (analogous to the {@code getName()</code> method of <code>java.lang.Class}).
  50.      */
  51.     protected String name;

  52.     /**
  53.      * Controls whether changes to this DynaClass's properties are allowed.
  54.      */
  55.     protected boolean restricted;

  56.     /**
  57.      * <p>
  58.      * Controls whether the {@code getDynaProperty()} method returns null if a property doesn't exist - or creates a new one.
  59.      * </p>
  60.      *
  61.      * <p>
  62.      * Default is {@code false}.
  63.      */
  64.     protected boolean returnNull;

  65.     /**
  66.      * Constructs a new instance.
  67.      */
  68.     public LazyDynaMap() {
  69.         this(null, (Map<String, Object>) null);
  70.     }

  71.     /**
  72.      * Constructs a new {@code LazyDynaMap} based on an exisiting DynaClass
  73.      *
  74.      * @param dynaClass DynaClass to copy the name and properties from
  75.      */
  76.     public LazyDynaMap(final DynaClass dynaClass) {
  77.         this(dynaClass.getName(), dynaClass.getDynaProperties());
  78.     }

  79.     /**
  80.      * Constructs a new {@code LazyDynaMap} with the specified properties.
  81.      *
  82.      * @param properties Property descriptors for the supported properties
  83.      */
  84.     public LazyDynaMap(final DynaProperty[] properties) {
  85.         this(null, properties);
  86.     }

  87.     /**
  88.      * Constructs a new {@code LazyDynaMap</code> with the specified <code>Map}.
  89.      *
  90.      * @param values The Map backing this {@code LazyDynaMap}
  91.      */
  92.     public LazyDynaMap(final Map<String, Object> values) {
  93.         this(null, values);
  94.     }

  95.     /**
  96.      * Constructs a new {@code LazyDynaMap} with the specified name.
  97.      *
  98.      * @param name Name of this DynaBean class
  99.      */
  100.     public LazyDynaMap(final String name) {
  101.         this(name, (Map<String, Object>) null);
  102.     }

  103.     /**
  104.      * Constructs a new {@code LazyDynaMap} with the specified name and properties.
  105.      *
  106.      * @param name       Name of this DynaBean class
  107.      * @param properties Property descriptors for the supported properties
  108.      */
  109.     public LazyDynaMap(final String name, final DynaProperty[] properties) {
  110.         this(name, (Map<String, Object>) null);
  111.         if (properties != null) {
  112.             for (final DynaProperty property : properties) {
  113.                 add(property);
  114.             }
  115.         }
  116.     }

  117.     /**
  118.      * Constructs a new {@code LazyDynaMap</code> with the specified name and  <code>Map}.
  119.      *
  120.      * @param name   Name of this DynaBean class
  121.      * @param values The Map backing this {@code LazyDynaMap}
  122.      */
  123.     public LazyDynaMap(final String name, final Map<String, Object> values) {
  124.         this.name = name == null ? "LazyDynaMap" : name;
  125.         this.values = values == null ? newMap() : values;
  126.         this.dynaClass = this;
  127.     }

  128.     /**
  129.      * Add a new dynamic property.
  130.      *
  131.      * @param property Property the new dynamic property to add.
  132.      * @throws IllegalArgumentException if name is null
  133.      */
  134.     protected void add(final DynaProperty property) {
  135.         add(property.getName(), property.getType());
  136.     }

  137.     /**
  138.      * Add a new dynamic property with no restrictions on data type, readability, or writeability.
  139.      *
  140.      * @param name Name of the new dynamic property
  141.      * @throws IllegalArgumentException if name is null
  142.      */
  143.     @Override
  144.     public void add(final String name) {
  145.         add(name, null);
  146.     }

  147.     /**
  148.      * Add a new dynamic property with the specified data type, but with no restrictions on readability or writeability.
  149.      *
  150.      * @param name Name of the new dynamic property
  151.      * @param type Data type of the new dynamic property (null for no restrictions)
  152.      * @throws IllegalArgumentException if name is null
  153.      * @throws IllegalStateException    if this DynaClass is currently restricted, so no new properties can be added
  154.      */
  155.     @Override
  156.     public void add(final String name, final Class<?> type) {
  157.         Objects.requireNonNull(name, "name");
  158.         if (isRestricted()) {
  159.             throw new IllegalStateException("DynaClass is currently restricted. No new properties can be added.");
  160.         }
  161.         // Check if the property already exists
  162.         values.computeIfAbsent(name, k -> type == null ? null : createProperty(name, type));
  163.     }

  164.     /**
  165.      * <p>
  166.      * Add a new dynamic property with the specified data type, readability, and writeability.
  167.      * </p>
  168.      *
  169.      * <p>
  170.      * <strong>N.B.</strong>Support for readable/writable properties has not been implemented and this method always throws a
  171.      * {@code UnsupportedOperationException}.
  172.      * </p>
  173.      *
  174.      * <p>
  175.      * I'm not sure the intention of the original authors for this method, but it seems to me that readable/writable should be attributes of the
  176.      * {@code DynaProperty} class (which they are not) and is the reason this method has not been implemented.
  177.      * </p>
  178.      *
  179.      * @param name     Name of the new dynamic property
  180.      * @param type     Data type of the new dynamic property (null for no restrictions)
  181.      * @param readable Set to {@code true} if this property value should be readable
  182.      * @param writable Set to {@code true} if this property value should be writable
  183.      * @throws UnsupportedOperationException anytime this method is called
  184.      */
  185.     @Override
  186.     public void add(final String name, final Class<?> type, final boolean readable, final boolean writable) {
  187.         throw new java.lang.UnsupportedOperationException("readable/writable properties not supported");
  188.     }

  189.     /**
  190.      * <p>
  191.      * Return an array of {@code PropertyDescriptor} for the properties currently defined in this DynaClass. If no properties are defined, a zero-length array
  192.      * will be returned.
  193.      * </p>
  194.      *
  195.      * <p>
  196.      * <strong>FIXME</strong> - Should we really be implementing {@code getBeanInfo()} instead, which returns property descriptors and a bunch of other stuff?
  197.      * </p>
  198.      *
  199.      * @return the set of properties for this DynaClass
  200.      */
  201.     @Override
  202.     public DynaProperty[] getDynaProperties() {
  203.         int i = 0;
  204.         final DynaProperty[] properties = new DynaProperty[values.size()];
  205.         for (final Map.Entry<String, Object> e : values.entrySet()) {
  206.             final String name = e.getKey();
  207.             final Object value = values.get(name);
  208.             properties[i++] = new DynaProperty(name, value == null ? null : value.getClass());
  209.         }

  210.         return properties;
  211.     }

  212.     /**
  213.      * <p>
  214.      * Return a property descriptor for the specified property.
  215.      * </p>
  216.      *
  217.      * <p>
  218.      * If the property is not found and the {@code returnNull} indicator is {@code true</code>, this method always returns <code>null}.
  219.      * </p>
  220.      *
  221.      * <p>
  222.      * If the property is not found and the {@code returnNull} indicator is {@code false} a new property descriptor is created and returned (although its not
  223.      * actually added to the DynaClass's properties). This is the default behavior.
  224.      * </p>
  225.      *
  226.      * <p>
  227.      * The reason for not returning a {@code null} property descriptor is that {@code BeanUtils} uses this method to check if a property exists before trying to
  228.      * set it - since these <em>Map</em> implementations automatically add any new properties when they are set, returning {@code null} from this method would
  229.      * defeat their purpose.
  230.      * </p>
  231.      *
  232.      * @param name Name of the dynamic property for which a descriptor is requested
  233.      * @return The descriptor for the specified property
  234.      * @throws IllegalArgumentException if no property name is specified
  235.      */
  236.     @Override
  237.     public DynaProperty getDynaProperty(final String name) {
  238.         Objects.requireNonNull(name, "name");
  239.         final Object value = values.get(name);
  240.         // If it doesn't exist and returnNull is false
  241.         // create a new DynaProperty
  242.         if (value == null && isReturnNull()) {
  243.             return null;
  244.         }
  245.         if (value == null) {
  246.             return new DynaProperty(name);
  247.         }
  248.         return new DynaProperty(name, value.getClass());
  249.     }

  250.     /**
  251.      * Gets the underlying Map backing this {@code DynaBean}
  252.      *
  253.      * @return the underlying Map
  254.      * @since 1.8.0
  255.      */
  256.     @Override
  257.     public Map<String, Object> getMap() {
  258.         return values;
  259.     }

  260.     /**
  261.      * Gets the name of this DynaClass (analogous to the {@code getName()</code> method of <code>java.lang.Class})
  262.      *
  263.      * @return the name of the DynaClass
  264.      */
  265.     @Override
  266.     public String getName() {
  267.         return this.name;
  268.     }

  269.     /**
  270.      * <p>
  271.      * Indicate whether a property actually exists.
  272.      * </p>
  273.      *
  274.      * <p>
  275.      * <strong>N.B.</strong> Using {@code getDynaProperty(name) == null} doesn't work in this implementation because that method might return a DynaProperty if
  276.      * it doesn't exist (depending on the {@code returnNull} indicator).
  277.      * </p>
  278.      *
  279.      * @param name Name of the dynamic property
  280.      * @return {@code true} if the property exists, otherwise {@code false}
  281.      * @throws IllegalArgumentException if no property name is specified
  282.      */
  283.     @Override
  284.     protected boolean isDynaProperty(final String name) {
  285.         return values.containsKey(Objects.requireNonNull(name, "name"));
  286.     }

  287.     /**
  288.      * <p>
  289.      * Is this DynaClass currently restricted.
  290.      * </p>
  291.      * <p>
  292.      * If restricted, no changes to the existing registration of property names, data types, readability, or writeability are allowed.
  293.      * </p>
  294.      *
  295.      * @return {@code true} if this Mutable {@link DynaClass} is restricted, otherwise {@code false}
  296.      */
  297.     @Override
  298.     public boolean isRestricted() {
  299.         return restricted;
  300.     }

  301.     /**
  302.      * Should this DynaClass return a {@code null} from the {@code getDynaProperty(name)} method if the property doesn't exist.
  303.      *
  304.      * @return {@code true</code> if a <code>null} {@link DynaProperty} should be returned if the property doesn't exist, otherwise {@code false} if a new
  305.      *         {@link DynaProperty} should be created.
  306.      */
  307.     public boolean isReturnNull() {
  308.         return returnNull;
  309.     }

  310.     /**
  311.      * Instantiate and return a new DynaBean instance, associated with this DynaClass.
  312.      *
  313.      * @return A new {@code DynaBean} instance
  314.      */
  315.     @Override
  316.     public DynaBean newInstance() {
  317.         // Create a new instance of the Map
  318.         Map<String, Object> newMap = null;
  319.         try {
  320.             final
  321.             // The new map is used as properties map
  322.             Map<String, Object> temp = getMap().getClass().newInstance();
  323.             newMap = temp;
  324.         } catch (final Exception ex) {
  325.             newMap = newMap();
  326.         }

  327.         // Crate new LazyDynaMap and initialize properties
  328.         final LazyDynaMap lazyMap = new LazyDynaMap(newMap);
  329.         final DynaProperty[] properties = getDynaProperties();
  330.         if (properties != null) {
  331.             for (final DynaProperty property : properties) {
  332.                 lazyMap.add(property);
  333.             }
  334.         }
  335.         return lazyMap;
  336.     }

  337.     /**
  338.      * Remove the specified dynamic property, and any associated data type, readability, and writeability, from this dynamic class. <strong>NOTE</strong> - This
  339.      * does <strong>NOT</strong> cause any corresponding property values to be removed from DynaBean instances associated with this DynaClass.
  340.      *
  341.      * @param name Name of the dynamic property to remove
  342.      * @throws IllegalArgumentException if name is null
  343.      * @throws IllegalStateException    if this DynaClass is currently restricted, so no properties can be removed
  344.      */
  345.     @Override
  346.     public void remove(final String name) {
  347.         Objects.requireNonNull(name, "name");
  348.         if (isRestricted()) {
  349.             throw new IllegalStateException("DynaClass is currently restricted. No properties can be removed.");
  350.         }
  351.         values.remove(name);
  352.     }

  353.     /**
  354.      * Sets the value of a simple property with the specified name.
  355.      *
  356.      * @param name  Name of the property whose value is to be set
  357.      * @param value Value to which this property is to be set
  358.      */
  359.     @Override
  360.     public void set(final String name, final Object value) {
  361.         if (isRestricted() && !values.containsKey(name)) {
  362.             throw new IllegalArgumentException("Invalid property name '" + name + "' (DynaClass is restricted)");
  363.         }
  364.         values.put(name, value);
  365.     }

  366.     /**
  367.      * Sets the Map backing this {@code DynaBean}
  368.      *
  369.      * @param values The new Map of values
  370.      */
  371.     public void setMap(final Map<String, Object> values) {
  372.         this.values = values;
  373.     }

  374.     /**
  375.      * <p>
  376.      * Set whether this DynaClass is currently restricted.
  377.      * </p>
  378.      * <p>
  379.      * If restricted, no changes to the existing registration of property names, data types, readability, or writeability are allowed.
  380.      * </p>
  381.      *
  382.      * @param restricted The new restricted state
  383.      */
  384.     @Override
  385.     public void setRestricted(final boolean restricted) {
  386.         this.restricted = restricted;
  387.     }

  388.     /**
  389.      * Sets whether this DynaClass should return a {@code null} from the {@code getDynaProperty(name)} method if the property doesn't exist.
  390.      *
  391.      * @param returnNull {@code true</code> if a <code>null} {@link DynaProperty} should be returned if the property doesn't exist, otherwise {@code false} if a
  392.      *                   new {@link DynaProperty} should be created.
  393.      */
  394.     public void setReturnNull(final boolean returnNull) {
  395.         this.returnNull = returnNull;
  396.     }

  397. }