]> git.argeo.org Git - gpl/argeo-slc.git/blob - plugins/org.argeo.slc.client.ui.dist/src/main/java/org/argeo/slc/client/ui/dist/utils/NameVersionComparator.java
Implement order for versions and name versions.
[gpl/argeo-slc.git] / plugins / org.argeo.slc.client.ui.dist / src / main / java / org / argeo / slc / client / ui / dist / utils / NameVersionComparator.java
1 package org.argeo.slc.client.ui.dist.utils;
2
3 import org.argeo.eclipse.ui.TreeParent;
4 import org.eclipse.jface.viewers.Viewer;
5 import org.eclipse.jface.viewers.ViewerComparator;
6
7 /**
8 * Enable comparison of two names version string with form org.argeo.slc-1.2.x.
9 * with following rules and assumptions:
10 * <ul>
11 * <li>
12 * Names are ordered using Lexicographical order</li>
13 * <li>
14 * Version are parsed and compared segment by segment; doing best effort to
15 * convert major, minor and micro to integer and compare them as such (to have
16 * 0.1 < 0.9 < 0.10 not 0.1 < 0.10 < 0.9).</li>
17 * <li>Version should not contain any dash (-), version segments should be
18 * separated by dots (.)</li>
19 * </ul>
20 */
21
22 public class NameVersionComparator extends ViewerComparator {
23
24 private VersionComparator vc = new VersionComparator();
25
26 @Override
27 public int category(Object element) {
28 if (element instanceof String) {
29 int lastInd = ((String) element).lastIndexOf('-');
30 if (lastInd > 0)
31 return 10;
32 }
33 // unvalid names always last
34 return 5;
35 }
36
37 @Override
38 public int compare(Viewer viewer, Object e1, Object e2) {
39 int cat1 = category(e1);
40 int cat2 = category(e2);
41
42 if (cat1 != cat2) {
43 return cat1 - cat2;
44 }
45
46 int result = 0;
47
48 String s1, s2;
49
50 if (e1 instanceof TreeParent) {
51 s1 = ((TreeParent) e1).getName();
52 s2 = ((TreeParent) e2).getName();
53 } else {
54 s1 = e1.toString();
55 s2 = e2.toString();
56 }
57
58 int i1 = s1.lastIndexOf('-');
59 int i2 = s2.lastIndexOf('-');
60
61 // Specific cases, unvalid Strings
62 if (i1 < 0)
63 if (i2 < 0)
64 return s1.compareTo(s2);
65 else
66 return 1;
67 else if (i2 < 0)
68 return -1;
69
70 String aName = s1.substring(0, s1.lastIndexOf('-'));
71 String aVersion = s1.substring(s1.lastIndexOf('-'));
72
73 String bName = s2.substring(0, s2.lastIndexOf('-'));
74 String bVersion = s2.substring(s2.lastIndexOf('-'));
75
76 result = aName.compareTo(bName);
77 if (result != 0)
78 return result;
79 else
80 return vc.compare(viewer, aVersion, bVersion);
81 }
82 }