blob: 90a51c5e18716b88f82f623be85a3b149be8329f [file] [log] [blame]
Tatu Salorantaf15531c2011-12-22 23:00:40 -08001package com.fasterxml.jackson.core.util;
2
3import java.io.*;
4import java.util.regex.Pattern;
5
6import com.fasterxml.jackson.core.Version;
7
8/**
9 * Functionality for supporting exposing of component {@link Version}s.
10 *
11 * @since 1.6
12 */
13public class VersionUtil
14{
15 public final static String VERSION_FILE = "VERSION.txt";
16
17 private final static Pattern VERSION_SEPARATOR = Pattern.compile("[-_./;:]");
18
19 /**
20 * Helper method that will try to load version information for specified
21 * class. Implementation is simple: class loader that loaded specified
22 * class is asked to load resource with name "VERSION" from same
23 * location (package) as class itself had.
24 * If no version information is found, {@link Version#unknownVersion()} is
25 * returned.
26 */
27 public static Version versionFor(Class<?> cls)
28 {
29 InputStream in;
30 Version version = null;
Tatu Salorantae6b25992011-12-28 20:33:45 -080031
Tatu Salorantaf15531c2011-12-22 23:00:40 -080032 try {
33 in = cls.getResourceAsStream(VERSION_FILE);
34 if (in != null) {
35 try {
36 BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
37 version = parseVersion(br.readLine());
38 } finally {
39 try {
40 in.close();
41 } catch (IOException e) {
42 throw new RuntimeException(e);
43 }
44 }
45 }
46 } catch (IOException e) { }
47 return (version == null) ? Version.unknownVersion() : version;
48 }
49
50 public static Version parseVersion(String versionStr)
51 {
52 if (versionStr == null) return null;
53 versionStr = versionStr.trim();
54 if (versionStr.length() == 0) return null;
55 String[] parts = VERSION_SEPARATOR.split(versionStr);
56 // Let's not bother if there's no separate parts; otherwise use whatever we got
57 if (parts.length < 2) {
58 return null;
59 }
60 int major = parseVersionPart(parts[0]);
61 int minor = parseVersionPart(parts[1]);
62 int patch = (parts.length > 2) ? parseVersionPart(parts[2]) : 0;
63 String snapshot = (parts.length > 3) ? parts[3] : null;
64 return new Version(major, minor, patch, snapshot);
65 }
66
67 protected static int parseVersionPart(String partStr)
68 {
69 partStr = partStr.toString();
70 int len = partStr.length();
71 int number = 0;
72 for (int i = 0; i < len; ++i) {
73 char c = partStr.charAt(i);
74 if (c > '9' || c < '0') break;
75 number = (number * 10) + (c - '0');
76 }
77 return number;
78 }
79}