01: /*
02: * Copyright 2002-2007 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.core;
18:
19: import java.util.Comparator;
20:
21: /**
22: * {@link Comparator} implementation for {@link Ordered} objects,
23: * sorting by order value ascending (resp. by priority descending).
24: *
25: * <p>Non-<code>Ordered</code> objects are treated as greatest order
26: * values, thus ending up at the end of the list, in arbitrary order
27: * (just like same order values of <code>Ordered</code> objects).
28: *
29: * @author Juergen Hoeller
30: * @since 07.04.2003
31: * @see Ordered
32: * @see java.util.Collections#sort(java.util.List, java.util.Comparator)
33: * @see java.util.Arrays#sort(Object[], java.util.Comparator)
34: */
35: public class OrderComparator implements Comparator {
36:
37: public int compare(Object o1, Object o2) {
38: boolean p1 = (o1 instanceof PriorityOrdered);
39: boolean p2 = (o2 instanceof PriorityOrdered);
40: if (p1 && !p2) {
41: return -1;
42: } else if (p2 && !p1) {
43: return 1;
44: }
45:
46: // Direct evaluation instead of Integer.compareTo to avoid unnecessary object creation.
47: int i1 = getOrder(o1);
48: int i2 = getOrder(o2);
49: return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
50: }
51:
52: /**
53: * Determine the order value for the given object.
54: * <p>The default implementation checks against the {@link Ordered}
55: * interface. Can be overridden in subclasses.
56: * @param obj the object to check
57: * @return the order value, or <code>Ordered.LOWEST_PRECEDENCE</code> as fallback
58: */
59: protected int getOrder(Object obj) {
60: return (obj instanceof Ordered ? ((Ordered) obj).getOrder()
61: : Ordered.LOWEST_PRECEDENCE);
62: }
63:
64: }
|