View Javadoc

1   package org.kuali.common.util;
2   
3   import org.apache.commons.lang3.StringUtils;
4   
5   public class VersionUtils {
6   
7   	public static final String MAVEN_SNAPSHOT_TOKEN = "SNAPSHOT";
8   	private static final String[] DELIMITERS = new String[] { ".", "-" };
9   	private static final String SEPARATOR_CHARS = Str.toString(DELIMITERS);
10  
11  	/**
12  	 * Return true if <code>version</code> ends with <code>-SNAPSHOT</code> or <code>.SNAPSHOT</code> (case insensitive).
13  	 */
14  	public static final boolean isSnapshot(String version) {
15  		for (String delimiter : DELIMITERS) {
16  			String suffix = delimiter + MAVEN_SNAPSHOT_TOKEN;
17  			if (StringUtils.endsWithIgnoreCase(version, suffix)) {
18  				return true;
19  			}
20  		}
21  		return false;
22  	}
23  
24  	/**
25  	 * Return <code>version</code> with <code>.SNAPSHOT</code> or <code>-SNAPSHOT</code> removed from the end (if present)
26  	 *
27  	 * <pre>
28  	 * 1.0.0-SNAPSHOT returns 1.0.0
29  	 * 1.0.0.SNAPSHOT returns 1.0.0
30  	 * 1.0.0          returns 1.0.0
31  	 * 1.0.0SNAPSHOT  returns 1.0.0SNAPSHOT
32  	 * </pre>
33  	 */
34  	public static final String trimSnapshot(String version) {
35  		if (isSnapshot(version)) {
36  			int length = MAVEN_SNAPSHOT_TOKEN.length() + 1;
37  			return StringUtils.left(version, version.length() - length);
38  		} else {
39  			return version;
40  		}
41  	}
42  
43  	/**
44  	 * Parse a <code>Version</code> object from the <code>version</code> string. The logic here is crudely simple. First
45  	 * <code>SNAPSHOT</code> is trimmed off the end of the string (if it exists). Whatever remains is then split into tokens using
46  	 * <code>.</code> and <code>-</code> as delimiters. The first 3 tokens encountered are <code>major</code>, <code>minor</code>, and
47  	 * <code>incremental</code>, respectively. Anything after that is the <code>qualifier</code>
48  	 */
49  	public static final Version getVersion(String version) {
50  		boolean snapshot = isSnapshot(version);
51  		String trimmed = trimSnapshot(version);
52  		Version v = new Version();
53  		v.setTrimmed(trimmed);
54  		v.setSnapshot(snapshot);
55  		String[] tokens = StringUtils.split(trimmed, SEPARATOR_CHARS);
56  		if (tokens.length > 0) {
57  			v.setMajor(tokens[0]);
58  		}
59  		if (tokens.length > 1) {
60  			v.setMinor(tokens[1]);
61  		}
62  		if (tokens.length > 2) {
63  			v.setIncremental(tokens[2]);
64  		}
65  		String qualifier = getQualifier(trimmed, tokens);
66  		v.setQualifier(qualifier);
67  		return v;
68  	}
69  
70  	protected static final String getQualifier(String trimmed, String[] tokens) {
71  		if (tokens.length < 4) {
72  			return null;
73  		}
74  		int pos = tokens[0].length() + 1 + tokens[1].length() + 1 + tokens[2].length() + 1;
75  		return trimmed.substring(pos);
76  	}
77  
78  }