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 */
017 package org.apache.logging.log4j.core.config;
018
019 import java.util.Comparator;
020
021 import org.apache.logging.log4j.core.util.Assert;
022
023 /**
024 * Comparator for classes annotated with {@link Order}.
025 *
026 * @since 2.1
027 */
028 public class OrderComparator implements Comparator<Class<?>> {
029
030 private static final Comparator<Class<?>> INSTANCE = new OrderComparator();
031
032 /**
033 * Returns a singleton instance of this class.
034 *
035 * @return the singleton for this class.
036 */
037 public static Comparator<Class<?>> getInstance() {
038 return INSTANCE;
039 }
040
041 @Override
042 public int compare(final Class<?> lhs, final Class<?> rhs) {
043 final Order lhsOrder = Assert.requireNonNull(lhs, "lhs").getAnnotation(Order.class);
044 final Order rhsOrder = Assert.requireNonNull(rhs, "rhs").getAnnotation(Order.class);
045 if (lhsOrder == null && rhsOrder == null) {
046 // both unannotated means equal priority
047 return 0;
048 }
049 // if only one class is @Order-annotated, then prefer that one
050 if (rhsOrder == null) {
051 return -1;
052 }
053 if (lhsOrder == null) {
054 return 1;
055 }
056 // larger value means lower priority
057 return Integer.signum(rhsOrder.value() - lhsOrder.value());
058 }
059 }