1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.core.api.util;
17
18
19 import org.apache.commons.lang.StringUtils;
20
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23
24
25
26
27
28
29
30
31 public class VersionHelper {
32
33
34 private static final Pattern extractVersion = Pattern.compile("(\\D*)((\\d*\\.?)+)(\\D*)");
35
36
37 private static final Pattern splitVersion = Pattern.compile("\\.");
38
39
40
41
42
43
44
45
46
47 public static int compareVersion(String versionOne, String versionTwo) {
48 try {
49 return compareVersionInt(versionOne, versionTwo);
50 } catch (IllegalArgumentException iae) {
51 return -1;
52 }
53
54 }
55
56 private static int compareVersionInt(String versionOne, String versionTwo) throws IllegalArgumentException {
57
58
59 if (StringUtils.isBlank(versionOne) || StringUtils.isBlank(versionTwo)) {
60 throw new IllegalArgumentException("Invalid argument");
61 }
62
63 Matcher m1 = extractVersion.matcher(versionOne);
64 Matcher m2 = extractVersion.matcher(versionTwo);
65
66 if (!m1.matches() || !m2.matches()) {
67 throw new IllegalArgumentException("Unable to extract version number from string using regex");
68 }
69
70
71
72
73 String sanitizedVOne = versionOne.substring(m1.start(2), m1.end(2));
74 String sanitizedVTwo = versionTwo.substring(m2.start(2), m2.end(2));
75
76
77
78
79 String[] oneDigits = splitVersion.split(sanitizedVOne);
80 String[] twoDigits = splitVersion.split(sanitizedVTwo);
81
82
83
84 int length=0;
85 if (oneDigits.length<twoDigits.length) {
86 length=oneDigits.length;
87 } else {
88 length=twoDigits.length;
89 }
90
91 for(int i=0; i<length; i++) {
92 Integer intOne = Integer.valueOf(oneDigits[i]);
93 Integer intTwo = Integer.valueOf(twoDigits[i]);
94 Integer compare = intOne.compareTo(intTwo);
95 if (compare < 0) {
96 return -1;
97 }
98 else if (compare > 0) {
99 return 1;
100 }
101 }
102 if (oneDigits.length<twoDigits.length) {
103 return -1;
104 }
105 if (oneDigits.length==twoDigits.length) {
106 return 0;
107 }
108 return 1;
109
110 }
111
112
113 }
114
115