source: trunk/gli/src/org/greenstone/gatherer/msm/GDMManager.java@ 4365

Last change on this file since 4365 was 4365, checked in by mdewsnip, 21 years ago

Fixed tabbing.

  • Property svn:keywords set to Author Date Id Revision
File size: 19.2 KB
Line 
1package org.greenstone.gatherer.msm;
2/**
3 *#########################################################################
4 *
5 * A component of the Gatherer application, part of the Greenstone digital
6 * library suite from the New Zealand Digital Library Project at the
7 * University of Waikato, New Zealand.
8 *
9 * <BR><BR>
10 *
11 * Author: John Thompson, Greenstone Digital Library, University of Waikato
12 *
13 * <BR><BR>
14 *
15 * Copyright (C) 1999 New Zealand Digital Library Project
16 *
17 * <BR><BR>
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * <BR><BR>
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * <BR><BR>
32 *
33 * You should have received a copy of the GNU General Public License
34 * along with this program; if not, write to the Free Software
35 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
36 *########################################################################
37 */
38import java.io.*;
39import java.util.*;
40import javax.swing.tree.*;
41import org.greenstone.gatherer.Gatherer;
42import org.greenstone.gatherer.file.FileNode;
43import org.greenstone.gatherer.msm.ElementWrapper;
44import org.greenstone.gatherer.msm.GDMDocument;
45import org.greenstone.gatherer.msm.GDMParser;
46import org.greenstone.gatherer.msm.Metadata;
47import org.greenstone.gatherer.msm.MSMEvent;
48import org.greenstone.gatherer.msm.MSMListener;
49import org.greenstone.gatherer.util.HashMap3D;
50import org.greenstone.gatherer.util.Utility;
51import org.greenstone.gatherer.valuetree.GValueModel;
52import org.greenstone.gatherer.valuetree.GValueNode;
53import org.w3c.dom.*;
54/** This object manages the metadata attached to file records. By storing all of the metadata in one place you garner several advantages. Firstly only one copy of each metadata object is retained, all actual entries are converted to references. Next you can immediately determine what metadata is assigned to an entire directory, thus the metadata.xml files can be built more effeciently (whereas the current 'optimal' method uses recursion through the tree contents). Finally, and perhaps most importantly, it allows for dynamic 'on demand' lookup of metadata. This is especially necessary with large collections, where the raw, unconnected metadata files could range into the tens of megabytes of memory and require hundreds of megabytes to read by in using serialization. Dynamic loading allows you to connect the metadata objects on load, reducing value node paths (possibly of hundreds of characters) down to a single reference pointer! At the very worst this object uses far less memory than the current method, and given that the current method is completely incapable of handling large collections, is necessary. The trade off of course is in time needed to load metadata.xml on demand, the worst possible case being the user selecting the root node of the collection tree of a large collection immediately after opening the collection. The subsequent attempt to build the metadata table will result in the metadata being loaded for every single file. But since this process is sequential and a small cache of metadata.xml files is implemented, and given that the table will actually be build on a separate thread, the wait should not be too arduous.<BR>
55 As for the size of the GDMParser cache, I was at first tempted to put around five. However after analysis of cache usage, I determined that no gain occured because of caching (in fact if everythings working as it should there should only ever be one call for a certain metadata.xml).
56*/
57public class GDMManager
58 extends HashMap
59 implements MSMListener {
60 /** A list of the known metadata instances, thus we only store one of each unique metadata, and reference the rest. */
61 static public HashMap3D metadata_cache = null;
62 /** The root file node. */
63 private TreeNode root = null;
64 /** The threaded object responsible for loading all of the existing metadata.xml files prior to any save action. This is necessary so that hierarchy indexes within the metadata.xml files stay fresh. */
65 private GDMLoader gdm_loader = null;
66 static final private String METADATA_XML = "metadata.xml";
67 /** Constructor. */
68 public GDMManager() {
69 super();
70 this.metadata_cache = new HashMap3D(Gatherer.c_man.getCollection().msm.getSize());
71 // Connect
72 Gatherer.c_man.getCollection().msm.addMSMListener(this);
73 // Now create and start the synchronous GDM loader.
74 gdm_loader = new GDMLoader();
75 gdm_loader.start();
76 ///atherer.println("New GDMManager created.");
77 }
78
79 /** This may seem a little odd but this method doesn't add the given metadata directly, instead calling fireMetadataChanged in MetadataSetManager so as to recursively add metadata if necessary, and to ensure that all listeners who are interested in data change (such as the Metadata Table and Save listeners) can be up to date. */
80 public void addMetadata(FileNode node, ArrayList metadatum) {
81 for(int i = 0; i < metadatum.size(); i++) {
82 Metadata metadata = (Metadata) metadatum.get(i);
83 Gatherer.c_man.getCollection().msm.fireMetadataChanged(node, (Metadata)null, metadata);
84 }
85 }
86 /** Destructor necessary for clean exit, subsequent to saving of metadata.xml files.
87 * @see org.greenstone.gatherer.Gatherer
88 * @see org.greenstone.gatherer.collection.CollectionManager
89 * @see org.greenstone.gatherer.msm.GDMParser
90 * @see org.greenstone.gatherer.msm.MetadataSetManager
91 */
92 public void destroy() {
93 // Destroy all the cached documents.
94 /*
95 Iterator iterator = keySet().iterator();
96 while(iterator.hasNext()) {
97 File file = (File) iterator.next();
98 GDMDocument document = (GDMDocument) get(file);
99 document.destroy(file);
100 }
101 */
102 // Deregister as listener
103 Gatherer.c_man.getCollection().msm.removeMSMListener(this);
104 // Deallocate all data members
105 metadata_cache.clear();
106 metadata_cache = null;
107 // Finally clear self
108 clear();
109 // Done!
110 }
111 /** Method that is called whenever an element within a set is changed or modified. Ensure all cached GDMDocuments are marked as stale.
112 * @param event A <strong>MSMEvent</strong> containing details of the event that caused this message to be fired.
113 */
114 public void elementChanged(MSMEvent event) {
115 for(Iterator values = values().iterator(); values.hasNext(); ) {
116 GDMDocument document = (GDMDocument) values.next();
117 document.setUpToDate(false);
118 document = null;
119 }
120 }
121 /** Retrieve the GreenstoneMetadataDocument that is associated with a certain file. If the document is in cache returns it. If the document exists but isn't in cache loads, caches, then returns it. Otherwise it creates a brand new document, caches it, then returns it.
122 * @see org.greenstone.gatherer.msm.GDMParser
123 */
124 public GDMDocument getDocument(File file) {
125 ///ystem.err.println("Get the GDMDocument for " + file.getAbsolutePath());
126 GDMDocument metadata_xml = null;
127 // Determine the name of the target files metadata.xml file.
128 File metadata_file = null;
129 if(file.isFile()) {
130 metadata_file = new File(file.getParentFile(), METADATA_XML);
131 }
132 else {
133 metadata_file = new File(file, METADATA_XML);
134 }
135 // Then try to retrieve it from cache. First we consider the case of a cache hit.
136 if(containsKey(metadata_file)) {
137 metadata_xml = (GDMDocument) get(metadata_file);
138 }
139 else {
140 // Now the two potential cache misses. The first requires us to load an existing metadata.xml
141 if(metadata_file.exists()) {
142 metadata_xml = new GDMDocument(metadata_file);
143 }
144 // The final case is where no current metadata.xml exists. Create a new one just by creating a new GDMDocument.
145 else {
146 metadata_xml = new GDMDocument();
147 }
148 put(metadata_file, metadata_xml);
149 //gatherer.debug(null, "[0ms]\tCached " + metadata_file);
150 }
151 return metadata_xml;
152 }
153
154 /** Recover the metadata associated with a particular file. Note that this call is synchronized, so that all of the data holders don't need to be. */
155 public synchronized ArrayList getMetadata(File file) {
156 return getMetadata(file, false);
157 }
158
159 public synchronized ArrayList getMetadata(File file, ElementWrapper element) {
160 ArrayList metadata = getMetadata(file, false);
161 ArrayList values = new ArrayList();
162 for(int i = 0; i < metadata.size(); i++) {
163 Metadata data = (Metadata) metadata.get(i);
164 if(element.equals(data.getElement())) {
165 values.add(data.getValue());
166 }
167 }
168 if(values.size() > 0) {
169 Collections.sort(values);
170 }
171 return values;
172 }
173
174 private ArrayList getMetadata(File file, boolean remove) {
175 ArrayList metadata = null;
176 String filename = null;
177 if(file.isFile()) {
178 filename = file.getName();
179 file = file.getParentFile();
180 }
181 GDMDocument document = getDocument(file);
182 if(document != null) {
183 metadata = document.getMetadata(filename, remove, metadata, file);
184 document = null;
185 }
186 return metadata;
187 }
188
189 public synchronized ArrayList getAllMetadata(File file) { // boolean remove) {
190 ///ystem.err.println("getMetadata(" + file.getAbsolutePath() + ")");
191 ArrayList metadata = null;
192 // Build up a list of all the metadata xml files we have to check for metadata.
193 ArrayList search_files = new ArrayList();
194 String filename = null;
195 File start_file = file;
196 if(file.isFile()) {
197 filename = file.getName();
198 start_file = file.getParentFile();
199 }
200 File collection_dir = new File(Gatherer.c_man.getCollectionDirectory());
201 ///ystem.err.println("Collection directory = " + collection_dir.getAbsolutePath());
202 ///ystem.err.println("Start directory = " + start_file.getAbsolutePath());
203 while(!start_file.equals(collection_dir)) {
204 ///ystem.err.println("Blip!");
205 search_files.add(0, new MetadataXMLFileSearch(start_file, filename));
206 if(filename != null) {
207 filename = start_file.getName() + "/" + filename;
208 }
209 else {
210 filename = start_file.getName() + "/";
211 }
212 start_file = start_file.getParentFile();
213 ///ystem.err.println("Start directory = " + start_file.getAbsolutePath());
214 }
215 // Now search each of these metadata xml for metadata, remembering to accumulate or overwrite as we go along.
216 for(int i = 0; i < search_files.size(); i++) {
217 MetadataXMLFileSearch a_search = (MetadataXMLFileSearch) search_files.get(i);
218 ///ystem.err.println("Search " + a_search.file.getAbsolutePath() + File.separator + "metadata.xml for " + (a_search.filename != null ? a_search.filename : "directory metadata"));
219 // Retrieve the document
220 GDMDocument document = getDocument(a_search.file);
221 if(document != null) {
222 // There is one piece of slight of hand here. You can never remove metadata during a get all metadata.
223 metadata = document.getMetadata(a_search.filename, false, metadata, a_search.file);
224 ///ystem.err.println("Current metadata: " + toString(metadata));
225 document = null;
226 }
227 a_search = null;
228 }
229 start_file = null;
230 collection_dir = null;
231 filename = null;
232 search_files.clear();
233 search_files = null;
234 return metadata;
235 }
236
237 public String toString(ArrayList list) {
238 StringBuffer text = new StringBuffer("(");
239 for(int i = 0; list != null && i < list.size(); i++) {
240 text.append((list.get(i)).toString());
241 if(i < list.size() - 1) {
242 text.append(", ");
243 }
244 }
245 text.append(")");
246 return text.toString();
247 }
248
249 private class MetadataXMLFileSearch {
250 public File file;
251 public String filename;
252 public MetadataXMLFileSearch(File file, String filename) {
253 this.file = file;
254 this.filename = filename;
255 }
256 }
257
258 /** Called whenever the metadata value changes in some way, such as the addition of a new value. This is the only event type we care about, but we care about it a lot. It tells us what metadata to add, remove, etc from the cached metadata.xml files. Note that this method is synchronized so that the data objects don't need to be.
259 * @param event A <strong>MSMEvent</strong> containing details of the event that caused this message to be fired.
260 * @see org.greenstone.gatherer.msm.GDMDocument
261 * @see org.greenstone.gatherer.msm.Metadata
262 * @see org.greenstone.gatherer.util.HashMap3D
263 */
264 public synchronized void metadataChanged(MSMEvent event) {
265 System.err.println("Recieved Event: " + event.toString());
266 File file = event.getFile();
267 if(file == null) {
268 FileNode record = event.getRecord();
269 file = record.getFile();
270 }
271 Metadata new_metadata = event.getNewMetadata();
272 Metadata old_metadata = event.getOldMetadata();
273 // These metadata objects may be new instances of metadata objects that already exist. Replace them if they are.
274 new_metadata = checkCache(new_metadata);
275 old_metadata = checkCache(old_metadata);
276 // Now apply the change to the document in question.
277 GDMDocument metadata_xml = getDocument(file);
278 if(metadata_xml != null) {
279 if(old_metadata != null) {
280 // File level
281 if(file.isFile()) {
282 metadata_xml.removeMetadata(file.getName(), old_metadata);
283 }
284 // Folder level
285 else {
286 metadata_xml.removeMetadata(null, old_metadata);
287 }
288 }
289 if(new_metadata != null) {
290 // File level
291 if(file.isFile()) {
292 metadata_xml.addMetadata(file.getName(), new_metadata);
293 }
294 else {
295 metadata_xml.addMetadata(null, new_metadata);
296 }
297 }
298 }
299 }
300
301 public ArrayList removeMetadata(File file) {
302 return getMetadata(file, true);
303 }
304
305 /** Causes all currently loaded GDMDocuments to write themselves out.
306 * @see org.greenstone.gatherer.msm.GDMDocument
307 */
308 public void save() {
309 Iterator iterator = keySet().iterator();
310 while(iterator.hasNext()) {
311 File file = (File) iterator.next();
312 GDMDocument document = (GDMDocument) get(file);
313 if(!document.isUpToDate()) {
314 // First purge any old references.
315 document.getMetadata(null, false, null, null, true);
316 // Now write the xml
317 Utility.export(document.getDocument(), file);
318 document.setUpToDate(true);
319 }
320 }
321 }
322 /** Used to cause the document associated with a particular file to write the latest copy of itself to disk. */
323 public void save(FileNode node) {
324 File file = node.getFile();
325 if(file != null && file.isFile()) {
326 GDMDocument document = getDocument(file);
327 File xml_file;
328 if(file.isFile()) {
329 xml_file = new File(file.getParentFile(), "metadata.xml");
330 }
331 else {
332 xml_file = new File(file, "metadata.xml");
333 }
334 if(document != null && !document.isUpToDate()) {
335 // First purge any old references.
336 document.getMetadata(null, false, null, null, true);
337 // Now write the xml
338 Utility.export(document.getDocument(), xml_file);
339 document.setUpToDate(true);
340 }
341 xml_file = null;
342 document = null;
343 }
344 file = null;
345 }
346
347 /** Method that is called whenever the metadata set collection changes in some way, such as the addition of a new set or the merging of two sets. If a set changes, mark all cached GDMDocuments as being stale.
348 * @param event A <strong>MSMEvent</strong> containing details of the event that caused this message to be fired.
349 */
350 public void setChanged(MSMEvent event) {
351 for(Iterator values = values().iterator(); values.hasNext(); ) {
352 GDMDocument document = (GDMDocument) values.next();
353 document.setUpToDate(false);
354 document = null;
355 }
356 }
357 /** Called whenever the value tree of an metadata element changes in some way, such as the addition of a new value. --While the comments below are now obsolete, I'll keep them just to remind me of how easy it is to back yourself into a corner with issues such as caching and persisitant references--. Such an action would require us to painstakingly reload every metadata.xml file using the value model prior to the change, then painstakingly write out each metadata.xml file again using the modified model, but I'm a glutton for punishment so thats ok. The alternative is to not do this and watch in horror as heirarchy references quickly fall into disarray, pointing to the wrong place. This task gets even more complicated by three facts:<br>1. We want to do this is a seperate thread, as we don't want the program to come to a screaming halt while we're updating metadata.xml files.<br>2. We have to prevent any metadata.xml files being removed from cache while we're doing this, as if we encounter these more recently written files their heirarchy references will already be correct and that will balls up our little process. Note that this means the saving process may have to block while pending metadata heirarchy updates are in progress.<br>3. Regarding (2) we don't have to rewrite any metadata.xml files already in cache as they will be correctly written out whenever they happen to be dumped from cache.<br>4. We need the ability to pre-empt the general update to load a user demanded metadata.xml and store it in cache, using the old value tree model as per usual, and<br>5. We have to store a cue of these events, and process them one at a time. Perhaps one day when I'm feeling masacistic I'll figure out someway to merge several updates into one, but for now we have to change the tree one node at a time in order for references to remain correct.<br>Ok, so thats five facts, but you get the gist. Not an easy task, but crucial for accurate storage and recall of metadata heirarchies.
358 * @param event A <strong>MSMEvent</strong> containing details of the event that caused this message to be fired.
359 */
360 public void valueChanged(MSMEvent event) {}
361
362 public void waitUntilComplete() {
363 gdm_loader.waitUntilComplete();
364 }
365
366 private Metadata checkCache(Metadata metadata) {
367 if(metadata != null) {
368 ///ystem.err.println("Search for " + metadata.toString());
369 if(metadata_cache.contains(metadata.getElement(), metadata.getValueNode())) {
370 metadata = (Metadata) metadata_cache.get(metadata.getElement(), metadata.getValueNode());
371 }
372 }
373 return metadata;
374 }
375
376 /** A separately threaded class to load all of the current metadata.xml files. Note that files can still be loaded on demand if they're not already in the cache. Also provides the functionality to block any other thread until the loading is complete, such as is necessary when moving values about in the value tree hierarchy. */
377 private class GDMLoader
378 extends Thread {
379 private boolean complete = false;
380 public void run() {
381 // Can't open a collections metadata when the collection isn't open!
382 while(!Gatherer.c_man.ready()) {
383 try {
384 wait(100);
385 }
386 catch(Exception error) {
387 }
388 }
389 // Now for each non-file directory in the tree, ask it to load its metadata
390 ArrayList remaining = new ArrayList();
391 remaining.add((FileNode)Gatherer.c_man.getRecordSet().getRoot());
392 int remaining_size = 0;
393 while((remaining_size = remaining.size()) > 0) {
394 FileNode record = (FileNode) remaining.remove(remaining_size - 1);
395 if(!record.isLeaf()) {
396 ///atherer.println("Retrieving metadata.xml for " + record);
397 getMetadata(record.getFile());
398 for(int i = 0; i < record.getChildCount(); i++) {
399 remaining.add(record.getChildAt(i));
400 }
401 }
402 record = null;
403 }
404 remaining = null;
405 complete = true;
406 }
407 public void waitUntilComplete() {
408 try {
409 while(!complete) {
410 sleep(100); // 1 second hopefully.
411 }
412 }
413 catch(Exception error) {
414 Gatherer.printStackTrace(error);
415 }
416 }
417 }
418}
Note: See TracBrowser for help on using the repository browser.