001package jmri.util;
002
003import jmri.NamedBean;
004
005/**
006 * Comparator for JMRI NamedBeans via their User Names.
007 * <p>
008 * If the User Names are both non-null and are not equal, uses the {@link AlphanumComparator},
009 * otherwise uses the {@link NamedBeanComparator}.
010 *
011 * @param <B> supported type of NamedBean
012 */
013public class NamedBeanUserNameComparator<B extends NamedBean> implements java.util.Comparator<B> {
014
015    public NamedBeanUserNameComparator() {
016    }
017
018    static final AlphanumComparator comparator = new AlphanumComparator();
019
020    @Override
021    public int compare(B n1, B n2) {
022        String s1 = n1.getUserName();
023        String s2 = n2.getUserName();
024
025        // handle both usernames being null or empty
026        if ((s1 == null || s1.isEmpty()) && (s2 == null || s2.isEmpty())) {
027            return n1.compareTo(n2);
028        }
029
030        // if both have user names, compare those
031        if (! (s1 == null || s1.isEmpty()) && ! (s2 == null || s2.isEmpty())) {
032            return comparator.compare(s1, s2);
033        }
034
035        // now must have one with and one without
036        if (s1 == null || s1.isEmpty()) {
037            return +1; // system name always after n2 with user name
038        } else {
039             return -1; // user name always before n2 with only system name
040        }
041    }
042}