class QNameComparator implements Comparator<QName> {

    @Override
    public int compare(final QName o1, final QName o2) {
        // first namespace declarations
        final boolean isXmlNs1 = o1.getPrefix().equalsIgnoreCase(XMLConstants.XML_NS_PREFIX);
        final boolean isXmlNs2 = o2.getPrefix().equalsIgnoreCase(XMLConstants.XML_NS_PREFIX);
        if (isXmlNs1 && !isXmlNs2) {
            return LESS_THAN;
        } else if (!isXmlNs1 && isXmlNs2) {
            return GREATER_THAN;
        }
        // prefixed attributes before non-prefixed ones...
        if (!o1.getPrefix().equalsIgnoreCase(XMLConstants.DEFAULT_NS_PREFIX) && o2.getPrefix().equalsIgnoreCase(XMLConstants.DEFAULT_NS_PREFIX)) {
            return LESS_THAN;
        } else if (o1.getPrefix().equalsIgnoreCase(XMLConstants.DEFAULT_NS_PREFIX) && !o2.getPrefix().equalsIgnoreCase(XMLConstants.DEFAULT_NS_PREFIX)) {
            return GREATER_THAN;
        } else {
            // order first by prefix, then by local name
            String lowerCaseQName1 = o1.getPrefix().toLowerCase(Locale.ROOT) + o1.getLocalPart().toLowerCase(Locale.ROOT);
            String lowerCaseQName2 = o2.getPrefix().toLowerCase(Locale.ROOT) + o2.getLocalPart().toLowerCase(Locale.ROOT);
            final int c = lowerCaseQName1.compareTo(lowerCaseQName2);
            // if the lowercase versions are equal, they could differ in case (see JCRVLT-334)
            if (c == EQUAL) {
                String qName1 = o1.getPrefix() + o1.getLocalPart();
                String qName2 = o2.getPrefix() + o2.getLocalPart();
                return qName1.compareTo(qName2);
            }
            return c;
        }
    }

}