]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.client.ui.dist/src/org/argeo/slc/client/ui/dist/utils/VersionComparator.java
34aff22b9b06895fb73dd1426d8b9166f557d701
[gpl/argeo-slc.git] / org.argeo.slc.client.ui.dist / src / org / argeo / slc / client / ui / dist / utils / VersionComparator.java
1 package org.argeo.slc.client.ui.dist.utils;
2
3 import org.eclipse.jface.viewers.Viewer;
4 import org.eclipse.jface.viewers.ViewerComparator;
5
6 /**
7 * Enable comparison of two version string with form "1.2.5.qualifier" with
8 * following rules and assumptions:
9 * <ul>
10 * <li>
11 * Version are parsed and compared segment by segment; doing best effort to
12 * convert major, minor and micro to integer and compare them as such (to have
13 * 0.1 < 0.9 < 0.10 not 0.1 < 0.10 < 0.9).</li>
14 * <li>Version should not contain any dash (-), version segments should be
15 * separated by dots (.)</li>
16 * </ul>
17 */
18
19 public class VersionComparator extends ViewerComparator {
20 private static final long serialVersionUID = 3760077835650538982L;
21
22 @Override
23 public int compare(Viewer viewer, Object e1, Object e2) {
24 String s1 = (String) e1;
25 String s2 = (String) e2;
26 return compareVersion(s1, s2);
27 }
28
29 /**
30 * Enable comparison of two versions of the form
31 * "major.minor.micro.qualifier". We assume the separator is always a "."
32 * and make best effort to convert major, minor and micro to int.
33 */
34 private int compareVersion(String v1, String v2) {
35 String[] t1 = v1.split("\\.");
36 String[] t2 = v2.split("\\.");
37
38 for (int i = 0; i < t1.length && i < t2.length; i++) {
39 int result = compareToken(t1[i], t2[i]);
40 if (result != 0)
41 return result;
42 }
43 if (t1.length > t2.length)
44 return 1;
45 else if (t1.length < t2.length)
46 return -1;
47 else
48 return 0;
49 }
50
51 private int compareToken(String t1, String t2) {
52 if (t1 == null && t2 == null)
53 return 0;
54 else if (t1 == null)
55 return -1;
56 else if (t2 == null)
57 return 1;
58
59 Integer i1 = null, i2 = null;
60 try {
61 i1 = new Integer(t1);
62 i2 = new Integer(t2);
63 } catch (NumberFormatException nfe) {
64 // the format is not valid we silently compare as String
65 return t1.compareTo(t2);
66 }
67 return i1.compareTo(i2);
68 }
69 }