001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.camel.util; 018 019import java.util.Comparator; 020 021import org.apache.camel.Ordered; 022 023/** 024 * A comparator to sort {@link Ordered} 025 * 026 * @version 027 */ 028public final class OrderedComparator implements Comparator<Object> { 029 030 private static final OrderedComparator INSTANCE = new OrderedComparator(); 031 private static final OrderedComparator INSTANCE_REVERSE = new OrderedComparator(true); 032 033 private final boolean reverse; 034 035 /** 036 * Favor using the static instance {@link #get()} 037 */ 038 public OrderedComparator() { 039 this(false); 040 } 041 042 /** 043 * Favor using the static instance {@link #getReverse()} 044 */ 045 public OrderedComparator(boolean reverse) { 046 this.reverse = reverse; 047 } 048 049 /** 050 * Gets the comparator that sorts a..z 051 */ 052 public static OrderedComparator get() { 053 return INSTANCE; 054 } 055 056 /** 057 * Gets the comparator that sorts z..a (reverse) 058 */ 059 public static OrderedComparator getReverse() { 060 return INSTANCE_REVERSE; 061 } 062 063 public int compare(Object o1, Object o2) { 064 Integer num1 = 0; 065 Integer num2 = 0; 066 if (o1 instanceof Ordered) { 067 num1 = ((Ordered) o1).getOrder(); 068 } 069 if (o2 instanceof Ordered) { 070 num2 = ((Ordered) o2).getOrder(); 071 } 072 int answer = num1.compareTo(num2); 073 return reverse ? -1 * answer : answer; 074 } 075}