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 */
020 package org.apache.directory.shared.ldap.schema.comparators;
021
022
023 import java.util.Comparator;
024 import javax.naming.NamingException;
025
026 import org.apache.directory.shared.ldap.entry.Value;
027 import org.apache.directory.shared.ldap.schema.Normalizer;
028 import org.slf4j.Logger;
029 import org.slf4j.LoggerFactory;
030
031
032 /**
033 * A comparator which normalizes a value first before using a subordinate
034 * comparator to compare them.
035 *
036 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
037 * @version $Rev: 798550 $
038 */
039 public class NormalizingComparator implements Comparator
040 {
041 private static final Logger log = LoggerFactory.getLogger( NormalizingComparator.class );
042
043 /** the Normalizer to normalize values with before comparing */
044 private Normalizer normalizer;
045
046 /** the underlying comparator to use for comparisons */
047 private Comparator<Object> comparator;
048
049
050 /**
051 * A comparator which normalizes a value first before comparing them.
052 *
053 * @param normalizer the Normalizer to normalize values with before comparing
054 * @param comparator the underlying comparator to use for comparisons
055 */
056 public NormalizingComparator( Normalizer normalizer, Comparator<Object> comparator )
057 {
058 this.normalizer = normalizer;
059 this.comparator = comparator;
060 }
061
062
063 /**
064 * If any normalization attempt fails we compare using the unnormalized
065 * object.
066 *
067 * @see Comparator#compare(Object, Object)
068 */
069 public int compare( Object o1, Object o2 )
070 {
071 Object n1;
072 Object n2;
073
074 try
075 {
076 n1 = normalizer.normalize( (String)o1 );
077 }
078 catch ( NamingException e )
079 {
080 log.warn( "Failed to normalize: " + o1, e );
081 n1 = o1;
082 }
083
084 try
085 {
086 n2 = normalizer.normalize( (String)o2 );
087 }
088 catch ( NamingException e )
089 {
090 log.warn( "Failed to normalize: " + o2, e );
091 n2 = o2;
092 }
093
094 return comparator.compare( n1, n2 );
095 }
096 }