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