    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) of the objects to diff are discovered using reflection and compared for differences.
    033 * </p>
    034 *
    035 * <p>
    036 * To use this class, write code as follows:
    037 * </p>
    038 *
    039 * <pre>{@code
    040 * public class Person implements Diffable&lt;Person&gt; {
    041 *   String name;
    042 *   int age;
    043 *   boolean smoker;
    044 *   ...
    045 *
    046 *   public DiffResult diff(Person obj) {
    047 *     // No need for null check, as NullPointerException correct if obj is null
    048 *     return new ReflectionDiffBuilder.<Person>builder()
    049 *       .setDiffBuilder(DiffBuilder.<Person>builder()
    050 *           .setLeft(this)
    051 *           .setRight(obj)
    052 *           .setStyle(ToStringStyle.SHORT_PREFIX_STYLE)
    053 *           .build())
    054 *       .setExcludeFieldNames("userName", "password")
    055 *       .build();
    056 *   }
    057 * }
    058 * }</pre>
    059 *
    060 * <p>
    061 * The {@link ToStringStyle} passed to the constructor is embedded in the returned {@link DiffResult} and influences the style of the
    062 * {@code DiffResult.toString()} method. This style choice can be overridden by calling {@link DiffResult#toString(ToStringStyle)}.
    063 * </p>
    064 * <p>
    065 * See {@link DiffBuilder} for a non-reflection based version of this class.
    066 * </p>
    067 *
    068 * @param <T> type of the left and right object to diff.
    069 * @see Diffable
    070 * @see Diff
    071 * @see DiffResult
    072 * @see ToStringStyle
    073 * @see DiffBuilder
    074 * @since 3.6
    075 */
    076public class ReflectionDiffBuilder<T> implements Builder<DiffResult<T>> {
    077
    078    /**
    079     * Constructs a new instance.
    080     *
    081     * @param <T> type of the left and right object.
    082     * @since 3.15.0
    083     */
    084    public static final class Builder<T> {
    085
    086        private String[] excludeFieldNames = ArrayUtils.EMPTY_STRING_ARRAY;
    087        private DiffBuilder<T> diffBuilder;
    088
    089        /**
    090         * Builds a new configured {@link ReflectionDiffBuilder}.
    091         *
    092         * @return a new configured {@link ReflectionDiffBuilder}.
    093         */
    094        public ReflectionDiffBuilder<T> build() {
    095            return new ReflectionDiffBuilder<>(diffBuilder, excludeFieldNames);
    096        }
    097
    098        /**
    099         * Sets the DiffBuilder.
    100         *
    101         * @param diffBuilder the DiffBuilder.
    102         * @return {@code this} instance.
    103         */
    104        public Builder<T> setDiffBuilder(final DiffBuilder<T> diffBuilder) {
    105            this.diffBuilder = diffBuilder;
    106            return this;
    107        }
    108
    109        /**
    110         * Sets field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
    111         *
    112         * @param excludeFieldNames field names to exclude.
    113         * @return {@code this} instance.
    114         */
    115        public Builder<T> setExcludeFieldNames(final String... excludeFieldNames) {
    116            this.excludeFieldNames = toExcludeFieldNames(excludeFieldNames);
    117            return this;
    118        }
    119
    120    }
    121
    122    /**
    123     * Constructs a new {@link Builder}.
    124     *
    125     * @param <T> type of the left and right object.
    126     * @return a new {@link Builder}.
    127     * @since 3.15.0
    128     */
    129    public static <T> Builder<T> builder() {
    130        return new Builder<>();
    131    }
    132
    133    private static String[] toExcludeFieldNames(final String[] excludeFieldNames) {
    134        if (excludeFieldNames == null) {
    135            return ArrayUtils.EMPTY_STRING_ARRAY;
    136        }
    137        // clone and remove nulls
    138        return ArraySorter.sort(ReflectionToStringBuilder.toNoNullStringArray(excludeFieldNames));
    139    }
    140
    141    private final DiffBuilder<T> diffBuilder;
    142
    143    /**
    144     * Field names to exclude from output. Intended for fields like {@code "password"} or {@code "lastModificationDate"}.
    145     */
    146    private String[] excludeFieldNames;
    147
    148    private ReflectionDiffBuilder(final DiffBuilder<T> diffBuilder, final String[] excludeFieldNames) {
    149        this.diffBuilder = diffBuilder;
    150        this.excludeFieldNames = excludeFieldNames;
    151    }
    152
    153    /**
    154     * Constructs a builder for the specified objects with the specified style.
    155     *
    156     * <p>
    157     * If {@code left == right} or {@code left.equals(right)} then the builder will not evaluate any calls to {@code append(...)} and will return an empty
    158     * {@link DiffResult} when {@link #build()} is executed.
    159     * </p>
    160     *
    161     * @param left  {@code this} object.
    162     * @param right the object to diff against.
    163     * @param style the style will use when outputting the objects, {@code null} uses the default
    164     * @throws IllegalArgumentException if {@code left} or {@code right} is {@code null}.
    165     * @deprecated Use {@link Builder}.
    166     */
    167    @Deprecated
    168    public ReflectionDiffBuilder(final T left, final T right, final ToStringStyle style) {
    169        this(DiffBuilder.<T>builder().setLeft(left).setRight(right).setStyle(style).build(), null);
    170    }
    171
    172    private boolean accept(final Field field) {
    173        if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
    174            return false;
    175        }
    176        if (Modifier.isTransient(field.getModifiers())) {
    177            return false;
    178        }
    179        if (Modifier.isStatic(field.getModifiers())) {
    180            return false;
    181        }
    182        if (this.excludeFieldNames != null && Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
    183            // Reject fields from the getExcludeFieldNames list.
    184            return false;
    185        }
    186        return !field.isAnnotationPresent(DiffExclude.class);
    187    }
    188
    189    private void appendFields(final Class<?> clazz) {
    190        for (final Field field : FieldUtils.getAllFields(clazz)) {
    191            if (accept(field)) {
    192                try {
    193                    diffBuilder.append(field.getName(), readField(field, getLeft()), readField(field, getRight()));
    194                } catch (final IllegalAccessException e) {
    195                    // this can't happen. Would get a Security exception instead
    196                    // throw a runtime exception in case the impossible happens.
    197                    throw new IllegalArgumentException("Unexpected IllegalAccessException: " + e.getMessage(), e);
    198                }
    199            }
    200        }
    201    }
    202
    203    @Override
    204    public DiffResult<T> build() {
    205        if (getLeft().equals(getRight())) {
    206            return diffBuilder.build();
    207        }
    208
    209        appendFields(getLeft().getClass());
    210        return diffBuilder.build();
    211    }
    212
    213    /**
    214     * Gets the field names that should be excluded from the diff.
    215     *
    216     * @return Returns the excludeFieldNames.
    217     * @since 3.13.0
    218     */
    219    public String[] getExcludeFieldNames() {
    220        return this.excludeFieldNames.clone();
    221    }
    222
    223    private T getLeft() {
    224        return diffBuilder.getLeft();
    225    }
    226
    227    private T getRight() {
    228        return diffBuilder.getRight();
    229    }
    230
    231    private Object readField(final Field field, final Object target) throws IllegalAccessException {
    232        return FieldUtils.readField(field, target, true);
    233    }
    234
    235    /**
    236     * Sets the field names to exclude.
    237     *
    238     * @param excludeFieldNames The field names to exclude from the diff or {@code null}.
    239     * @return {@code this}
    240     * @since 3.13.0
    241     * @deprecated Use {@link Builder#setExcludeFieldNames(String[])}.
    242     */
    243    @Deprecated
    244    public ReflectionDiffBuilder<T> setExcludeFieldNames(final String... excludeFieldNames) {
    245        this.excludeFieldNames = toExcludeFieldNames(excludeFieldNames);
    246        return this;
    247    }
    248
    249}