001 package jp.osdl.jbento2.analyzer; 002 003 import java.io.Serializable; 004 import java.util.regex.Matcher; 005 import java.util.regex.Pattern; 006 007 /** 008 * Time class represents the time used in JBento. 009 * The value must be formatted as "MILLISECOND" or "MILLISECOND[NANOSECOND]" 010 */ 011 public class Time implements Serializable, Comparable { 012 013 public static final Time ZERO = new Time(0); 014 015 private static final Pattern REGEXP = 016 Pattern.compile("^([0-9]+)(?:\\[([0-9]+)\\])?$"); 017 018 private String value; 019 020 /** 021 * Construct Time instance. 022 * 023 * @param value value 024 * @throws IllegalArgumentException thrown if value has invalid fomat. 025 */ 026 public Time(String value) { 027 if (!REGEXP.matcher(value).matches()) { 028 throw new IllegalArgumentException( 029 "Invalid format. value=" + value); 030 } 031 this.value = value; 032 } 033 034 /** 035 * Construct Time instance. 036 * 037 * @param millitime millitime 038 */ 039 public Time(long millitime) { 040 this.value = String.valueOf(millitime); 041 } 042 043 /** 044 * Returns milliseconds. 045 * 046 * @return milliseconds value. 047 */ 048 public long getMillitime() { 049 Matcher m = REGEXP.matcher(value); 050 m.matches(); 051 String milli = m.group(1); 052 return Long.parseLong(milli); 053 } 054 055 /** 056 * Returns nanoseconds value. 057 * 058 * @return nanoseconds value. 059 * @throws IllegalStateException 060 * thrown if this instance doesn't have nanoseconds. 061 */ 062 public long getNanotime() { 063 Matcher m = REGEXP.matcher(value); 064 m.matches(); 065 String nano = m.group(2); 066 if (nano == null) { 067 throw new IllegalStateException( 068 "This instance doesn't have nanoseconds."); 069 } 070 return Long.parseLong(nano); 071 } 072 073 /** 074 * Returns nanoseconds value. 075 * 076 * @return nanoseconds value. 077 */ 078 public boolean hasNanotime() { 079 Matcher m = REGEXP.matcher(value); 080 m.matches(); 081 return m.group(2) != null; 082 } 083 084 public String toString() { 085 return value; 086 } 087 088 public int compareTo(Object o) { 089 return this.value.compareTo(((Time)o).value); 090 } 091 092 } 093