001package com.identityworksllc.iiq.common;
002
003import org.apache.commons.logging.Log;
004import org.apache.commons.logging.LogFactory;
005
006import java.util.Collection;
007import java.util.Date;
008import java.util.HashSet;
009import java.util.Map;
010import java.util.stream.Collectors;
011
012/**
013 * Utility methods for detecting whether two objects are the same, since IIQ is inconsistent about it.
014 * The primary method in here is {@link Sameness#isSame(Object, Object, boolean)}. This class
015 * is heavily used throughout the IIQCommon libraries as well as the IDW plugins.
016 *
017 * @author Devin Rosenbauer
018 * @author Instrumental Identity
019 */
020public class Sameness {
021    private static final Log log = LogFactory.getLog(Sameness.class);
022
023    /**
024     * Populates two HashSet collections with the appropriate values, taking into
025     * account case sensitivity, and then returns true if they are the same.
026     *
027     * @param ignoreCase True if the comparison should ignore case
028     * @param newSet The set containing 'new' values
029     * @param oldSet The set containing 'old' values
030     * @return True if the values are the same
031     */
032    private static boolean checkSets(boolean ignoreCase, HashSet<Object> newSet, HashSet<Object> oldSet) {
033        if (ignoreCase) {
034            newSet = newSet.stream().map(e -> String.valueOf(e).toUpperCase()).collect(Collectors.toCollection(HashSet::new));
035            oldSet = oldSet.stream().map(e -> String.valueOf(e).toUpperCase()).collect(Collectors.toCollection(HashSet::new));
036        }
037
038        return newSet.equals(oldSet);
039    }
040
041    /**
042     * Returns true if the given thing is empty in the isSame() sense, i.e.,
043     * if it ought to be the same as null. These are values that are often
044     * optimized out by SailPoint when serializing to XML.
045     *
046     * A thing is empty if it is null or is an empty string, array, collection,
047     * or map. Boolean false and integer 0 are also empty.
048     *
049     * All other values are not empty.
050     *
051     * @param thing The thing to check for emptiness
052     * @return True if the thing is empty; false otherwise
053     */
054    public static boolean isEmpty(Object thing) {
055        if (thing == null) {
056            return true;
057        }
058        if (thing instanceof String) {
059            return thing.equals("");
060        } else if (thing instanceof Boolean) {
061            return !((Boolean)thing);
062        } else if (thing instanceof Number) {
063            // I am questioning this. If this causes problems, it can be removed.
064            int intValue = ((Number) thing).intValue();
065            return (intValue == 0);
066        } else if (thing.getClass().isArray()) {
067            assert thing instanceof Object[];
068            return ((Object[])thing).length == 0;
069        } else if (thing instanceof Collection) {
070            return ((Collection<?>) thing).isEmpty();
071        } else if (thing instanceof Map) {
072            return ((Map<?, ?>) thing).isEmpty();
073        }
074        return false;
075    }
076
077    /**
078     * A typo-friendly inversion of {@link #isSame(Object, Object, boolean)}.
079     *
080     * @param newValue The new value (can be null)
081     * @param oldValue The old value (can be null)
082     * @param ignoreCase True if strings and collections should be compared ignoring case. Maps are always compared case-insensitively.
083     * @return True if the values are NOT "the same" according to our definition
084     */
085    public static boolean isNotSame(final Object newValue, final Object oldValue, boolean ignoreCase) {
086        return !isSame(newValue, oldValue, ignoreCase);
087    }
088
089    /**
090     * Decide whether the two inputs are the same.
091     *
092     * This can be an expensive check and so should be used in concert with existing .equals(), e.g. `o1.equals(o2) || isSame(o1, o2)`.
093     *
094     * 1) Type differences: If the two values are a String and a Boolean (or a String and a Number), but will be stored the same way by Hibernate, they are the same
095     * 2) Null and empty: Null is the same as any empty object (strings, lists, maps, boolean false)
096     * 3) Dates and Longs: If one value is a long and one is a Date, they are the same if {@link Date#getTime()} equals the long value
097     * 4) Collections: Two collections are the same if they have equal elements in any order. If ignoreCase is true, elements will be converted to strings and compared case-insensitively.
098     * 5) String case: Two strings will be compared case-insensitive if the flag is passed as true
099     * 6) String vs. Collection case: A string is the same as collection containing only that string
100     *
101     * @param newValue The new value (can be null)
102     * @param oldValue The old value (can be null)
103     * @param ignoreCase True if strings and collections should be compared ignoring case. Maps are always compared case-insensitively.
104     * @return True if the values are "the same" according to our definition
105     */
106    public static boolean isSame(final Object newValue, final Object oldValue, boolean ignoreCase) {
107        if (log.isTraceEnabled()) {
108            log.trace("isSame() called with: newValue = [" + newValue + "], oldValue = [" + oldValue + "], ignoreCase = [" + ignoreCase + "]");
109        }
110        if (newValue == null || oldValue == null) {
111            return isEmpty(newValue) && isEmpty(oldValue);
112        } else if (newValue == oldValue) {
113            return true;
114        } else if (newValue instanceof Boolean && oldValue instanceof Boolean) {
115            return newValue.equals(oldValue);
116        } else if (newValue instanceof String && oldValue instanceof String) {
117            if (ignoreCase) {
118                return ((String) newValue).equalsIgnoreCase((String) oldValue);
119            }
120            return newValue.equals(oldValue);
121        } else if (newValue instanceof Date && oldValue instanceof Long) {
122            Date oldDate = new Date((Long)oldValue);
123            return newValue.equals(oldDate);
124        } else if (newValue instanceof Long && oldValue instanceof Date) {
125            Date newDate = new Date((Long) newValue);
126            return oldValue.equals(newDate);
127        } else if (newValue.getClass().isArray() && isEmpty(newValue)) {
128            return isEmpty(oldValue);
129        } else if (oldValue.getClass().isArray() && isEmpty(oldValue)) {
130            return isEmpty(newValue);
131        } else if (newValue instanceof Collection && oldValue instanceof Collection) {
132            HashSet<Object> newSet = new HashSet<>((Collection<?>) newValue);
133            HashSet<Object> oldSet = new HashSet<>((Collection<?>) oldValue);
134            return checkSets(ignoreCase, newSet, oldSet);
135        } else if (newValue instanceof Map && oldValue instanceof Map) {
136            return newValue.equals(oldValue);
137        } else if (newValue instanceof String && oldValue instanceof Collection) {
138            HashSet<Object> newSet = new HashSet<>();
139            HashSet<Object> oldSet = new HashSet<>((Collection<?>)oldValue);
140            newSet.add(newValue);
141            return checkSets(ignoreCase, newSet, oldSet);
142        } else if (newValue instanceof Collection && oldValue instanceof String) {
143            HashSet<Object> newSet = new HashSet<>((Collection<?>) newValue);
144            HashSet<Object> oldSet = new HashSet<>();
145            oldSet.add(oldValue);
146            return checkSets(ignoreCase, newSet, oldSet);
147        } else {
148            String ns = String.valueOf(newValue);
149            String os = String.valueOf(oldValue);
150            if (ignoreCase) {
151                return ns.equalsIgnoreCase(os);
152            } else {
153                return ns.equals(os);
154            }
155        }
156    }
157}