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 * </ol>
042 */
043public class EndpointPriorityComparator implements Comparator<Endpoint>, Serializable {
044
045  /* Note: Due to legacy reasons this is a Comparator itself instead of just using the PRIORITY_COMPARATOR.
046   It should be easy to remove this class or change it into a factory */
047
048  // Priorities from lowest to highest
049  public static final List<EndpointType> PRIORITIES = Collections.unmodifiableList(
050    Arrays.asList(
051      EndpointType.EML,
052      EndpointType.DIGIR_MANIS,
053      EndpointType.DIGIR,
054      EndpointType.BIOCASE,
055      EndpointType.TAPIR,
056      EndpointType.BIOCASE_XML_ARCHIVE,
057      EndpointType.DWC_ARCHIVE,
058      EndpointType.CAMTRAP_DP
059    ));
060
061  private static final long serialVersionUID = 8085216142750609841L;
062
063  @Override
064  public int compare(Endpoint endpoint1, Endpoint endpoint2) {
065    int firstEndpointTypeIndex = PRIORITIES.indexOf(endpoint1.getType());
066    int secondEndpointTypeIndex = PRIORITIES.indexOf(endpoint2.getType());
067
068    if (firstEndpointTypeIndex == -1) {
069      throw new ClassCastException("Cannot compare value: " + endpoint1.getType());
070    } else if (secondEndpointTypeIndex == -1) {
071      throw new ClassCastException("Cannot compare value: " + endpoint2.getType());
072    } else {
073      return Integer.compare(firstEndpointTypeIndex, secondEndpointTypeIndex);
074    }
075  }
076}