1 19 package org.objectweb.carol.cmi; 20 21 import java.io.DataInput ; 22 import java.io.DataOutput ; 23 import java.io.IOException ; 24 import java.io.Serializable ; 25 import java.util.Arrays ; 26 27 31 public class ClusterId implements Serializable { 32 private static WeakCache wc = new WeakCache(); 33 private transient byte id[]; 34 private transient int hash = 0; 35 private transient String str; 36 37 private ClusterId() { 38 } 39 40 private ClusterId(byte id[]) { 41 if (id.length > Short.MAX_VALUE) { 42 throw new IllegalArgumentException ("Too long array for a cluster ID"); 43 } 44 this.id = id; 45 redoHash(); 46 } 47 48 public static ClusterId toClusterId(byte[] id) { 49 ClusterId cid = new ClusterId(id); 50 return (ClusterId) wc.getCached(cid); 51 } 52 53 private void redoHash() { 54 int h = 0; 55 int l = id.length; 56 int n = 1; 57 for (int i=0; i<l; i++) { 58 h += id[i] * n; 59 n *= 31; 60 } 61 hash = h; 62 } 63 64 public int hashCode() { 65 return hash; 66 } 67 68 public boolean match(byte ar[]) { 69 return Arrays.equals(id, ar); 70 } 71 72 public boolean equals(Object o) { 73 if (o instanceof ClusterId) { 74 ClusterId i = (ClusterId)o; 75 return match(i.id); 76 } 77 return false; 78 } 79 80 84 public String toString() { 85 if (str != null) return str; 86 String s = ""; 87 int i; 88 for (i = 0; i < id.length; i++) { 89 int n = id[i]; 90 if (n < 0) { 91 n += 256; 92 } 93 if (i > 0) { 94 s += "-"; 95 } 96 s += n; 97 } 98 str = s; 99 return s; 100 } 101 102 public void write(DataOutput out) throws IOException { 110 out.writeShort(id.length); 111 out.write(id); 112 } 113 114 public static ClusterId read(DataInput in) throws IOException { 115 int l = in.readShort(); 116 byte[] a = new byte[l]; 117 in.readFully(a); 118 ClusterId id = new ClusterId(); 119 id.id = a; 120 id.redoHash(); 121 return (ClusterId) wc.getCached(id); 122 } 123 124 private void writeObject(java.io.ObjectOutputStream out) 125 throws IOException { 126 out.writeShort(id.length); 127 out.write(id, 0, id.length); 128 } 129 130 private void readObject(java.io.ObjectInputStream in) 131 throws IOException , ClassNotFoundException { 132 int l = in.readShort(); 133 id = new byte[l]; 134 in.readFully(id); 135 redoHash(); 136 } 137 } 138 | Popular Tags |