/src/main/java/uk/ac/cam/ch/ami/AmiObject.java
Java | 84 lines | 57 code | 18 blank | 9 comment | 11 complexity | 5a56a78ffc0afea41e347c45fba19c83 MD5 | raw file
1package uk.ac.cam.ch.ami; 2 3import com.thoughtworks.xstream.annotations.XStreamOmitField; 4 5import javax.swing.tree.DefaultMutableTreeNode; 6import java.util.Comparator; 7import java.util.Map; 8import java.util.TreeMap; 9 10/** 11 * Created by IntelliJ IDEA. 12 * User: Matthew 13 * Date: 07-Sep-2010 14 * Time: 16:30:02 15 * To change this template use File | Settings | File Templates. 16 */ 17public class AmiObject { 18 19 public static AmiObject EQUIPMENT = new AmiObject("Equipment"); 20 21 @XStreamOmitField 22 Comparator treeComparator = new CustomEquipmentTreeComparator(); 23 24 // we'll create cache only when needed (in register()) to avoid superfluous empty caches 25 // in the serialized form - most of the objects in the tree are leaf nodes without alpha cache 26 private Map<String, AmiObject> cache = null; 27 28 private final String name; 29 30 private AmiObject(String name) { 31 this.name = name; 32 } 33 34 public String getName() { 35 return name; 36 } 37 38 public String toString() { 39 return name; 40 } 41 42 public AmiObject register(String name) throws IllegalArgumentException { 43 if(cache == null) { cache = new TreeMap<String, AmiObject>(treeComparator); } 44 if (cache.containsKey(name)) { 45 throw new IllegalArgumentException("Duplicate name " + name); 46 } 47 AmiObject amiObject = new AmiObject(name); 48 cache.put(name, amiObject); 49 return amiObject; 50 } 51 52 public AmiObject valueOf(String name) { 53 return cache.get(name); 54 } 55 56 public AmiObject[] values() { 57 return cache.values().toArray(new AmiObject[cache.size()]); 58 } 59 60 public boolean hasChildren(){ 61 if(cache == null) { return false; } 62 if(this.values().length != 0){ 63 return true; 64 } else{ 65 return false; 66 } 67 } 68 69 public static void clearCache(){ 70 if(EQUIPMENT.cache != null) { EQUIPMENT.cache.clear(); } 71 } 72 73 public static DefaultMutableTreeNode buildTreeFrom(AmiObject o) { 74 DefaultMutableTreeNode node=new DefaultMutableTreeNode(o); 75 if(o.hasChildren()) { 76 for(AmiObject amiObject : o.values()) { 77 node.add(buildTreeFrom(amiObject)); 78 } 79 } 80 81 return node; 82 } 83 84}