1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.microemu.app.util;
28
29 import java.util.Enumeration;
30 import java.util.Iterator;
31 import java.util.ListIterator;
32 import java.util.Stack;
33
34 import nanoxml.XMLElement;
35
36
37
38
39
40
41
42 public class MRUList implements XMLItem {
43
44 private static final long serialVersionUID = 1L;
45
46 private static final int MAXCAPACITY_DEFAULT = 10;
47
48 protected int maxCapacity = MAXCAPACITY_DEFAULT;
49
50 private Stack items = new Stack
51
52 private String itemsName;
53
54 private Class classXMLItem;
55
56 private MRUListListener listener;
57
58 private boolean modified = true;
59
60 public MRUList(Class classXMLItem, String itemsName) {
61 this.classXMLItem = classXMLItem;
62 this.itemsName = itemsName;
63 }
64
65 public Object push(Object item) {
66 if (!(item instanceof XMLItem)) {
67 throw new ClassCastException(item.getClass().getName());
68 }
69 modified = true;
70 if (items.size() > maxCapacity) {
71 items.pop();
72 }
73 items.remove(item);
74 if (items.empty()) {
75 items.add(item);
76 } else {
77 items.insertElementAt(item, 0);
78 }
79 fireListener(item);
80 return item;
81 }
82
83 private void fireListener(Object item) {
84 if (this.listener != null) {
85 this.listener.listItemChanged(item);
86 }
87
88 }
89
90 public void setListener(MRUListListener l) {
91 if (this.listener != null) {
92 throw new IllegalArgumentException();
93 }
94 this.listener = l;
95 }
96
97 public int getMaxCapacity() {
98 return maxCapacity;
99 }
100
101 public void setMaxCapacity(int maxCapacity) {
102 this.maxCapacity = maxCapacity;
103 }
104
105 public void save(XMLElement xml) {
106 if (!modified) {
107 return;
108 }
109 xml.removeChildren();
110 xml.setAttribute("maxCapacity", String.valueOf(maxCapacity));
111 for (Iterator iter = items.iterator(); iter.hasNext();) {
112 XMLItem element = (XMLItem) iter.next();
113 element.save(xml.addChild(itemsName));
114 }
115 modified = false;
116 }
117
118 public void read(XMLElement xml) {
119 modified = false;
120 items.removeAllElements();
121 this.maxCapacity = xml.getIntAttribute("maxCapacity", MAXCAPACITY_DEFAULT);
122 for (Enumeration en = xml.enumerateChildren(); en.hasMoreElements();) {
123 XMLElement xmlChild = (XMLElement) en.nextElement();
124 if (xmlChild.getName().equals(itemsName)) {
125 try {
126 XMLItem element = (XMLItem) classXMLItem.newInstance();
127 element.read(xmlChild);
128 items.add(element);
129 } catch (InstantiationException e) {
130 throw new RuntimeException(e);
131 } catch (IllegalAccessException e) {
132 throw new RuntimeException(e);
133 }
134 }
135 }
136
137 if (!items.empty()) {
138
139 for (ListIterator iter = items.listIterator(items.size()); iter.hasPrevious();) {
140 XMLItem element = (XMLItem) iter.previous();
141 fireListener(element);
142 }
143 }
144 }
145
146 }