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 *      http://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 */
017package org.apache.commons.lang3.builder;
018
019import java.lang.reflect.Field;
020import java.lang.reflect.Modifier;
021import java.util.Arrays;
022
023import org.apache.commons.lang3.ArraySorter;
024import org.apache.commons.lang3.ArrayUtils;
025import org.apache.commons.lang3.ClassUtils;
026import org.apache.commons.lang3.reflect.FieldUtils;
027
028/**
029 * Assists in implementing {@link Diffable#diff(Object)} methods.
030 *
031 * <p>
032 * All non-static, non-transient fields (including inherited fields)
033 * of the objects to diff are discovered using reflection and compared
034 * for differences.
035 * </p>
036 *
037 * <p>
038 * To use this class, write code as follows:
039 * </p>
040 *
041 * <pre>
042 * public class Person implements Diffable&lt;Person&gt; {
043 *   String name;
044 *   int age;
045 *   boolean smoker;
046 *   ...
047 *
048 *   public DiffResult diff(Person obj) {
049 *     // No need for null check, as NullPointerException correct if obj is null
050 *     return new ReflectionDiffBuilder(this, obj, ToStringStyle.SHORT_PREFIX_STYLE)
051 *       .build();
052 *   }
053 * }
054 * </pre>
055 *
056 * <p>
057 * The {@link ToStringStyle} passed to the constructor is embedded in the
058 * returned {@link DiffResult} and influences the style of the
059 * {@code DiffResult.toString()} method. This style choice can be overridden by
060 * calling {@link DiffResult#toString(ToStringStyle)}.
061 * </p>
062 * <p>
063 * See {@link DiffBuilder} for a non-reflection based version of this class.
064 * </p>
065 * @param <T>
066 *            type of the left and right object to diff.
067 * @see Diffable
068 * @see Diff
069 * @see DiffResult
070 * @see ToStringStyle
071 * @see DiffBuilder
072 * @since 3.6
073 */
074public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
075
076    private final T left;
077    private final T right;
078    private final DiffBuilder<T> diffBuilder;
079
080    /**
081     * Field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
082     *
083     * @since 3.13.0
084     */
085    private String[] excludeFieldNames;
086
087    /**
088     * Constructs a builder for the specified objects with the specified style.
089     *
090     * <p>
091     * If {@code lhs == rhs} or {@code lhs.equals(rhs)} then the builder will
092     * not evaluate any calls to {@code append(...)} and will return an empty
093     * {@link DiffResult} when {@link #build()} is executed.
094     * </p>
095     * @param lhs
096     *            {@code this} object
097     * @param rhs
098     *            the object to diff against
099     * @param style
100     *            the style will use when outputting the objects, {@code null}
101     *            uses the default
102     * @throws IllegalArgumentException
103     *             if {@code lhs} or {@code rhs} is {@code null}
104     */
105    public ReflectionDiffBuilder(final T lhs, final T rhs, final ToStringStyle style) {
106        this.left = lhs;
107        this.right = rhs;
108        this.diffBuilder = new DiffBuilder<>(lhs, rhs, style);
109    }
110
111    private boolean accept(final Field field) {
112        if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
113            return false;
114        }
115        if (Modifier.isTransient(field.getModifiers())) {
116            return false;
117        }
118        if (Modifier.isStatic(field.getModifiers())) {
119            return false;
120        }
121        if (this.excludeFieldNames != null
122                && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
123            // Reject fields from the getExcludeFieldNames list.
124            return false;
125        }
126        return !field.isAnnotationPresent(DiffExclude.class);
127    }
128
129
130    private void appendFields(final Class<?> clazz) {
131        for (final Field field : FieldUtils.getAllFields(clazz)) {
132            if (accept(field)) {
133                try {
134                    diffBuilder.append(field.getName(), FieldUtils.readField(field, left, true), FieldUtils.readField(field, right, true));
135                } catch (final IllegalAccessException e) {
136                    // this can't happen. Would get a Security exception instead
137                    // throw a runtime exception in case the impossible happens.
138                    throw new IllegalArgumentException("Unexpected IllegalAccessException: " + e.getMessage(), e);
139                }
140            }
141        }
142    }
143
144    @Override
145    public DiffResult<T> build() {
146        if (left.equals(right)) {
147            return diffBuilder.build();
148        }
149
150        appendFields(left.getClass());
151        return diffBuilder.build();
152    }
153
154    /**
155     * Gets the field names that should be excluded from the diff.
156     *
157     * @return Returns the excludeFieldNames.
158     * @since 3.13.0
159     */
160    public String[] getExcludeFieldNames() {
161        return this.excludeFieldNames.clone();
162    }
163
164    /**
165     * Sets the field names to exclude.
166     *
167     * @param excludeFieldNamesParam
168     *            The field names to exclude from the diff or {@code null}.
169     * @return {@code this}
170     * @since 3.13.0
171     */
172    public ReflectionDiffBuilder<T> setExcludeFieldNames(final String... excludeFieldNamesParam) {
173        if (excludeFieldNamesParam == null) {
174            this.excludeFieldNames = ArrayUtils.EMPTY_STRING_ARRAY;
175        } else {
176            // clone and remove nulls
177            this.excludeFieldNames = ArraySorter.sort(ReflectionToStringBuilder.toNoNullStringArray(excludeFieldNamesParam));
178        }
179        return this;
180    }
181
182}