openrat-java-client

Unnamed repository; edit this file 'description' to name the repository.
git clone http://git.code.weiherhei.de/openrat-java-client.git
Log | Files | Refs

Version.java (1428B)


      1 package de.openrat.client;
      2 
      3 /**
      4  * Checking and comparing versions.
      5  *
      6  * @source https://stackoverflow.com/questions/198431/how-do-you-compare-two-version-strings-in-java
      7  */
      8 public class Version implements Comparable<Version> {
      9 
     10 	private String version;
     11 
     12 	public final String get() {
     13 		return this.version;
     14 	}
     15 
     16 	public Version(String version) {
     17 		if (version == null)
     18 			throw new IllegalArgumentException("Version can not be null");
     19 		if (!version.matches("[0-9]+(\\.[0-9]+)*"))
     20 			throw new IllegalArgumentException("Invalid version format");
     21 		this.version = version;
     22 	}
     23 
     24 	@Override
     25 	public int compareTo(Version that) {
     26 		if (that == null)
     27 			return 1;
     28 		String[] thisParts = this.get().split("\\.");
     29 		String[] thatParts = that.get().split("\\.");
     30 		int length = Math.max(thisParts.length, thatParts.length);
     31 		for (int i = 0; i < length; i++) {
     32 			int thisPart = i < thisParts.length ?
     33 					Integer.parseInt(thisParts[i]) : 0;
     34 			int thatPart = i < thatParts.length ?
     35 					Integer.parseInt(thatParts[i]) : 0;
     36 			if (thisPart < thatPart)
     37 				return -1;
     38 			if (thisPart > thatPart)
     39 				return 1;
     40 		}
     41 		return 0;
     42 	}
     43 
     44 	@Override
     45 	public boolean equals(Object that) {
     46 		if (this == that)
     47 			return true;
     48 		if (that == null)
     49 			return false;
     50 		if (this.getClass() != that.getClass())
     51 			return false;
     52 		return this.compareTo((Version) that) == 0;
     53 	}
     54 
     55 
     56 	@Override
     57 	public String toString() {
     58 		return "version:" + get();
     59 	}
     60 }
     61