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