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

Last change on this file since 5040 was 4674, checked in by jmt12, 21 years ago

* empty log message *

  • Property svn:keywords set to Author Date Id Revision
File size: 19.6 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.println("[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, true);
157 }
158
159/** Recover the metadata associated with a particular file excluding folder level metadata. Note that this call is synchronized, so that all of the data holders don't need to be. */
160 public synchronized ArrayList getMetadataOnly(File file) {
161 return getMetadata(file, false, false);
162 }
163
164 public synchronized ArrayList getMetadata(File file, ElementWrapper element) {
165 ArrayList metadata = getMetadata(file, false, true);
166 ArrayList values = new ArrayList();
167 for(int i = 0; i < metadata.size(); i++) {
168 Metadata data = (Metadata) metadata.get(i);
169 if(element.equals(data.getElement())) {
170 values.add(data.getValue());
171 }
172 }
173 if(values.size() > 0) {
174 Collections.sort(values);
175 }
176 return values;
177 }
178
179 private ArrayList getMetadata(File file, boolean remove, boolean append_folder_level) {
180 ArrayList metadata = null;
181 String filename = null;
182 if(file.isFile()) {
183 filename = file.getName();
184 file = file.getParentFile();
185 }
186 GDMDocument document = getDocument(file);
187 if(document != null) {
188 metadata = document.getMetadata(filename, remove, metadata, file, append_folder_level);
189 document = null;
190 }
191 return metadata;
192 }
193
194 public synchronized ArrayList getAllMetadata(File file) { // boolean remove) {
195 ///ystem.err.println("getMetadata(" + file.getAbsolutePath() + ")");
196 ArrayList metadata = null;
197 // Build up a list of all the metadata xml files we have to check for metadata.
198 ArrayList search_files = new ArrayList();
199 String filename = null;
200 File start_file = file;
201 if(file.isFile()) {
202 filename = file.getName();
203 start_file = file.getParentFile();
204 }
205 File collection_dir = new File(Gatherer.c_man.getCollectionDirectory());
206 ///ystem.err.println("Collection directory = " + collection_dir.getAbsolutePath());
207 ///ystem.err.println("Start directory = " + start_file.getAbsolutePath());
208 while(!start_file.equals(collection_dir)) {
209 ///ystem.err.println("Blip!");
210 search_files.add(0, new MetadataXMLFileSearch(start_file, filename));
211 if(filename != null) {
212 filename = start_file.getName() + "/" + filename;
213 }
214 else {
215 filename = start_file.getName() + "/";
216 }
217 start_file = start_file.getParentFile();
218 ///ystem.err.println("Start directory = " + start_file.getAbsolutePath());
219 }
220 // Now search each of these metadata xml for metadata, remembering to accumulate or overwrite as we go along.
221 for(int i = 0; i < search_files.size(); i++) {
222 MetadataXMLFileSearch a_search = (MetadataXMLFileSearch) search_files.get(i);
223 ///ystem.err.println("Search " + a_search.file.getAbsolutePath() + File.separator + "metadata.xml for " + (a_search.filename != null ? a_search.filename : "directory metadata"));
224 // Retrieve the document
225 GDMDocument document = getDocument(a_search.file);
226 if(document != null) {
227 // There is one piece of slight of hand here. You can never remove metadata during a get all metadata.
228 metadata = document.getMetadata(a_search.filename, false, metadata, a_search.file, true);
229 ///ystem.err.println("Current metadata: " + toString(metadata));
230 document = null;
231 }
232 a_search = null;
233 }
234 start_file = null;
235 collection_dir = null;
236 filename = null;
237 search_files.clear();
238 search_files = null;
239 return metadata;
240 }
241
242 public String toString(ArrayList list) {
243 StringBuffer text = new StringBuffer("(");
244 for(int i = 0; list != null && i < list.size(); i++) {
245 text.append((list.get(i)).toString());
246 if(i < list.size() - 1) {
247 text.append(", ");
248 }
249 }
250 text.append(")");
251 return text.toString();
252 }
253
254 private class MetadataXMLFileSearch {
255 public File file;
256 public String filename;
257 public MetadataXMLFileSearch(File file, String filename) {
258 this.file = file;
259 this.filename = filename;
260 }
261 }
262
263 /** 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.
264 * @param event A <strong>MSMEvent</strong> containing details of the event that caused this message to be fired.
265 * @see org.greenstone.gatherer.msm.GDMDocument
266 * @see org.greenstone.gatherer.msm.Metadata
267 * @see org.greenstone.gatherer.util.HashMap3D
268 */
269 public synchronized void metadataChanged(MSMEvent event) {
270 ///ystem.err.println("Recieved Event: " + event.toString());
271 File file = event.getFile();
272 if(file == null) {
273 FileNode record = event.getRecord();
274 file = record.getFile();
275 }
276 Metadata new_metadata = event.getNewMetadata();
277 Metadata old_metadata = event.getOldMetadata();
278 // These metadata objects may be new instances of metadata objects that already exist. Replace them if they are.
279 new_metadata = checkCache(new_metadata);
280 old_metadata = checkCache(old_metadata);
281 // Now apply the change to the document in question.
282 GDMDocument metadata_xml = getDocument(file);
283 if(metadata_xml != null) {
284 if(old_metadata != null) {
285 // File level
286 if(file.isFile()) {
287 metadata_xml.removeMetadata(file.getName(), old_metadata);
288 }
289 // Folder level
290 else {
291 metadata_xml.removeMetadata(null, old_metadata);
292 }
293 }
294 if(new_metadata != null) {
295 // File level
296 if(file.isFile()) {
297 metadata_xml.addMetadata(file.getName(), new_metadata);
298 }
299 else {
300 metadata_xml.addMetadata(null, new_metadata);
301 }
302 }
303 }
304 }
305
306 public ArrayList removeMetadata(File file) {
307 return getMetadata(file, true, false);
308 }
309
310 /** Causes all currently loaded GDMDocuments to write themselves out.
311 * @see org.greenstone.gatherer.msm.GDMDocument
312 */
313 public void save() {
314 Iterator iterator = keySet().iterator();
315 while(iterator.hasNext()) {
316 File file = (File) iterator.next();
317 GDMDocument document = (GDMDocument) get(file);
318 if(!document.isUpToDate()) {
319 // First purge any old references.
320 document.getMetadata(null, false, null, null, true);
321 // Now write the xml
322 Utility.export(document.getDocument(), file);
323 document.setUpToDate(true);
324 }
325 }
326 }
327 /** Used to cause the document associated with a particular file to write the latest copy of itself to disk. */
328 public void save(FileNode node) {
329 File file = node.getFile();
330 if(file != null && file.isFile()) {
331 GDMDocument document = getDocument(file);
332 File xml_file;
333 if(file.isFile()) {
334 xml_file = new File(file.getParentFile(), "metadata.xml");
335 }
336 else {
337 xml_file = new File(file, "metadata.xml");
338 }
339 if(document != null && !document.isUpToDate()) {
340 // First purge any old references.
341 document.getMetadata(null, false, null, null, true);
342 // Now write the xml
343 Utility.export(document.getDocument(), xml_file);
344 document.setUpToDate(true);
345 }
346 xml_file = null;
347 document = null;
348 }
349 file = null;
350 }
351
352 /** 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.
353 * @param event A <strong>MSMEvent</strong> containing details of the event that caused this message to be fired.
354 */
355 public void setChanged(MSMEvent event) {
356 for(Iterator values = values().iterator(); values.hasNext(); ) {
357 GDMDocument document = (GDMDocument) values.next();
358 document.setUpToDate(false);
359 document = null;
360 }
361 }
362 /** 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.
363 * @param event A <strong>MSMEvent</strong> containing details of the event that caused this message to be fired.
364 */
365 public void valueChanged(MSMEvent event) {}
366
367 public void waitUntilComplete() {
368 gdm_loader.waitUntilComplete();
369 }
370
371 private Metadata checkCache(Metadata metadata) {
372 if(metadata != null) {
373 ///ystem.err.println("Search for " + metadata.toString());
374 if(metadata_cache.contains(metadata.getElement(), metadata.getValueNode())) {
375 metadata = (Metadata) metadata_cache.get(metadata.getElement(), metadata.getValueNode());
376 }
377 }
378 return metadata;
379 }
380
381 /** 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. */
382 private class GDMLoader
383 extends Thread {
384 private boolean complete = false;
385 public void run() {
386 // Can't open a collections metadata when the collection isn't open!
387 while(!Gatherer.c_man.ready()) {
388 try {
389 wait(100);
390 }
391 catch(Exception error) {
392 }
393 }
394 // Now for each non-file directory in the tree, ask it to load its metadata
395 ArrayList remaining = new ArrayList();
396 remaining.add((FileNode)Gatherer.c_man.getRecordSet().getRoot());
397 int remaining_size = 0;
398 while((remaining_size = remaining.size()) > 0) {
399 FileNode record = (FileNode) remaining.remove(remaining_size - 1);
400 if(!record.isLeaf()) {
401 ///atherer.println("Retrieving metadata.xml for " + record);
402 getMetadata(record.getFile());
403 for(int i = 0; i < record.getChildCount(); i++) {
404 remaining.add(record.getChildAt(i));
405 }
406 }
407 record = null;
408 }
409 remaining = null;
410 complete = true;
411 }
412 public void waitUntilComplete() {
413 try {
414 while(!complete) {
415 sleep(100); // 1 second hopefully.
416 }
417 }
418 catch(Exception error) {
419 Gatherer.printStackTrace(error);
420 }
421 }
422 }
423}
Note: See TracBrowser for help on using the repository browser.