1 /* 2 * Copyright 2006-2012 smartics, Kronseder & Reiner GmbH 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package de.smartics.maven.util.project; 17 18 import java.util.Comparator; 19 20 import org.apache.maven.project.MavenProject; 21 22 /** 23 * A simple implementation of a comparator that compares the groupId, then the 24 * artifactId, and finally the versions, lexicographically. 25 * 26 * @author <a href="mailto:robert.reiner@smartics.de">Robert Reiner</a> 27 * @version $Revision: 12040 $ 28 * @todo do no compare versions lexicographically. 29 */ 30 public class ProjectComparator implements Comparator<MavenProject> 31 { 32 /** 33 * {@inheritDoc} 34 * <p> 35 * Compares the groupId, then the artifactId, and finally the versions, 36 * lexicographically. 37 */ 38 public int compare(final MavenProject project1, final MavenProject project2) 39 { 40 final String groupId1 = project1.getGroupId(); 41 final String groupId2 = project2.getGroupId(); 42 int value = compareTo(groupId1, groupId2); 43 44 if (value == 0) 45 { 46 final String artifactId1 = project1.getArtifactId(); 47 final String artifactId2 = project2.getArtifactId(); 48 value = compareTo(artifactId1, artifactId2); 49 50 if (value == 0) 51 { 52 final String version1 = project1.getVersion(); 53 final String version2 = project2.getVersion(); 54 value = compareTo(version1, version2); 55 } 56 } 57 58 return value; 59 } 60 61 /** 62 * This is a <code>null</code>-safe implementation of the compare-to call. 63 * 64 * @param c1 the first comparable (left side, the instance whose compareTo 65 * method will be called). 66 * @param c2 the second comparable (right side, the instance that is the 67 * argument to the compareTo call). 68 * @return the value of the compareTo call. If both instances are 69 * <code>null</code>, zero is returned. If c1 is <code>null</code>, 70 * <code>-1</code> and if c2 is <code>null</code>, <code>1</code> is 71 * returned. 72 */ 73 private static int compareTo(final String c1, final String c2) 74 { 75 if (c1 == c2) 76 { 77 return 0; 78 } 79 else if (c1 == null) 80 { 81 return -1; 82 } 83 else if (c2 == null) 84 { 85 return 1; 86 } 87 else 88 { 89 return ((Comparable<String>) c1).compareTo(c2); 90 } 91 } 92 }