1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.util;
21
22 import java.util.StringTokenizer;
23
24 /***
25 * This class can parse an compare (software) versions.
26 */
27 public class VersionParser implements Comparable {
28
29 private String version;
30 /***
31 * Constructs a new version parser that parses <code>version</code>.
32 */
33 public VersionParser(String version)
34 {
35 this.version = version;
36 }
37
38 /***
39 * Compares version <code>v1</code> with version <code>v2</code>.
40 *
41 * @return 1, if v1 is more recent; 0, if v1 is equal to v2; -1, if v2
42 * is more recent
43 * @see #compareTo(Object)
44 */
45 public static int compare(String v1, String v2)
46 {
47 int result = (new VersionParser(v1)).compareTo(new VersionParser(v2));
48 return result;
49 }
50
51 /***
52 * Compares this VersionParser to <code>o</code>.
53 *
54 * @return 1, if v1 is more recent; 0, if v1 is equal to v2; -1, if v2
55 * is more recent
56 */
57 public int compareTo(Object o)
58 {
59 VersionParser vp = (VersionParser)o;
60
61 StringTokenizer left = new StringTokenizer(version, ".-_: ");
62 StringTokenizer right = new StringTokenizer(vp.version, ".-_: ");
63
64 int result = 0;
65 while (result == 0) {
66
67 if (!left.hasMoreTokens() && !right.hasMoreTokens()) {
68 return 0;
69 }
70 else if (!right.hasMoreTokens()) {
71 return 1;
72 }
73 else if (!left.hasMoreTokens()) {
74 return -1;
75 }
76
77 result = compareTokens(left.nextToken(), right.nextToken());
78 }
79 return result;
80 }
81
82 private static int compareTokens(String left, String right)
83 {
84 int leftNumber = getNumberPrefix(left);
85 int rightNumber = getNumberPrefix(right);
86
87 int result = leftNumber - rightNumber;
88 if (result != 0) {
89 return result;
90 }
91
92 return left.compareTo(right);
93 }
94
95 private static int getNumberPrefix(String s)
96 {
97 int i = 0;
98 while (i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') {
99 i++;
100 }
101 return (i > 0) ? Integer.parseInt(s.substring(0, i)) : -1;
102 }
103
104 public String toString()
105 {
106 return version;
107 }
108
109 }
110