001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.api.util.comparators;
015
016import org.gbif.api.model.registry.Endpoint;
017import org.gbif.api.vocabulary.EndpointType;
018
019import java.io.Serializable;
020import java.util.Arrays;
021import java.util.Collections;
022import java.util.Comparator;
023import java.util.List;
024
025/**
026 * Compares two Endpoints.
027 * <p></p>
028 * It does so by using a priority list of Endpoint Types. This Comparator will throw a {@link
029 * ClassCastException} exception if a non supported EndpointType is passed in. It also does not
030 * support {@code null} values.
031 * <p></p>
032 * The priority list is as follows (most to least important):
033 * <ol>
034 * <li>CamtrapDP</li>
035 * <li>DwC-A</li>
036 * <li>TAPIR</li>
037 * <li>BioCASe</li>
038 * <li>DiGIR</li>
039 * <li>DiGIR (Manis)</li>
040 * <li>EML</li>
041 * <li>DWC_DP</li>
042 * <li>COLDP</li>
043 * </ol>
044 */
045public class EndpointPriorityComparator implements Comparator<Endpoint>, Serializable {
046
047  /* Note: Due to legacy reasons this is a Comparator itself instead of just using the PRIORITY_COMPARATOR.
048   It should be easy to remove this class or change it into a factory */
049
050  // Priorities from lowest to highest
051  public static final List<EndpointType> PRIORITIES = Collections.unmodifiableList(
052    Arrays.asList(
053      EndpointType.COLDP,
054      EndpointType.DWC_DP,
055      EndpointType.EML,
056      EndpointType.DIGIR_MANIS,
057      EndpointType.DIGIR,
058      EndpointType.BIOCASE,
059      EndpointType.TAPIR,
060      EndpointType.BIOCASE_XML_ARCHIVE,
061      EndpointType.DWC_ARCHIVE,
062      EndpointType.CAMTRAP_DP
063    ));
064
065  private static final long serialVersionUID = 8085216142750609841L;
066
067  @Override
068  public int compare(Endpoint endpoint1, Endpoint endpoint2) {
069    int firstEndpointTypeIndex = PRIORITIES.indexOf(endpoint1.getType());
070    int secondEndpointTypeIndex = PRIORITIES.indexOf(endpoint2.getType());
071
072    if (firstEndpointTypeIndex == -1) {
073      throw new ClassCastException("Cannot compare value: " + endpoint1.getType());
074    } else if (secondEndpointTypeIndex == -1) {
075      throw new ClassCastException("Cannot compare value: " + endpoint2.getType());
076    } else {
077      return Integer.compare(firstEndpointTypeIndex, secondEndpointTypeIndex);
078    }
079  }
080}