001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.beanutils;
019
020import java.lang.reflect.InvocationTargetException;
021
022import org.apache.commons.collections.Transformer;
023import org.apache.commons.logging.Log;
024import org.apache.commons.logging.LogFactory;
025
026/**
027 * <p><code>Transformer</code> that outputs a property value.</p>
028 *
029 * <p>An implementation of <code>org.apache.commons.collections.Transformer</code> that transforms
030 * the object provided by returning the value of a specified property of the object.  The
031 * constructor for <code>BeanToPropertyValueTransformer</code> requires the name of the property
032 * that will be used in the transformation.  The property can be a simple, nested, indexed, or
033 * mapped property as defined by <code>org.apache.commons.beanutils.PropertyUtils</code>. If any
034 * object in the property path specified by <code>propertyName</code> is <code>null</code> then the
035 * outcome is based on the value of the <code>ignoreNull</code> attribute.
036 * </p>
037 * <p>
038 * A typical usage might look like:
039 * </p>
040 * <pre>
041 * // create the transformer
042 * BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer( "person.address.city" );
043 *
044 * // transform the Collection
045 * Collection peoplesCities = CollectionUtils.collect( peopleCollection, transformer );
046 * </pre>
047 * <p>
048 * This would take a <code>Collection</code> of person objects and return a <code>Collection</code>
049 * of objects which represents the cities in which each person lived. Assuming...
050 * </p>
051 * <ul>
052 *    <li>
053 *       The top level object in the <code>peeopleCollection</code> is an object which represents a
054 *       person.
055 *    </li>
056 *    <li>
057 *       The person object has a <code>getAddress()</code> method which returns an object which
058 *       represents a person's address.
059 *    </li>
060 *    <li>
061 *       The address object has a <code>getCity()</code> method which returns an object which
062 *       represents the city in which a person lives.
063 *    </li>
064 * </ul>
065 *
066 * @see org.apache.commons.beanutils.PropertyUtils
067 * @see org.apache.commons.collections.Transformer
068 */
069public class BeanToPropertyValueTransformer implements Transformer {
070
071    /** For logging. */
072    private final Log log = LogFactory.getLog(this.getClass());
073
074    /** The name of the property that will be used in the transformation of the object. */
075    private final String propertyName;
076
077    /**
078     * <p>Should null objects on the property path throw an <code>IllegalArgumentException</code>?</p>
079     * <p>
080     * Determines whether <code>null</code> objects in the property path will genenerate an
081     * <code>IllegalArgumentException</code> or not. If set to <code>true</code> then if any objects
082     * in the property path evaluate to <code>null</code> then the
083     * <code>IllegalArgumentException</code> throw by <code>PropertyUtils</code> will be logged but
084     * not rethrown and <code>null</code> will be returned.  If set to <code>false</code> then if any
085     * objects in the property path evaluate to <code>null</code> then the
086     * <code>IllegalArgumentException</code> throw by <code>PropertyUtils</code> will be logged and
087     * rethrown.
088     * </p>
089     */
090    private final boolean ignoreNull;
091
092    /**
093     * Constructs a Transformer which does not ignore nulls.
094     * Constructor which takes the name of the property that will be used in the transformation and
095     * assumes <code>ignoreNull</code> to be <code>false</code>.
096     *
097     * @param propertyName The name of the property that will be used in the transformation.
098     * @throws IllegalArgumentException If the <code>propertyName</code> is <code>null</code> or
099     * empty.
100     */
101    public BeanToPropertyValueTransformer(final String propertyName) {
102        this(propertyName, false);
103    }
104
105    /**
106     * Constructs a Transformer and sets ignoreNull.
107     * Constructor which takes the name of the property that will be used in the transformation and
108     * a boolean which determines whether <code>null</code> objects in the property path will
109     * genenerate an <code>IllegalArgumentException</code> or not.
110     *
111     * @param propertyName The name of the property that will be used in the transformation.
112     * @param ignoreNull Determines whether <code>null</code> objects in the property path will
113     * genenerate an <code>IllegalArgumentException</code> or not.
114     * @throws IllegalArgumentException If the <code>propertyName</code> is <code>null</code> or
115     * empty.
116     */
117    public BeanToPropertyValueTransformer(final String propertyName, final boolean ignoreNull) {
118        if (propertyName == null || propertyName.length() <= 0) {
119            throw new IllegalArgumentException(
120                "propertyName cannot be null or empty");
121        }
122        this.propertyName = propertyName;
123        this.ignoreNull = ignoreNull;
124    }
125
126    /**
127     * Returns the name of the property that will be used in the transformation of the bean.
128     *
129     * @return The name of the property that will be used in the transformation of the bean.
130     */
131    public String getPropertyName() {
132        return propertyName;
133    }
134
135    /**
136     * Returns the flag which determines whether <code>null</code> objects in the property path will
137     * genenerate an <code>IllegalArgumentException</code> or not. If set to <code>true</code> then
138     * if any objects in the property path evaluate to <code>null</code> then the
139     * <code>IllegalArgumentException</code> throw by <code>PropertyUtils</code> will be logged but
140     * not rethrown and <code>null</code> will be returned.  If set to <code>false</code> then if any
141     * objects in the property path evaluate to <code>null</code> then the
142     * <code>IllegalArgumentException</code> throw by <code>PropertyUtils</code> will be logged and
143     * rethrown.
144     *
145     * @return The flag which determines whether <code>null</code> objects in the property path will
146     * genenerate an <code>IllegalArgumentException</code> or not.
147     */
148    public boolean isIgnoreNull() {
149        return ignoreNull;
150    }
151
152    /**
153     * Returns the value of the property named in the transformer's constructor for
154     * the object provided. If any object in the property path leading up to the target property is
155     * <code>null</code> then the outcome will be based on the value of the <code>ignoreNull</code>
156     * attribute. By default, <code>ignoreNull</code> is <code>false</code> and would result in an
157     * <code>IllegalArgumentException</code> if an object in the property path leading up to the
158     * target property is <code>null</code>.
159     *
160     * @param object The object to be transformed.
161     * @return The value of the property named in the transformer's constructor for the object
162     * provided.
163     * @throws IllegalArgumentException If an IllegalAccessException, InvocationTargetException, or
164     * NoSuchMethodException is thrown when trying to access the property specified on the object
165     * provided. Or if an object in the property path provided is <code>null</code> and
166     * <code>ignoreNull</code> is set to <code>false</code>.
167     */
168    @Override
169    public Object transform(final Object object) {
170
171        Object propertyValue = null;
172
173        try {
174            propertyValue = PropertyUtils.getProperty(object, propertyName);
175        } catch (final IllegalArgumentException e) {
176            final String errorMsg = "Problem during transformation. Null value encountered in property path...";
177
178            if (!ignoreNull) {
179                throw new IllegalArgumentException(errorMsg, e);
180            }
181            log.warn("WARNING: " + errorMsg + e);
182        } catch (final IllegalAccessException e) {
183            final String errorMsg = "Unable to access the property provided.";
184            throw new IllegalArgumentException(errorMsg, e);
185        } catch (final InvocationTargetException e) {
186            final String errorMsg = "Exception occurred in property's getter";
187            throw new IllegalArgumentException(errorMsg, e);
188        } catch (final NoSuchMethodException e) {
189            final String errorMsg = "No property found for name [" +
190                propertyName + "]";
191            throw new IllegalArgumentException(errorMsg, e);
192        }
193
194        return propertyValue;
195    }
196}