/src/main/java/uk/ac/cam/ch/ami/AmiObject.java

https://bitbucket.org/jat45/ami · Java · 84 lines · 57 code · 18 blank · 9 comment · 11 complexity · 5a56a78ffc0afea41e347c45fba19c83 MD5 · raw file

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