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