001package ca.uhn.fhir.jpa.packages;
002
003/*-
004 * #%L
005 * HAPI FHIR JPA Server
006 * %%
007 * Copyright (C) 2014 - 2022 Smile CDR, Inc.
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import java.math.BigDecimal;
024import java.util.Comparator;
025
026import static org.apache.commons.lang3.StringUtils.isNumeric;
027
028public class PackageVersionComparator implements Comparator<String> {
029        public static final PackageVersionComparator INSTANCE = new PackageVersionComparator();
030
031        @Override
032        public int compare(String o1, String o2) {
033
034                String[] o1parts = o1.split("\\.");
035                String[] o2parts = o2.split("\\.");
036
037                for (int i = 0; i < o1parts.length && i < o2parts.length; i++) {
038                        String i1part = o1parts[i];
039                        String i2part = o2parts[i];
040
041                        if (isNumeric(i1part)) {
042                                if (isNumeric(i2part)) {
043                                        int cmp = new BigDecimal(i1part).compareTo(new BigDecimal(i2part));
044                                        if (cmp != 0) {
045                                                return cmp;
046                                        }
047                                }
048                        }
049
050                        int cmp = i1part.compareTo(i2part);
051                        if (cmp != 0) {
052                                return cmp;
053                        }
054                }
055
056                return o1parts.length - o2parts.length;
057        }
058
059        public static boolean isEquivalent(String theSpec, String thePackageVersion) {
060                String[] o1parts = theSpec.split("\\.");
061                String[] o2parts = thePackageVersion.split("\\.");
062
063                for (int i = 0; i < o1parts.length; i++ ) {
064                        if (!o1parts[i].equals("x")) {
065                                if (!o1parts[i].equals(o2parts[i])) {
066                                        return false;
067                                }
068                        }
069                }
070
071                return true;
072        }
073}