001/* 002 Licensed to the Apache Software Foundation (ASF) under one 003 or more contributor license agreements. See the NOTICE file 004 distributed with this work for additional information 005 regarding copyright ownership. The ASF licenses this file 006 to you under the Apache License, Version 2.0 (the 007 "License"); you may not use this file except in compliance 008 with the License. You may obtain a copy of the License at 009 010 http://www.apache.org/licenses/LICENSE-2.0 011 012 Unless required by applicable law or agreed to in writing, 013 software distributed under the License is distributed on an 014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 KIND, either express or implied. See the License for the 016 specific language governing permissions and limitations 017 under the License. 018 */ 019 020package org.apache.wiki.util.comparators; 021 022import org.apache.commons.lang3.StringUtils; 023 024import java.text.Collator; 025import java.util.Comparator; 026 027/** 028 * A comparator that sorts Strings using a Collator. This class is needed 029 * because, even though Collator implements 030 * <code>Comparator<Object></code> and the required 031 * <code>compare(String, String)</code> method, you can't safely cast Collator 032 * to <code>Comparator<String></code>. 033 * 034 */ 035public class CollatorComparator implements Comparator<String> 036{ 037 // A special singleton instance for quick access 038 public static final Comparator<String> DEFAULT_LOCALE_COMPARATOR = new CollatorComparator(); 039 040 protected Collator m_collator; 041 042 /** 043 * Default constructor uses the current locale's collator. 044 */ 045 public CollatorComparator() 046 { 047 m_collator = Collator.getInstance(); 048 } 049 050 /** 051 * Construct with a specific collator. 052 * 053 * @param collator the collator to be used for comparisons 054 */ 055 public CollatorComparator(final Collator collator ) 056 { 057 m_collator = collator; 058 } 059 060 /* 061 * (non-Javadoc) 062 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) 063 */ 064 public int compare(final String str1, final String str2 ) 065 { 066 if( StringUtils.equals( str1, str2 ) ) { 067 return 0; // the same object 068 } 069 if( str1 == null ) { 070 return -1; // str1 is null and str2 isn't so str1 is smaller 071 } 072 if( str2 == null ) { 073 return 1; // str2 is null and str1 isn't so str1 is bigger 074 } 075 return m_collator.compare( str1, str2 ); 076 } 077 078 /** 079 * Specify a new collator. 080 * 081 * @param collator the collator to be used from now on 082 */ 083 public void setCollator(final Collator collator ) 084 { 085 m_collator = collator; 086 } 087}