source: trunk/gli/src/org/greenstone/gatherer/msm/MetadataSetManager.java@ 6045

Last change on this file since 6045 was 5992, checked in by jmt12, 21 years ago

MSMEvents are now created including an integer to specify what user action caused them - thus I am able to differentiate between assigns and replaces later on

  • Property svn:keywords set to Author Date Id Revision
File size: 56.4 KB
Line 
1/**
2 *#########################################################################
3 *
4 * A component of the Gatherer application, part of the Greenstone digital
5 * library suite from the New Zealand Digital Library Project at the
6 * University of Waikato, New Zealand.
7 *
8 * <BR><BR>
9 *
10 * Author: John Thompson, Greenstone Digital Library, University of Waikato
11 *
12 * <BR><BR>
13 *
14 * Copyright (C) 1999 New Zealand Digital Library Project
15 *
16 * <BR><BR>
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
22 *
23 * <BR><BR>
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * <BR><BR>
31 *
32 * You should have received a copy of the GNU General Public License
33 * along with this program; if not, write to the Free Software
34 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35 *########################################################################
36 */
37package org.greenstone.gatherer.msm;
38
39import java.io.*;
40import java.util.*;
41import javax.swing.*;
42import javax.swing.filechooser.*;
43import org.greenstone.gatherer.Configuration;
44import org.greenstone.gatherer.Dictionary;
45import org.greenstone.gatherer.Gatherer;
46import org.greenstone.gatherer.cdm.CommandTokenizer;
47import org.greenstone.gatherer.file.FileNode;
48import org.greenstone.gatherer.gui.MetaEditPrompt;
49import org.greenstone.gatherer.mem.MetadataEditorManager;
50import org.greenstone.gatherer.msm.Declarations;
51import org.greenstone.gatherer.msm.MDSFileFilter;
52import org.greenstone.gatherer.msm.MetadataSet;
53import org.greenstone.gatherer.msm.MSMAction;
54import org.greenstone.gatherer.msm.MSMEvent;
55import org.greenstone.gatherer.msm.MSMPrompt;
56import org.greenstone.gatherer.msm.MSMUtils;
57import org.greenstone.gatherer.valuetree.GValueModel;
58import org.greenstone.gatherer.valuetree.GValueNode;
59import org.greenstone.gatherer.util.MetadataXML;
60import org.greenstone.gatherer.util.Utility;
61import org.apache.xerces.parsers.*;
62import org.apache.xml.serialize.*;
63import org.w3c.dom.*;
64import org.xml.sax.*;
65
66/** This class is responsible for managing all the metadata sets in the collection and for providing methods for manipulating the aforementioned sets contents.
67 * @author John Thompson, Greenstone Digital Library, University of Waikato
68 * @version 2.3b
69 */
70public class MetadataSetManager {
71
72 /** The name of the hidden, or system, metadata set. */
73 static final public String HIDDEN = "hidden";
74
75 /** A mapping from metadata namespace to metadata set. */
76 static private Hashtable mds_hashtable = new Hashtable();
77
78 /** The class responsible for creating and maintaining all the visual components of the metadata management package. */
79 public MSMPrompt prompt = null;
80 /** The profiler is responsible for remembering what actions a user has requested when importing metadata, so as to prevent the user needlessly re-entering this information for each import. */
81 public MSMProfiler profiler = null;
82
83 /** Records all of the changes made to metadata as part of the current metadata change. Entries map from a particular FileNode to an ArrayList of the modified metadata for that node. Not to be confused with the undo managers idea of undo which records a list of all metadata changes requested. */
84 private HashMap undo_buffer = new HashMap();
85 /** The loader responsible for sequentially loading and attempting to use all registered metadata parsers to extract existing metadata from new files. */
86 private ExistingMetadataLoader loader = null;
87 /** Specialized parser for parsing GreenstoneDirectoryMetadata files, which not only caches entries, but also breaks up massive metadata.xml files into reasonable sizes. */
88 private GDMParser gdm_parser = null;
89 /** A list of classes who are interested in changes to the loaded metadata sets. */
90 private Vector listeners = null;
91
92 /** Constructor. */
93 public MetadataSetManager() {
94 this.gdm_parser = new GDMParser();
95 this.listeners = new Vector();
96 this.loader = new ExistingMetadataLoader();
97 loadProfiler();
98 this.prompt = new MSMPrompt(this);
99 }
100
101 /** Attach a piece of metadata to a record or records, ensuring the value tree is built properly, and correct messaging fired.
102 * @param records A FileNode[] of records, or directories, to add the specified metadata to.
103 * @param element The metadata element, contained within an ElementWrapper to base metadata on.
104 * @param value The value to assign to the metadata as a String.
105 */
106 public Metadata addMetadata(long id, FileNode records[], ElementWrapper element, String value_str) {
107 Metadata metadata = null;
108 if (records.length == 1) {
109 metadata = addMetadata(id, records, element, value_str, MetaEditPrompt.ACCUMULATE_ALL);
110 }
111 else {
112 metadata = addMetadata(id, records, element, value_str, MetaEditPrompt.CONFIRM);
113 }
114 return metadata;
115 }
116 public Metadata addMetadata(long id, FileNode records[], ElementWrapper element, String value_str, int action) {
117 // Retrieve the appropriate value node from the value tree for this element, creating it if necessary.
118 GValueModel model = getValueTree(element);
119 GValueNode value = null;
120 if(model != null) {
121 value = model.addValue(value_str); // Only adds if not already present, otherwise just returns existing node.
122 }
123 else {
124 value = new GValueNode(element.toString(), value_str);
125 }
126 // Create new metadata.
127 Metadata metadata = new Metadata(element, value);
128 // Reset the undo buffer.
129 undo_buffer.clear();
130 // Assign to records. Note that we must watch for responses from the user prompts, and cease loop if break signalled.
131 // Now add the metadata to each selected file node.
132 for(int i = 0; action != MetaEditPrompt.CANCEL && i < records.length; i++) {
133 action = addMetadata(id, records[i], metadata, action, (records.length > 1));
134 }
135 // If we were cancelled we should undo any changes so far
136 if(action == MetaEditPrompt.CANCEL) {
137 for(Iterator keys = undo_buffer.keySet().iterator(); keys.hasNext(); ) {
138 FileNode record = (FileNode) keys.next();
139 undoAdd(id, record);
140 }
141 }
142 return metadata;
143 }
144
145 /** Adds a metadata set listener to this set, if it isn't alreay listening.
146 * @param listener The new MSMListener.
147 */
148 public void addMSMListener(MSMListener listener) {
149 if(!listeners.contains(listener)) {
150 listeners.add(listener);
151 }
152 }
153
154 public MetadataSet addSet(String namespace, String name) {
155 MetadataSet mds = new MetadataSet(Utility.METADATA_SET_TEMPLATE);
156 mds.setAttribute("creator", "The Greenstone Librarian Interface");
157 // Calculate lastchanged to right now on this machine by this user
158 String user_name = System.getProperty("user.name");
159 String machine_name = Utility.getMachineName();
160 mds.setAttribute("lastchanged", Utility.getDateString() + " - " + user_name + " on " + machine_name);
161 // And the remaining attributes.
162 //mds.setAttribute("name", name);
163 mds.setAttribute("namespace", namespace);
164 mds_hashtable.put(namespace, mds);
165 // Add the name element.
166 mds.setName(name);
167 fireSetChanged(mds);
168 return mds;
169 }
170
171 /** Add a value tree to a given metadata element.
172 * @param element The ElementWrapper containing the element you wish to add a value tree for.
173 * @param value_tree The root Element of the value tree.
174 */
175 public void addValueTree(GValueModel model) {
176 ElementWrapper element = model.getElement();
177 String namespace = element.getNamespace();
178 MetadataSet mds = (MetadataSet) mds_hashtable.get(namespace);
179 if(mds != null) {
180 mds.addValueTree(element, model);
181 }
182 }
183 /** Destructor.
184 * @see org.greenstone.gatherer.msm.MSMProfiler
185 */
186 public void destroy() {
187 mds_hashtable.clear();
188 profiler.destroy();
189 profiler = null;
190 }
191 /** Method called to open a metadata set editing window.
192 * @return A boolean indicating if the edit was successful.
193 */
194 public boolean editMDS() {
195 MetadataEditorManager mem = new MetadataEditorManager();
196 mem.dispose();
197 mem = null;
198 return true;
199 }
200
201 /** This method is called to export a metadata set. First a prompt is displayed to gather necessary details such as which metadata set to export, where to export it to and what conditions should be applied when exporting. Once this information is gathered the static method <i>exportMDS()</i> is called with the appropriate output stream.
202 * @return A boolean which is <i>true</i> if the metadata set has been exported successfully, <i>false</i> otherwise.
203 */
204 public boolean exportMDS() {
205 ExportMDSPrompt emdsp = new ExportMDSPrompt(this, true);
206 int result = emdsp.display();
207 MetadataSet set = emdsp.getSelectedSet();
208 if (result == ExportMDSPrompt.EXPORT && set != null) {
209 File file = emdsp.getSelectedFile();
210 MetadataSet set_copy = new MetadataSet(set, emdsp.getSelectedCondition());
211 try {
212 file.getParentFile().mkdirs();
213 Utility.export(set_copy.getDocument(), file);
214 // Now for each element attempt to save its value tree.
215 NodeList elements = set_copy.getElements();
216 for(int i = elements.getLength() - 1; i >= 0; i--) {
217 ElementWrapper value_element = new ElementWrapper((Element)elements.item(i));
218 GValueModel value_tree = set_copy.getValueTree(value_element);
219 if(value_tree != null) {
220 File value_file = new File(file.getParentFile(), value_element.getName() + ".mdv");
221 ///ystem.err.println("Saving value file: " + value_file.toString());
222 Utility.export(value_tree.getDocument(), value_file);
223 }
224 }
225 return true;
226 }
227 catch (Exception error) {
228 error.printStackTrace();
229 }
230 }
231 emdsp.dispose();
232 emdsp = null;
233 return false;
234 }
235
236 /** Fire an element changed message off to all registered listeners.
237 * @param event An MSMEvent detailing the change.
238 */
239 public void fireElementChanged(MSMEvent event) {
240 // Then send it to all the listeners.
241 for(int i = 0; i < listeners.size(); i++) {
242 ((MSMListener)listeners.get(i)).elementChanged(event);
243 }
244 }
245
246/** Fire a metadata value changed message, whose id is to be generated now, and whose action code is -1, off to all registered listeners. */
247 public void fireMetadataChanged(FileNode node, Metadata old_data, Metadata new_data) {
248 fireMetadataChanged(System.currentTimeMillis(), node, old_data, new_data, -1);
249 }
250
251 /** Fire a metadata value changed message, whose id is to be generated now, off to all registered listeners. */
252 public void fireMetadataChanged(FileNode node, Metadata old_data, Metadata new_data, int action) {
253 fireMetadataChanged(System.currentTimeMillis(), node, old_data, new_data);
254 }
255
256 /** Fire a metadata value changed message off to all registered listeners. */
257 public void fireMetadataChanged(long id, FileNode node, Metadata old_data, Metadata new_data) {
258 fireMetadataChanged(id, node, old_data, new_data, -1);
259 }
260
261 public void fireMetadataChanged(long id, FileNode node, Metadata old_data, Metadata new_data, int action) {
262 if(old_data != null) {
263 old_data.getElement().dec();
264 }
265 if(new_data != null) {
266 new_data.getElement().inc();
267 }
268 ///ystem.err.println("Metadata changed: " + record + " > '" + old_data + "' -> '" + new_data + "'");
269 // Create a new MSMEvent based on the record.
270 MSMEvent event = new MSMEvent(this, id, node, old_data, new_data, action);
271 // Then send it to all the listeners.
272 for(int i = 0; i < listeners.size(); i++) {
273 ((MSMListener)listeners.get(i)).metadataChanged(event);
274 }
275 }
276
277 /** Fire a metadata set changed message off to all registered listeners.
278 * @param set The MetadataSet thats changed.
279 */
280 public void fireSetChanged(MetadataSet set) {
281 // Create a new MSMEvent, with a MSMAction containing only the new set.
282 MSMEvent event = new MSMEvent(this, 0L, new MSMAction(set.toString(), null, -1, null));
283 // Then send it to all the listeners.
284 for(int i = 0; i < listeners.size(); i++) {
285 ((MSMListener)listeners.get(i)).setChanged(event);
286 }
287 }
288 /** Called whenever the value tree associated with an element changes significantly.
289 * @param element The metadata element whose value tree has changed, as an ElementWrapper.
290 */
291 public void fireValueChanged(ElementWrapper element, GValueModel old_model, GValueModel new_model) {
292 // Create a new MSMEvent based on the element wrapper.
293 MSMEvent event = new MSMEvent(this, 0L, element, old_model, new_model);
294 // Then send it to all the listeners.
295 for(int i = 0; i < listeners.size(); i++) {
296 ((MSMListener)listeners.get(i)).valueChanged(event);
297 }
298 }
299 /** Builds a list of elements that have been assigned as metadata in this collection. We go through all of the elements, looking for elements whose occurances are greater than 0. A convenience call to the version with one parameter.
300 * @return A Vector of assigned elements.
301 */
302 public Vector getAssignedElements() {
303 return getAssignedElements(false);
304 }
305 /** Builds a list of elements that have been assigned as metadata in this collection. We go through all of the elements, looking for elements whose occurances are greater than 0.
306 * @param hierarchy_only <i>true</i> to only return those elements that are both assigned and have hierarchical value trees, <i>false</i> for just assignments.
307 * @return A Vector of assigned elements.
308 */
309 public Vector getAssignedElements(boolean hierarchy_only) {
310 Vector elements = new Vector();
311 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
312 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
313 if(!mds.getNamespace().equals(HIDDEN)) {
314 NodeList set_elements = mds.getElements();
315 for(int i = 0; i < set_elements.getLength(); i++) {
316 ElementWrapper element = new ElementWrapper((Element)set_elements.item(i));
317 elements.add(element);
318 }
319 }
320 }
321 Collections.sort(elements);
322 for(int i = elements.size(); i != 0; i--) {
323 ElementWrapper element = (ElementWrapper) elements.get(i - 1);
324 if(element.getOccurances() == 0 && element.getNamespace().length() > 0 && !element.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE)) {
325 elements.remove(element);
326 }
327 else if(hierarchy_only) {
328 GValueModel model = getValueTree(element);
329 if(!model.isHierarchy()) {
330 elements.remove(element);
331 }
332 }
333 }
334 return elements;
335 }
336 /** Used to get all the (non-hidden) elements in this manager.
337 * @return A Vector of ElementWrappers.
338 */
339 public Vector getElements() {
340 return getElements(false);
341 }
342
343 public Vector getElements(boolean all) {
344 return getElements(all, false);
345 }
346
347 /** Used to get all the elements in this manager.
348 * @param all <i>true</i> if all elements, including hidden, should be returned.
349 * @return A Vector of ElementWrappers.
350 */
351 public Vector getElements(boolean all, boolean force_extracted) {
352 Vector all_elements = new Vector();
353 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
354 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
355 if((!mds.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE) && !mds.getNamespace().equals(HIDDEN))
356 || (mds.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE) && (Gatherer.config.get("general.view_extracted_metadata", Configuration.COLLECTION_SPECIFIC) || force_extracted))
357 || (mds.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE) && mds.getNamespace().equals(HIDDEN) && all)) {
358 NodeList set_elements = mds.getElements();
359 ///ystem.err.println("The set " + mds + " has " + set_elements.getLength() + " elements.");
360 for(int i = 0; i < set_elements.getLength(); i++) {
361 Element raw_element = (Element)set_elements.item(i);
362 ElementWrapper element = new ElementWrapper(raw_element);
363 // For now we do not add subfield elements and their parents, just the subfields.
364 NodeList child_elements = raw_element.getElementsByTagName("Element");
365 if(child_elements.getLength() == 0) {
366 all_elements.add(element);
367 }
368 }
369 }
370 }
371 Collections.sort(all_elements);
372 return all_elements;
373 }
374 /** Returns all the elements within this set as a combobox model.
375 * @return A MetadataComboBoxModel containing all the metadata elements from all the sets, with namespacing.
376 */
377 public MetadataComboBoxModel getElementModel() {
378 return new MetadataComboBoxModel(this);
379 }
380 /** Retrieve a metadata element by its index.
381 * @param index The specified index as an int.
382 * @return An ElementWrapper containing the specied element, or <i>null</i> is no such element exists.
383 */
384 public ElementWrapper getElement(int index) {
385 Vector elements = getElements(false);
386 ElementWrapper result = null;
387 if(0 <= index && index < elements.size()) {
388 result = (ElementWrapper) elements.get(index);
389 }
390 return result;
391 }
392 /** Retrieve a metadata element by looking at the current metadata element. Note that this 'index' element may now be disconnected from the DOM model, so we have to reload the target element by the string method.
393 * @param element The possibly out-of-data MetadataElement.
394 * @return An ElementWrapper containing the specied element, or <i>null</i> is no such element exists.
395 */
396 public ElementWrapper getElement(ElementWrapper element) {
397 return getElement(element.toString());
398 }
399 /** Retrieve a metadata element by its fully qualified name.
400 * @param name The elements name as a String.
401 * @return An ElementWrapper containing the specied element, or <i>null</i> is no such element exists.
402 */
403 public ElementWrapper getElement(String name) {
404 return getElement(name, false);
405 }
406
407 public ElementWrapper getElement(String name, boolean perfect) {
408 ///ystem.err.println("Retrieve element " + name);
409 if(name == null) {
410 ///ystem.err.println("No name!");
411 return null;
412 }
413 ElementWrapper result = null;
414 MetadataSet set = null;
415 String element = null;
416 // First we seperate off what set it is in, where we have '<set><namespace_separator><element>'.
417 if(name.indexOf(MSMUtils.NS_SEP) != -1) {
418 String namespace = name.substring(0, name.indexOf(MSMUtils.NS_SEP));
419 // Retrieve the correct set if possible.
420 set = (MetadataSet)mds_hashtable.get(namespace);
421 namespace = null;
422 // Now retrieve the element name.
423 element = name.substring(name.indexOf(MSMUtils.NS_SEP) + 1);
424 }
425 // If we are looking for a perfect match, we can assume that no namespace means extracted metadata
426 else if(!perfect) {
427 // No namespace so assume that its extracted metadata.
428 set = (MetadataSet)mds_hashtable.get(Utility.EXTRACTED_METADATA_NAMESPACE);
429 element = name;
430 }
431 if(set != null) {
432 // Now we have a set we are ready to locate the requested element. Break the remaining element name down by the subfield separator, attempting to retrieve the element indicated by each step.
433 if(element.indexOf(MSMUtils.SF_SEP) != -1) {
434 StringTokenizer tokenizer = new StringTokenizer(element, MSMUtils.SF_SEP);
435 // Has to be at least two tokens
436 if(tokenizer.countTokens() >= 2) {
437 Element current_element = set.getElement(tokenizer.nextToken());
438 while(current_element != null && tokenizer.hasMoreTokens()) {
439 current_element = set.getElement(current_element, tokenizer.nextToken());
440 }
441 if(current_element != null) {
442 result = new ElementWrapper(current_element);
443 current_element = null;
444 }
445 }
446 tokenizer = null;
447 }
448 // No subfields - much easier.
449 if(result == null) {
450 ///ystem.err.print("Trying to match element " + element +"?");
451 Element temp = set.getElement(element);
452 if(temp != null) {
453 result = new ElementWrapper(temp);
454 }
455 temp = null;
456 }
457 set = null;
458 }
459 element = null;
460 return result;
461 }
462 /** Retrieve a certain named element from a certain named set.
463 * @param set The metadata set whose element you want.
464 * @param name The name of the element.
465 * @return An ElementWrapper around the requested element, or null if no such set or element.
466 */
467 public ElementWrapper getElement(String set, String name) {
468 if(mds_hashtable.containsKey(set)) {
469 MetadataSet temp = (MetadataSet)mds_hashtable.get(set);
470 return new ElementWrapper(temp.getElement(name));
471 }
472 return null;
473 }
474 /** Get all of the metadata elements as an array of nodelists.
475 * @return A NodeList[] of metadata elements.
476 */
477 /* private NodeList[] getNodeLists() {
478 NodeList elements[] = null;
479 int index = 0;
480 elements = new NodeList[getSets().size()]; // Remember not to count hidden metadata
481 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
482 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
483 if(!mds.getNamespace().equals(HIDDEN)) {
484 elements[index] = mds.getElements();
485 index++;
486 }
487 }
488 return elements;
489 } */
490
491 /** Retrieve the named metadata set.
492 * @param name The sets name as a String.
493 * @return The MetadataSet as named, or null if no such set.
494 */
495 public MetadataSet getSet(String name) {
496 if(mds_hashtable.containsKey(name)) {
497 return (MetadataSet) mds_hashtable.get(name);
498 }
499 else if(name.equals(HIDDEN)) {
500 return createHidden();
501 }
502 return null;
503 }
504
505 /** Method to retrieve all of the metadata sets loaded in this collection.
506 * @return A Vector of metadata sets.
507 */
508 public Vector getSets() {
509 return getSets(true);
510 }
511
512 public Vector getSets(boolean include_greenstone) {
513 Vector result = new Vector();
514 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
515 MetadataSet set = (MetadataSet)mds_hashtable.get(keys.nextElement());
516 if(!set.getNamespace().equals(HIDDEN) && (include_greenstone || !set.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE))) {
517 result.add(set);
518 }
519 }
520 return result;
521 }
522
523 /** Find the total number of elements loaded.
524 * @return The element count as an int.
525 */
526 public int getSize() {
527 int count = 0;
528 if(mds_hashtable.size() > 0) {
529 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements();) {
530 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
531 if(mds.getNamespace().equals(HIDDEN)) {
532 count = count + mds.size();
533 }
534 }
535 }
536 return count;
537 }
538 /** Get the value tree that matches the given element.
539 * @param element The ElementWrapper representing the element.
540 * @return The GValueModel representing the value tree or null.
541 */
542 public GValueModel getValueTree(ElementWrapper element) {
543 GValueModel value_tree = null;
544 if(element != null) {
545 String namespace = element.getNamespace();
546 if(namespace.length() > 0) {
547 MetadataSet mds = (MetadataSet) mds_hashtable.get(namespace);
548 if(mds != null) {
549 value_tree = mds.getValueTree(element);
550 }
551 }
552 }
553 return value_tree;
554 }
555 /** This method is called to import a metadata set. First a prompt is displayed to gather necessary details such as which metadata set to import. Once this information is gathered the method <i>importMDS(File)</i> is called with the appropriate filename.
556 * @return A boolean which is <i>true</i> if the metadata set has been imported successfully, <i>false</i> otherwise.
557 */
558 public boolean importMDS() {
559 JFileChooser chooser = new JFileChooser(new File(Utility.METADATA_DIR));
560 javax.swing.filechooser.FileFilter filter = new MDSFileFilter();
561 chooser.setFileFilter(filter);
562 int returnVal = chooser.showDialog(Gatherer.g_man, Dictionary.get("MSMPrompt.File_Import"));
563 if(returnVal == JFileChooser.APPROVE_OPTION) {
564 return importMDS(chooser.getSelectedFile(), true);
565 }
566 return false;
567 }
568
569 public boolean importMDS(File mds_file, boolean user_driven) {
570 // 1. Parse the new file.
571 MetadataSet mds_new = new MetadataSet(mds_file);
572 if(user_driven) {
573 // Display a prompt asking how much of the value structure the user wishes to import.
574 // ...but only if there are some MDV files to read values from
575 FilenameFilter mdv_filter = new MDVFilenameFilter(mds_new.getNamespace());
576 File[] mdv_files = mds_file.getParentFile().listFiles(mdv_filter);
577 if (mdv_files.length > 0) {
578 ExportMDSPrompt imdsp = new ExportMDSPrompt(this, false);
579 int result = imdsp.display();
580 if(result == ExportMDSPrompt.EXPORT) { // Here export means the user didn't cancel.
581 switch(imdsp.getSelectedCondition()) {
582 case MetadataSet.NO_VALUES:
583 mds_new = new MetadataSet(mds_new, MetadataSet.NO_VALUES);
584 break;
585 case MetadataSet.SUBJECTS_ONLY:
586 mds_new = new MetadataSet(mds_new, MetadataSet.SUBJECTS_ONLY);
587 break;
588 default: // ALL_VALUES
589 // Don't do anything.
590 }
591 }
592 else {
593 mds_new = null;
594 }
595 imdsp.dispose();
596 imdsp = null;
597 }
598 }
599 // Carry on importing the new collection
600 if(mds_new != null && mds_new.getDocument() != null) {
601 String family = mds_new.getNamespace();
602 // 2. See if we have another metadata set of the same family
603 // already. If so retrieve it and merge.
604 boolean matched = false;
605 for(Enumeration keys = mds_hashtable.keys();
606 keys.hasMoreElements();) {
607 String key = (String)keys.nextElement();
608 if(key.equals(family)) {
609 matched = true;
610 MetadataSet mds_cur = (MetadataSet)mds_hashtable.get(key);
611 ///ystem.err.println("Merging " + mds_new + " into " + mds_cur);
612 MergeTask task = new MergeTask(mds_cur, mds_new);
613 task.start();
614 }
615 }
616 if(!matched) {
617 ///ystem.err.println("Mapping " + family + " to " + mds_new);
618 mds_hashtable.put(family, mds_new);
619 }
620 fireSetChanged(mds_new);
621 return true;
622 }
623 // else we cancelled for some reason.
624 return false;
625 }
626
627 private class MergeTask
628 extends Thread {
629
630 MetadataSet mds_cur;
631 MetadataSet mds_new;
632
633 MergeTask(MetadataSet mds_cur, MetadataSet mds_new) {
634 this.mds_cur = mds_cur;
635 this.mds_new = mds_new;
636 }
637
638 public void run() {
639 mergeMDS(mds_cur, mds_new);
640 // Fire setChanged() message.
641 fireSetChanged(mds_new);
642 }
643 }
644
645
646 /** Accepts .mdv files for a certain metadata set. */
647 private class MDVFilenameFilter implements FilenameFilter
648 {
649 private String mds_namespace = null;
650
651 public MDVFilenameFilter(String mds_namespace)
652 {
653 this.mds_namespace = mds_namespace.toLowerCase();
654 }
655
656 public boolean accept(File dir, String name)
657 {
658 String copy = name.toLowerCase();
659 if (copy.startsWith(mds_namespace) && copy.endsWith(".mdv")) {
660 return true;
661 }
662
663 return false;
664 }
665 }
666
667 /** This method reloads all of the metadata sets that have been marked as included in this collection by entries in the collection configuration file.
668 */
669 public void load() {
670 File source = new File(Gatherer.c_man.getCollectionMetadata());
671 File files[] = source.listFiles();
672 for(int i = 0; files != null && i < files.length; i++) {
673 if(files[i].getName().endsWith(".mds")) {
674 importMDS(files[i], false);
675 }
676 }
677 // If no current 'hidden' metadata set exists, create one.
678 if(getSet(HIDDEN) == null) {
679 createHidden();
680 }
681 }
682 /** This method takes two metadata sets, the current one and a new one, and merges them. This merge takes place at an element level falling to lower levels as necessary (using <i>mergeMDE()</i> to merge elements and <i>mergeMDV()</i> to merge value trees.
683 * @param mds_current The currently loaded MetadataSet.
684 * @param mds_new A new MetadataSet you wish to merge in.
685 * @return A boolean with value <i>true</i> indicating if the merge was successful, otherwise <i>false</i> if errors were detected.
686 */
687 public boolean mergeMDS(MetadataSet mds_cur, MetadataSet mds_new) {
688 // For a super quick check for equivelent trees, we compare the last changed values.
689 if(mds_cur.getLastChanged().equals(mds_new.getLastChanged())) {
690 // Exactly the same. Nothing to change.
691 return true;
692 }
693 // Show initial progress prompt.
694 prompt.startMerge(mds_new.size());
695 boolean cancel = false;
696 // For each element in the new set
697 for(int i = 0; !cancel && i < mds_new.size(); i++) {
698 boolean cont = false;
699 Element mde_new = mds_new.getElement(i);
700 GValueModel mde_values = mds_new.getValueTree(new ElementWrapper(mde_new));
701 // See if the element already exists in the current set
702 Element mde_cur = mds_cur.getElement(mde_new.getAttribute("name"));
703 int option = Declarations.NO_ACTION;
704 while(!cont && !cancel) {
705 // We may be dealing with a brand new element, or possibly a
706 // renamed one.
707 if(mde_cur == null) {
708 // Provide merge, rename and skip options.
709 option = prompt.mDSPrompt(mds_cur, null, mds_new, mde_new);
710 }
711 else {
712 // If the two elements have equal structure we only have
713 // to worry about merging the values.
714 if(MSMUtils.elementsEqual(mds_cur, mde_cur, mds_new, mde_new, false)) {
715 cancel = !mergeMDV(mds_cur, mde_cur, mds_new, mde_new);
716 cont = true;
717 }
718 else {
719 // Provide add, merge and skip options.
720 option = prompt.mDSPrompt(mds_cur, mde_cur, mds_new, mde_new);
721 }
722 }
723 String reason = null;
724 switch(option) {
725 case Declarations.ADD:
726 // Only available to brand new elements, this options
727 // simply adds the element to the set.
728 reason = mds_cur.addElement(mde_new, mde_values);
729 if(reason == null) {
730 cont = true;
731 }
732 else {
733 prompt.addFailed(mde_new, reason);
734 cont = false;
735 }
736 break;
737 case Declarations.CANCEL:
738 cancel = true;
739 cont = true;
740 break;
741 case Declarations.FORCE_MERGE:
742 // If the mde_cur is null, that means the users has asked
743 // to merge but hasn't choosen any element to merge with.
744 // Make the user select an element.
745 mde_cur = prompt.selectElement(mds_cur);
746 case Declarations.MERGE:
747 // This case in turn calls the mergeMDE method to perform
748 // the actual merging of the Elements.
749 if(mde_cur != null) {
750 cancel = !mergeMDE(mds_cur, mde_cur, mds_new, mde_new);
751 }
752 cont = true;
753 break;
754 case Declarations.RENAME:
755 // This case adds the Element, but requires the user to
756 // enter a unique name.
757 String new_name = prompt.rename(mde_new);
758 if(new_name != null && new_name.length() > 0) {
759 reason = mds_cur.addElement(mde_new, new_name, mde_values);
760 if(reason == null) {
761 mde_cur = mds_cur.getElement(new_name);
762 cont = true;
763 }
764 else {
765 prompt.renameFailed(mde_new, new_name, reason);
766 cont = false;
767 }
768 }
769 else {
770 if(new_name != null) {
771 prompt.renameFailed(mde_new, new_name,
772 "MSMPrompt.Invalid_Name");
773 }
774 cont = false;
775 }
776 break;
777 case Declarations.REPLACE:
778 // Removes the existing Element then adds the new.
779
780 mds_cur.removeElement(mde_cur);
781
782 reason = mds_cur.addElement(mde_new, mde_values);
783 if(reason == null) {
784 cont = true;
785 }
786 else {
787 prompt.removeFailed(mde_cur, reason);
788 cont = false;
789 }
790 break;
791 case Declarations.SKIP:
792 // Does not change the set.
793 cont = true;
794 break;
795 }
796 // Add this action to profile for later reference.
797 if(profiler == null) {
798 ///ystem.err.println("No Profiler");
799 }
800 //profiler.addAction(mds_new.getFile().getAbsolutePath(), MSMUtils.getFullName(mde_new), option, MSMUtils.getFullName(mde_cur));
801 }
802 prompt.incrementMerge();
803 }
804 prompt.endMerge();
805 return true;
806 }
807
808 /** This method allows for two metadata elements to be merged. Essentially merging existing elements give the users such options as keeping or replacing attribute elements as they are merged.
809 * @param mde_cur The Element that already exists in the current metadata sets.
810 * @param mde_new A new Element which has the same name as the current one but different data.
811 * @return A boolean that if <i>true</i> indicats the action was completed. If <i>false</i> then an error or user action has prevented the merge.
812 * TODO Implement
813 */
814 public boolean mergeMDE(MetadataSet mds_cur, Element mde_cur, MetadataSet mds_new, Element mde_new) {
815 for(Node mdn_new = mde_new.getFirstChild(); mdn_new != null; mdn_new = mdn_new.getNextSibling()) {
816 // Only merge the nodes whose name is 'Attribute'
817 if(mdn_new.getNodeName().equals("Attribute")) {
818 Element att_new = (Element) mdn_new;
819 int action = Declarations.NO_ACTION;
820 Element replace_att = null; // replace this att with the new one
821 // Unfortunately some attributes, such as author, can have several occurances, so match each in turn.
822 Element temp[] = MSMUtils.getAttributeNodesNamed(mde_cur, att_new.getAttribute("name"));
823 if (temp==null) {
824 action = Declarations.ADD;
825 } else {
826
827 // look for an exact match
828 for(int i = 0; temp != null && i < temp.length; i++) {
829 Element att_cur = temp[i];
830 if(MSMUtils.attributesEqual(att_cur, att_new)) {
831 action = Declarations.SKIP;
832 break;
833 }
834 att_cur = null;
835 }
836 if (action == Declarations.NO_ACTION) {
837 // we didn't find a match, so we have to prompt teh user for what to do
838 Object result = prompt.mDEPrompt(mde_cur, temp, mde_new, att_new);
839 if (result instanceof Integer) {
840 action = ((Integer)result).intValue();
841 } else {
842 // we have a replace action, and the returned object is the Attribute to replace
843 action = Declarations.REPLACE;
844 replace_att = (Element)result;
845 }
846 }
847 }
848
849 // now do the required action
850 switch (action) {
851 case Declarations.REPLACE:
852 // Out with the old.
853 mde_cur.removeChild(replace_att);
854 case Declarations.ADD:
855 // Simply add the new attribute. No clash is possible as we have already tested for it.
856 MSMUtils.add(mde_cur, att_new);
857 break;
858 case Declarations.SKIP:
859 // Do nothing. Move on to next attribute.
860 break;
861 case Declarations.CANCEL:
862 return false;
863 default:
864 }
865
866 att_new = null;
867 temp = null;
868 replace_att = null;
869 } // if node nmae = attribute
870 } //for each child node
871 return mergeMDV(mds_cur, mde_cur, mds_new, mde_new);
872 }
873
874 /** Merge two metadata value trees.
875 * @param mds_cur The current MetadataSet.
876 * @param mde_cur The current Element which acts as a value tree root.
877 * @param mds_new The MetadataSet we are merging in.
878 * @param mde_new The Element which acts as a value tree that we are merging in.
879 */
880 public boolean mergeMDV(MetadataSet mds_cur, Element mde_cur,
881 MetadataSet mds_new, Element mde_new) {
882 // Remember we may be asked to merge with a current mdv of null.
883 return MSMUtils.updateValueTree(mds_cur, mde_cur, mds_new, mde_new);
884 }
885
886 public void removeElement(ElementWrapper element) {
887 // Retrieve the metadata set this element belongs to.
888 String namespace = element.getNamespace();
889 MetadataSet set = (MetadataSet) mds_hashtable.get(namespace);
890 if(set != null) {
891 // Bugger. Get the old name -before- we remove the element from the set.
892 String old_name = element.toString();
893 // Remove the element.
894 set.removeElement(element.getElement());
895 // Fire event.
896 fireElementChanged(new MSMEvent(this, null, old_name));
897 }
898 else {
899 ///ystem.err.println("no such set " + namespace);
900 }
901 // No such set. No such element.
902 }
903
904 /** Remove a piece of metadata from a record or records[] and fire all the relevant events.
905 * @param records A FileNode[] of records to be changed.
906 * @param metadata The Metadata to remove.
907 */
908 public void removeMetadata(long id, Metadata metadata, FileNode records[]) {
909 // Reset undo buffer
910 undo_buffer.clear();
911 // Simplier than the others. Simply remove the metadata. Note that we only bother prompting if there is more than one
912 int action = MetaEditPrompt.CONFIRM;
913 if(records.length == 1) {
914 action = MetaEditPrompt.REMOVE;
915 }
916 // Now remove metadata from the selected file nodes.
917 for(int i = 0; action != MetaEditPrompt.CANCEL && i < records.length; i++) {
918 action = removeMetadata(id, records[i], metadata, action, (records.length > 1));
919 }
920 // If we were cancelled we should undo any changes so far
921 if(action == MetaEditPrompt.CANCEL) {
922 for(Iterator keys = undo_buffer.keySet().iterator(); keys.hasNext(); ) {
923 FileNode record = (FileNode) keys.next();
924 undoRemove(id, record);
925 }
926 }
927 }
928 /** Remove the specified listener from ourselves.
929 * @param listener The MSMListener in question.
930 */
931 public void removeMSMListener(MSMListener listener) {
932 listeners.remove(listener);
933 }
934
935 public void removeSet(MetadataSet set) {
936 mds_hashtable.remove(set.getNamespace());
937 fireSetChanged(set);
938 }
939
940 /** Rename the identifier of a given element to the name given.
941 * @param element The metadata element effected, as an ElementWrapper.
942 * @param new_name The String to use as the new name.
943 */
944 /* private void renameElement(ElementWrapper element, String new_name) {
945 Element e = element.getElement();
946 String old_name = element.toString();
947 MSMUtils.setIdentifier(e, new_name);
948 fireElementChanged(new MSMEvent(this, element, old_name));
949 old_name = null;
950 e = null;
951 } */
952 /** A method to save the state of this metadata set manager. First we ensure that the names of all included metadata sets have been added to the collection configuration file, then all of the metadata sets contained are exported with full content to the collect/<col_name>/metadata/ directory.
953 */
954 public void save() {
955 // Create the correct file to save these sets to...
956 File file = new File(Gatherer.self.getCollectionMetadata());
957 if (!file.exists()) {
958 Gatherer.println("trying to save a collection and the metadata directory does not exist - creating it!");
959 file.mkdir();
960 }
961 // And make back ups of all existing metadata set files.
962 File temp[] = file.listFiles();
963 for(int i = temp.length - 1; i >= 0; i--) {
964 if(temp[i].getName().endsWith(".mds") || temp[i].getName().endsWith(".mdv")) {
965 File backup = new File(temp[i].getAbsolutePath() + "~");
966 backup.deleteOnExit();
967 if(!temp[i].renameTo(backup)) {
968 Gatherer.println("Error in MetadataSetManager.save(): FileRenamedException");
969 }
970 }
971 }
972 // Now save the latest versions of the metadata sets.
973 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
974 String namespace = (String) keys.nextElement();
975 MetadataSet set = (MetadataSet) mds_hashtable.get(namespace);
976 try {
977 File mds_file = new File(file, set.getNamespace() + ".mds");
978 Utility.export(set.getDocument(), mds_file);
979 set.setFile(mds_file);
980 // Now for each element attempt to save its value tree.
981 NodeList elements = set.getElements();
982 for(int i = elements.getLength() - 1; i >= 0; i--) {
983 ElementWrapper value_element = new ElementWrapper((Element)elements.item(i));
984 if(value_element.hasValueTree()) {
985 GValueModel value_tree = set.getValueTree(value_element);
986 if(value_tree != null) {
987 File value_file = new File(file, value_element.getName() + ".mdv");
988 ///ystem.err.println("Saving value file: " + value_file.toString());
989 Utility.export(value_tree.getDocument(), value_file);
990 // If this is a hierarchy element, write hierarchy file.
991 if(value_element.getNamespace().equals(MetadataSetManager.HIDDEN) || value_tree.isHierarchy()) {
992 MetadataXML.write(value_element, value_tree, this, Gatherer.c_man.getCollectionEtc());
993 }
994 }
995 }
996 }
997 }
998 catch (Exception error) {
999 error.printStackTrace();
1000 }
1001 }
1002 profiler.save();
1003 }
1004 /** Given a FileNode of the original file and the new FileNode, search for any metadata, either from a greenstone directory archive xml file, or from one of the registered 'plugin' parsers.
1005 * @param source The source FileNode.
1006 * @param destination The new FileNode.
1007 */
1008 public final boolean searchForMetadata(FileNode destination, FileNode source, boolean folder_level) {
1009 return searchForMetadata(destination, source, folder_level, false);
1010 }
1011 public final boolean searchForMetadata(FileNode destination, FileNode source, boolean folder_level, boolean dummy_run) {
1012 ///atherer.println("MetadataSetManager.searchForMetadata()");
1013 // for some reason, the loader returns 'dialog_cancelled' ie true if cancelled, false if OK. why???
1014 // since we want to return true if successful, we'll return the opposite
1015 return (loader.searchForMetadata(destination, source, folder_level, dummy_run)?false:true);
1016 }
1017 /** Build a vector of all the metadata sets that contain an element with the given name.
1018 * @param name The name of an element as a String.
1019 * @return A Vector of metadata sets.
1020 * @see MSMPrompt (org.greenstone.gatherer.msm.MSMPrompt#selectSet)
1021 */
1022 public Vector setsThatContain(String name) {
1023 Vector result = new Vector();
1024 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
1025 MetadataSet set = (MetadataSet) mds_hashtable.get(keys.nextElement());
1026 if(set.getElement(name) != null) {
1027 result.add(set);
1028 }
1029 }
1030 return result;
1031 }
1032
1033 public final int size() {
1034 return getSets().size();
1035 }
1036
1037 /** Update a piece of metadata connected to a record or records, ensuring the value tree is built properly, and correct messaging fired.
1038 * @param records A FileNode[] of records, or directories, to add the specified metadata to.
1039 * @param element The metadata element, contained within an ElementWrapper to base metadata on.
1040 * @param value The value to assign to the metadata as a String.
1041 * @param action The default action to take in the prompt.
1042 * @param file_level If true then the metadata can be replaced normally, if false then we should actually use an add method instead.
1043 * @return The Metadata we just assigned.
1044 */
1045 public Metadata updateMetadata(long id, Metadata old_metadata, FileNode records[], String value_str, int action, boolean file_level) {
1046 // Retrieve the new value node from the same value tree as the old metadata.
1047 ElementWrapper element = old_metadata.getElement();
1048 GValueModel model = getValueTree(element);
1049 GValueNode value = null;
1050 if(model != null) {
1051 value = model.addValue(value_str);
1052 }
1053 else {
1054 value = new GValueNode(element.toString(), value_str);
1055 }
1056 // Create new metadata.
1057 Metadata new_metadata = new Metadata(value);
1058 // Reset the undo buffer
1059 undo_buffer.clear();
1060 // And update the old with it.
1061 if(action == -1) {
1062 //Note that we only bother prompting if there is more than one
1063 action = MetaEditPrompt.CONFIRM;
1064 if(records.length == 1) {
1065 action = MetaEditPrompt.OVERWRITE;
1066 }
1067 }
1068 // And then update each selection file node.
1069 for(int i = 0; action != MetaEditPrompt.CANCEL && i < records.length; i++) {
1070 action = updateMetadata(id, records[i], old_metadata, new_metadata, action, (records.length > 1), file_level);
1071 }
1072 // If we were cancelled we should undo any changes so far
1073 if(action == MetaEditPrompt.CANCEL) {
1074 for(Iterator keys = undo_buffer.keySet().iterator(); keys.hasNext(); ) {
1075 FileNode record = (FileNode) keys.next();
1076 undoUpdate(id, record);
1077 }
1078 }
1079 // All done. Any events would have been fired within the record recursion.
1080 return new_metadata;
1081 }
1082
1083 /** Add a reference to a piece of metadata to the given FileNode. The whole method gets a wee bit messy as we have to allow for several different commands from users such as accumulate / overwrite, skip just this file or cancel the whole batch. Cancelling is especially problematic as we need to rollback any changes (within reason).
1084 * It is also worth mentioning that despite its name, no actual metadata is added directly by this method. Instead a call to fireMetadataChanged() is issued, which is in turn processed by the GDMManager (which, given this method may have been called from GDMManager as well, means the cycle is complete. Um, that doesn't mean theres an infinite loop... I hope).
1085 * @param id a long unique identifier shared by all actions caused by the same gesture.
1086 * @param record the FileNode we are adding the metadata to.
1087 * @param data the new Metadata.
1088 * @param action the default action as an int. May require user interaction.
1089 * @param fire_event <i>true</i> if this action should fire a metadata changed event, <i>false</i> if we are calling this as an affect of a previous event. (Don't want an infinitely recursive loop, do we).
1090 * @param multiple_selection <i>true</i> if more than one file or folder was selected.
1091 * @return an int specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1092 */
1093 private int addMetadata(long id, FileNode record, Metadata data, int action, boolean multiple_selection) {
1094 // Super special exception for accumulate all action. We are going to add this metadata anyway, regardless of whats already there, so just add it.
1095 if(action == MetaEditPrompt.ACCUMULATE_ALL || action == MetaEditPrompt.OVERWRITE_ALL) {
1096 fireMetadataChanged(id, record, null, data, action - 1); // Transform action to accumulate or overwrite
1097 }
1098 else {
1099 // Recover the metadata from this file.
1100 ArrayList metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1101 // Most important test, we don't have to add the metadata if its already there!
1102 if(!metadata.contains(data)) {
1103 // Record undo information for this file node.
1104 ArrayList undo = new ArrayList();
1105 // Prepare for MEP
1106 int user_action = MetaEditPrompt.ACCUMULATE;
1107 String values = "";
1108 // See if there is any existing metadata with the same name. If so make a string from all the values (bob, jim etc).
1109 int metadata_size = metadata.size();
1110 for(int i = 0; i < metadata_size; i++) {
1111 Metadata current_data = (Metadata)metadata.get(i);
1112 if(current_data.getElement().equals(data.getElement())) {
1113 if(values.length() > 0) {
1114 values = values + ", ";
1115 }
1116 values = values + current_data.getValue();
1117 }
1118 }
1119 // If we are confirming prompt for user_action.
1120 if(values.length() > 0 && action == MetaEditPrompt.CONFIRM) {
1121 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.ADD_PROMPT, multiple_selection, record.getFile(), data.getElement().toString(), values, data.getValue());
1122 user_action = mep.display();
1123 }
1124 if(user_action == MetaEditPrompt.ACCUMULATE_ALL || user_action == MetaEditPrompt.CANCEL || user_action == MetaEditPrompt.OVERWRITE_ALL) {
1125 action = user_action;
1126 }
1127 // If we are overwriting we first remove all metadata with the same element, unless the metadata is non-file level is which case we leave it, and hope the accumulate vs overwrite will be followed during the determining of metadata assigned.
1128 if(action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.OVERWRITE) {
1129 for(int i = metadata_size; i != 0; i--) {
1130 Metadata old_data = (Metadata)metadata.get(i - 1);
1131 if(old_data.getElement().equals(data.getElement()) && old_data.isFileLevel()) {
1132 // We have a match. Remove this metadata.
1133 fireMetadataChanged(id, record, old_data, null, MetaEditPrompt.REMOVE);
1134 // Add it to our undo buffer.
1135 undo.add(old_data);
1136 }
1137 }
1138 }
1139 // Ensure the metadata will accumulate or overwrite as the user wishes.
1140 if(user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL) {
1141 data.setAccumulate(true);
1142 }
1143 else if(user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.OVERWRITE_ALL) {
1144 data.setAccumulate(false);
1145 }
1146 // Unless cancelled, add the metadata after checking we don't already have it in the metadata (obviously not if we're overwriting but we'd better check anyway). Also if we've skipped the file we should do so, but move on to the next child...
1147 if((user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL || user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.OVERWRITE_ALL) && !metadata.contains(data)) {
1148 ///ystem.err.println("Adding metadata " + data);
1149 fireMetadataChanged(id, record, null, data, ((user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL) ? MetaEditPrompt.ACCUMULATE : MetaEditPrompt.OVERWRITE));
1150 // The last element in undo is the new element.
1151 undo.add(data);
1152 }
1153 // Store the undo list in our undo buffer.
1154 undo_buffer.put(record, undo);
1155 }
1156 }
1157 // If we've been cancelled, roll back the addition.
1158 if(action == MetaEditPrompt.CANCEL) {
1159 undoAdd(id, record);
1160 }
1161 return action;
1162 }
1163 /** addMetadata(long, FileNode, Metadata, int, boolean) */
1164
1165 /** Create the hidden mds, used for custom classifiers. */
1166 private MetadataSet createHidden() {
1167 MetadataSet hidden_mds = new MetadataSet(Utility.METADATA_SET_TEMPLATE);
1168 hidden_mds.setAttribute("creator","The Gatherer");
1169 hidden_mds.setAttribute("contact","gatherer@greenstone");
1170 hidden_mds.setAttribute("description","A hidden metadata set used to create custom classifiers.");
1171 hidden_mds.setAttribute("family","Gatherer Hidden Metadata");
1172 hidden_mds.setAttribute("lastchanged","");
1173 hidden_mds.setAttribute("name","Gatherer Hidden Metadata");
1174 hidden_mds.setAttribute("namespace",HIDDEN);
1175 mds_hashtable.put(HIDDEN, hidden_mds);
1176 fireSetChanged(hidden_mds);
1177 return hidden_mds;
1178 }
1179
1180 /** Creates a new profiler, which in turn will attempt to load previous profile information. */
1181 private void loadProfiler() {
1182 profiler = new MSMProfiler();
1183 addMSMListener(profiler);
1184 }
1185
1186 /** In order to remove metadata from the tree you first call this method providing it with the metadata you want removed. This will remove any occurance of said metadata from the given FileNode (using fireMetadataChanged()).
1187 * @param id a unique long identifier common to all actions caused by a single gesture.
1188 * @param record the FileNode who we are removing metadata from.
1189 * @param data the <strong>Metadata</strong> you wish removed from the tree.
1190 * @param action an <i>int</i> specifying the wanted prompting action.
1191 * @param fire_event <i>true</i> if this action should fire metadata changed events.
1192 * @param multiple_selection the number of records in the selection, as an <i>int</i>. Used to determine prompt controls.
1193 * @return an <i>int</i> specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1194 */
1195 private int removeMetadata(long id, FileNode record, Metadata data, int action, boolean multiple_selection) {
1196 ArrayList metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1197 int user_action = MetaEditPrompt.REMOVE;
1198 // See if we even have this metadata.
1199 if(metadata.contains(data)) {
1200 ArrayList undo = new ArrayList();
1201 // We do have it. If action == CONFIRM, show user prompt.
1202 if(action == MetaEditPrompt.CONFIRM) {
1203 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.REMOVE_PROMPT, multiple_selection, record.getFile(), data.getElement().toString(), data.getValue(), "");
1204 user_action = mep.display();
1205 }
1206 // Set action to match the user_action under certain circumstances.
1207 if(user_action == MetaEditPrompt.CANCEL || user_action == MetaEditPrompt.REMOVE_ALL) {
1208 action = user_action;
1209 }
1210 if(action == MetaEditPrompt.REMOVE_ALL || user_action == MetaEditPrompt.REMOVE) {
1211 fireMetadataChanged(id, record, data, null, MetaEditPrompt.REMOVE);
1212 undo.add(data);
1213 }
1214 // Store undo information
1215 undo_buffer.put(record, undo);
1216 }
1217 // If we've been cancelled higher up, undo action.
1218 if(action == MetaEditPrompt.CANCEL) {
1219 undoRemove(id, record);
1220 }
1221 return action;
1222 }
1223
1224 /** Rollback any changes made as part of a single metadata add process (only valid during the action itself, ie if a user presses cancel).
1225 * @param id the unique identify of all actions created as part of a single gesture, as a <i>long</i>.
1226 * @param record the FileNode whose metadata was changed.
1227 */
1228 private void undoAdd(long id, FileNode record) {
1229 // Retrieve the undo data from the buffer
1230 ArrayList undo = (ArrayList) undo_buffer.get(record);
1231 // If there is no undo then we can't do anything, but there should be
1232 if(undo != null && undo.size() > 0) {
1233 // The last piece of data in an add actions undo buffer is the metadata that was added
1234 Metadata data = (Metadata) undo.remove(undo.size() - 1);
1235 // Remove the data
1236 fireMetadataChanged(id, record, data, null, MetaEditPrompt.REMOVE);
1237 // If we removed other metadata when adding this metadata restore it too
1238 for(int i = 0; i < undo.size(); i++) {
1239 Metadata old_data = (Metadata) undo.get(i);
1240 fireMetadataChanged(id, record, null, old_data, MetaEditPrompt.ACCUMULATE);
1241 }
1242 }
1243 }
1244 /** Rollback any changes made as part of a single metadata remove process (only valid during the action itself, ie if a user presses cancel).
1245 * @param id the unique identify of all actions created as part of a single gesture, as a long.
1246 * @param record the FileNode metadata was removed from.
1247 */
1248 private void undoRemove(long id, FileNode record) {
1249 // Retrieve undo information
1250 ArrayList undo = (ArrayList) undo_buffer.get(record);
1251 // Ensure that we have something to undo
1252 if(undo != null && undo.size() == 1) {
1253 // The undo buffer should contain exactly one entry, the metadata removed
1254 Metadata data = (Metadata) undo.get(0);
1255 fireMetadataChanged(id, record, null, data, MetaEditPrompt.ACCUMULATE);
1256 }
1257 }
1258 /** Roll back any changes made as part of a single metadata update process (only valid during the action itself, ie if a user presses cancel).
1259 * @param id the unique identify of all actions created as part of a single gesture, as a long.
1260 * @param record the FileNode whose metadata was changed.
1261 */
1262 private void undoUpdate(long id, FileNode record) {
1263 // Retrieve undo information
1264 ArrayList undo = (ArrayList) undo_buffer.get(record);
1265 if(undo != null && undo.size() == 2) {
1266 Metadata old_data = (Metadata) undo.get(0);
1267 Metadata new_data = (Metadata) undo.get(1);
1268 fireMetadataChanged(id, record, new_data, null, MetaEditPrompt.REMOVE);
1269 if(old_data != new_data) { // Correct reference comparison
1270 fireMetadataChanged(id, record, null, old_data, MetaEditPrompt.ACCUMULATE);
1271 }
1272 }
1273 }
1274
1275 /** Used to update the values of one of the metadata elements within this node. Has the same trickiness as Add but only half the number of options.
1276 * @param id the unique identify of all actions created as part of a single gesture, as a <i>long</i>.
1277 * @param record the FileNode whose metadata we are changing.
1278 * @param old_data The old existing <strong>Metadata</strong>.
1279 * @param new_data The new updated <strong>Metadata</strong>.
1280 * @param action An <i>int</i> indicating what we are going to do about it.
1281 * @param multiple_selection The number of records in the selection, as an <i>int</i>. Used to determine prompt controls.
1282 * @return An <i>int</i> specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1283 */
1284 private int updateMetadata(long id, FileNode record, Metadata old_data, Metadata new_data, int action, boolean multiple_selection, boolean file_level) {
1285 ArrayList metadata;
1286 if(file_level) {
1287 metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1288 }
1289 else {
1290 metadata = Gatherer.c_man.getCollection().gdm.getAllMetadata(record.getFile());
1291 }
1292 int user_action = MetaEditPrompt.OVERWRITE;
1293 // Standard case of updating an existing metadata value.
1294 if(metadata.contains(old_data)) {
1295 ArrayList undo = new ArrayList();
1296 // If we are to prompt the user, do so.
1297 if(action == MetaEditPrompt.CONFIRM) {
1298 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.UPDATE_PROMPT, multiple_selection, record.getFile(), old_data.getElement().toString(), old_data.getValue(), new_data.getValue());
1299 user_action = mep.display();
1300 }
1301 // Some user actions should have a continuous effect.
1302 if(user_action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.CANCEL) {
1303 action = user_action;
1304 }
1305 // And if the update chose update, do so.
1306 if(action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.UPDATE_ONCE) {
1307 ///ystem.err.println("Updating:\n"+old_data+"\nto\n"+new_data);
1308 // If this is file level then we can do a normal replace
1309 if(file_level) {
1310 fireMetadataChanged(id, record, old_data, new_data, MetaEditPrompt.OVERWRITE);
1311 undo.add(old_data);
1312 undo.add(new_data);
1313 }
1314 // Otherwise we are dealing with someone attempting to override inherited metadata, so we actually fire an add. To this end we add new data twice to the undo buffer, thus we can detect if this has happened.
1315 else {
1316 fireMetadataChanged(id, record, null, new_data, MetaEditPrompt.OVERWRITE);
1317 undo.add(new_data);
1318 undo.add(new_data);
1319 }
1320 }
1321 // Store the undo information
1322 undo_buffer.put(record, undo);
1323 }
1324 // If we've been cancelled undo.
1325 if(action == MetaEditPrompt.CANCEL) {
1326 undoUpdate(id, record);
1327 }
1328 return action;
1329 }
1330}
Note: See TracBrowser for help on using the repository browser.