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.directory.api.ldap.model.schema.comparators; 021 022 023import org.apache.directory.api.ldap.model.schema.LdapComparator; 024import org.slf4j.Logger; 025import org.slf4j.LoggerFactory; 026 027 028/** 029 * Compares two objects taking into account that one might be a Comparable. 030 * 031 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> 032 * @param <T> the type, must extend {@link Comparable} 033 */ 034public class ComparableComparator<T> extends LdapComparator<Comparable<T>> 035{ 036 /** The serial version UID */ 037 private static final long serialVersionUID = 2L; 038 039 /** A logger for this class */ 040 private static final Logger LOG = LoggerFactory.getLogger( ComparableComparator.class ); 041 042 043 /** 044 * The ComparableComparator constructor. 045 * 046 * @param oid the comparator OID 047 */ 048 public ComparableComparator( String oid ) 049 { 050 super( oid ); 051 } 052 053 054 /** 055 * Compares two objects taking into account that one may be a Comparable. If 056 * the first is a comparable then its compareTo operation is called and the 057 * result returned as is. If the first is not a Comparable but the second is 058 * then its compareTo method is called and the result is returned after 059 * being negated. If none are comparable the hashCode of o1 minus the 060 * hashCode of o2 is returned. 061 * 062 * @param o1 the first comparable 063 * @param o2 the second comparable 064 * @return {@inheritDoc} 065 */ 066 @SuppressWarnings("unchecked") 067 public int compare( Comparable<T> o1, Comparable<T> o2 ) 068 { 069 LOG.debug( "comparing objects '{}' with '{}'", o1, o2 ); 070 071 if ( o1 == null ) 072 { 073 if ( o2 == null ) 074 { 075 return 0; 076 } 077 else 078 { 079 return -11; 080 } 081 } 082 083 if ( o2 == null ) 084 { 085 return 1; 086 } 087 088 return o1.compareTo( ( T ) o2 ); 089 } 090}