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

Last change on this file since 6213 was 6213, checked in by jmt12, 20 years ago

Overloaded the fireMetadataChanged again to allow callers to provide a preconstructed event, such as what is available in GreenstoneArchiveParser

  • Property svn:keywords set to Author Date Id Revision
File size: 56.5 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 fireMetadataChanged(event);
272 event = null;
273 }
274
275 public void fireMetadataChanged(MSMEvent event) {
276 // Then send it to all the listeners.
277 for(int i = 0; i < listeners.size(); i++) {
278 ((MSMListener)listeners.get(i)).metadataChanged(event);
279 }
280 }
281
282 /** Fire a metadata set changed message off to all registered listeners.
283 * @param set The MetadataSet thats changed.
284 */
285 public void fireSetChanged(MetadataSet set) {
286 // Create a new MSMEvent, with a MSMAction containing only the new set.
287 MSMEvent event = new MSMEvent(this, 0L, new MSMAction(set.toString(), null, -1, null));
288 // Then send it to all the listeners.
289 for(int i = 0; i < listeners.size(); i++) {
290 ((MSMListener)listeners.get(i)).setChanged(event);
291 }
292 }
293 /** Called whenever the value tree associated with an element changes significantly.
294 * @param element The metadata element whose value tree has changed, as an ElementWrapper.
295 */
296 public void fireValueChanged(ElementWrapper element, GValueModel old_model, GValueModel new_model) {
297 // Create a new MSMEvent based on the element wrapper.
298 MSMEvent event = new MSMEvent(this, 0L, element, old_model, new_model);
299 // Then send it to all the listeners.
300 for(int i = 0; i < listeners.size(); i++) {
301 ((MSMListener)listeners.get(i)).valueChanged(event);
302 }
303 }
304 /** 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.
305 * @return A Vector of assigned elements.
306 */
307 public Vector getAssignedElements() {
308 return getAssignedElements(false);
309 }
310 /** 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.
311 * @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.
312 * @return A Vector of assigned elements.
313 */
314 public Vector getAssignedElements(boolean hierarchy_only) {
315 Vector elements = new Vector();
316 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
317 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
318 if(!mds.getNamespace().equals(HIDDEN)) {
319 NodeList set_elements = mds.getElements();
320 for(int i = 0; i < set_elements.getLength(); i++) {
321 ElementWrapper element = new ElementWrapper((Element)set_elements.item(i));
322 elements.add(element);
323 }
324 }
325 }
326 Collections.sort(elements);
327 for(int i = elements.size(); i != 0; i--) {
328 ElementWrapper element = (ElementWrapper) elements.get(i - 1);
329 if(element.getOccurances() == 0 && element.getNamespace().length() > 0 && !element.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE)) {
330 elements.remove(element);
331 }
332 else if(hierarchy_only) {
333 GValueModel model = getValueTree(element);
334 if(!model.isHierarchy()) {
335 elements.remove(element);
336 }
337 }
338 }
339 return elements;
340 }
341 /** Used to get all the (non-hidden) elements in this manager.
342 * @return A Vector of ElementWrappers.
343 */
344 public Vector getElements() {
345 return getElements(false);
346 }
347
348 public Vector getElements(boolean all) {
349 return getElements(all, false);
350 }
351
352 /** Used to get all the elements in this manager.
353 * @param all <i>true</i> if all elements, including hidden, should be returned.
354 * @return A Vector of ElementWrappers.
355 */
356 public Vector getElements(boolean all, boolean force_extracted) {
357 Vector all_elements = new Vector();
358 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
359 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
360 if((!mds.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE) && !mds.getNamespace().equals(HIDDEN))
361 || (mds.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE) && (Gatherer.config.get("general.view_extracted_metadata", Configuration.COLLECTION_SPECIFIC) || force_extracted))
362 || (mds.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE) && mds.getNamespace().equals(HIDDEN) && all)) {
363 NodeList set_elements = mds.getElements();
364 ///ystem.err.println("The set " + mds + " has " + set_elements.getLength() + " elements.");
365 for(int i = 0; i < set_elements.getLength(); i++) {
366 Element raw_element = (Element)set_elements.item(i);
367 ElementWrapper element = new ElementWrapper(raw_element);
368 // For now we do not add subfield elements and their parents, just the subfields.
369 NodeList child_elements = raw_element.getElementsByTagName("Element");
370 if(child_elements.getLength() == 0) {
371 all_elements.add(element);
372 }
373 }
374 }
375 }
376 Collections.sort(all_elements);
377 return all_elements;
378 }
379 /** Returns all the elements within this set as a combobox model.
380 * @return A MetadataComboBoxModel containing all the metadata elements from all the sets, with namespacing.
381 */
382 public MetadataComboBoxModel getElementModel() {
383 return new MetadataComboBoxModel(this);
384 }
385 /** Retrieve a metadata element by its index.
386 * @param index The specified index as an int.
387 * @return An ElementWrapper containing the specied element, or <i>null</i> is no such element exists.
388 */
389 public ElementWrapper getElement(int index) {
390 Vector elements = getElements(false);
391 ElementWrapper result = null;
392 if(0 <= index && index < elements.size()) {
393 result = (ElementWrapper) elements.get(index);
394 }
395 return result;
396 }
397 /** 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.
398 * @param element The possibly out-of-data MetadataElement.
399 * @return An ElementWrapper containing the specied element, or <i>null</i> is no such element exists.
400 */
401 public ElementWrapper getElement(ElementWrapper element) {
402 return getElement(element.toString());
403 }
404 /** Retrieve a metadata element by its fully qualified name.
405 * @param name The elements name as a String.
406 * @return An ElementWrapper containing the specied element, or <i>null</i> is no such element exists.
407 */
408 public ElementWrapper getElement(String name) {
409 return getElement(name, false);
410 }
411
412 public ElementWrapper getElement(String name, boolean perfect) {
413 ///ystem.err.println("Retrieve element " + name);
414 if(name == null) {
415 ///ystem.err.println("No name!");
416 return null;
417 }
418 ElementWrapper result = null;
419 MetadataSet set = null;
420 String element = null;
421 // First we seperate off what set it is in, where we have '<set><namespace_separator><element>'.
422 if(name.indexOf(MSMUtils.NS_SEP) != -1) {
423 String namespace = name.substring(0, name.indexOf(MSMUtils.NS_SEP));
424 // Retrieve the correct set if possible.
425 set = (MetadataSet)mds_hashtable.get(namespace);
426 namespace = null;
427 // Now retrieve the element name.
428 element = name.substring(name.indexOf(MSMUtils.NS_SEP) + 1);
429 }
430 // If we are looking for a perfect match, we can assume that no namespace means extracted metadata
431 else if(!perfect) {
432 // No namespace so assume that its extracted metadata.
433 set = (MetadataSet)mds_hashtable.get(Utility.EXTRACTED_METADATA_NAMESPACE);
434 element = name;
435 }
436 if(set != null) {
437 // 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.
438 if(element.indexOf(MSMUtils.SF_SEP) != -1) {
439 StringTokenizer tokenizer = new StringTokenizer(element, MSMUtils.SF_SEP);
440 // Has to be at least two tokens
441 if(tokenizer.countTokens() >= 2) {
442 Element current_element = set.getElement(tokenizer.nextToken());
443 while(current_element != null && tokenizer.hasMoreTokens()) {
444 current_element = set.getElement(current_element, tokenizer.nextToken());
445 }
446 if(current_element != null) {
447 result = new ElementWrapper(current_element);
448 current_element = null;
449 }
450 }
451 tokenizer = null;
452 }
453 // No subfields - much easier.
454 if(result == null) {
455 ///ystem.err.print("Trying to match element " + element +"?");
456 Element temp = set.getElement(element);
457 if(temp != null) {
458 result = new ElementWrapper(temp);
459 }
460 temp = null;
461 }
462 set = null;
463 }
464 element = null;
465 return result;
466 }
467 /** Retrieve a certain named element from a certain named set.
468 * @param set The metadata set whose element you want.
469 * @param name The name of the element.
470 * @return An ElementWrapper around the requested element, or null if no such set or element.
471 */
472 public ElementWrapper getElement(String set, String name) {
473 if(mds_hashtable.containsKey(set)) {
474 MetadataSet temp = (MetadataSet)mds_hashtable.get(set);
475 return new ElementWrapper(temp.getElement(name));
476 }
477 return null;
478 }
479 /** Get all of the metadata elements as an array of nodelists.
480 * @return A NodeList[] of metadata elements.
481 */
482 /* private NodeList[] getNodeLists() {
483 NodeList elements[] = null;
484 int index = 0;
485 elements = new NodeList[getSets().size()]; // Remember not to count hidden metadata
486 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
487 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
488 if(!mds.getNamespace().equals(HIDDEN)) {
489 elements[index] = mds.getElements();
490 index++;
491 }
492 }
493 return elements;
494 } */
495
496 /** Retrieve the named metadata set.
497 * @param name The sets name as a String.
498 * @return The MetadataSet as named, or null if no such set.
499 */
500 public MetadataSet getSet(String name) {
501 if(mds_hashtable.containsKey(name)) {
502 return (MetadataSet) mds_hashtable.get(name);
503 }
504 else if(name.equals(HIDDEN)) {
505 return createHidden();
506 }
507 return null;
508 }
509
510 /** Method to retrieve all of the metadata sets loaded in this collection.
511 * @return A Vector of metadata sets.
512 */
513 public Vector getSets() {
514 return getSets(true);
515 }
516
517 public Vector getSets(boolean include_greenstone_extracted) {
518 Vector result = new Vector();
519 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
520 MetadataSet set = (MetadataSet)mds_hashtable.get(keys.nextElement());
521 if(!set.getNamespace().equals(HIDDEN) && (include_greenstone_extracted || !set.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE))) {
522 result.add(set);
523 }
524 }
525 return result;
526 }
527
528 /** Find the total number of elements loaded.
529 * @return The element count as an int.
530 */
531 public int getSize() {
532 int count = 0;
533 if(mds_hashtable.size() > 0) {
534 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements();) {
535 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
536 if(mds.getNamespace().equals(HIDDEN)) {
537 count = count + mds.size();
538 }
539 }
540 }
541 return count;
542 }
543 /** Get the value tree that matches the given element.
544 * @param element The ElementWrapper representing the element.
545 * @return The GValueModel representing the value tree or null.
546 */
547 public GValueModel getValueTree(ElementWrapper element) {
548 GValueModel value_tree = null;
549 if(element != null) {
550 String namespace = element.getNamespace();
551 if(namespace.length() > 0) {
552 MetadataSet mds = (MetadataSet) mds_hashtable.get(namespace);
553 if(mds != null) {
554 value_tree = mds.getValueTree(element);
555 }
556 }
557 }
558 return value_tree;
559 }
560 /** 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.
561 * @return A boolean which is <i>true</i> if the metadata set has been imported successfully, <i>false</i> otherwise.
562 */
563 public boolean importMDS() {
564 JFileChooser chooser = new JFileChooser(new File(Utility.METADATA_DIR));
565 javax.swing.filechooser.FileFilter filter = new MDSFileFilter();
566 chooser.setFileFilter(filter);
567 int returnVal = chooser.showDialog(Gatherer.g_man, Dictionary.get("MSMPrompt.File_Import"));
568 if(returnVal == JFileChooser.APPROVE_OPTION) {
569 return importMDS(chooser.getSelectedFile(), true);
570 }
571 return false;
572 }
573
574 public boolean importMDS(File mds_file, boolean user_driven) {
575 // 1. Parse the new file.
576 MetadataSet mds_new = new MetadataSet(mds_file);
577 if(user_driven) {
578 // Display a prompt asking how much of the value structure the user wishes to import.
579 // ...but only if there are some MDV files to read values from
580 FilenameFilter mdv_filter = new MDVFilenameFilter(mds_new.getNamespace());
581 File[] mdv_files = mds_file.getParentFile().listFiles(mdv_filter);
582 if (mdv_files.length > 0) {
583 ExportMDSPrompt imdsp = new ExportMDSPrompt(this, false);
584 int result = imdsp.display();
585 if(result == ExportMDSPrompt.EXPORT) { // Here export means the user didn't cancel.
586 switch(imdsp.getSelectedCondition()) {
587 case MetadataSet.NO_VALUES:
588 mds_new = new MetadataSet(mds_new, MetadataSet.NO_VALUES);
589 break;
590 case MetadataSet.SUBJECTS_ONLY:
591 mds_new = new MetadataSet(mds_new, MetadataSet.SUBJECTS_ONLY);
592 break;
593 default: // ALL_VALUES
594 // Don't do anything.
595 }
596 }
597 else {
598 mds_new = null;
599 }
600 imdsp.dispose();
601 imdsp = null;
602 }
603 }
604 // Carry on importing the new collection
605 if(mds_new != null && mds_new.getDocument() != null) {
606 String family = mds_new.getNamespace();
607 // 2. See if we have another metadata set of the same family
608 // already. If so retrieve it and merge.
609 boolean matched = false;
610 for(Enumeration keys = mds_hashtable.keys();
611 keys.hasMoreElements();) {
612 String key = (String)keys.nextElement();
613 if(key.equals(family)) {
614 matched = true;
615 MetadataSet mds_cur = (MetadataSet)mds_hashtable.get(key);
616 ///ystem.err.println("Merging " + mds_new + " into " + mds_cur);
617 MergeTask task = new MergeTask(mds_cur, mds_new);
618 task.start();
619 }
620 }
621 if(!matched) {
622 ///ystem.err.println("Mapping " + family + " to " + mds_new);
623 mds_hashtable.put(family, mds_new);
624 }
625 fireSetChanged(mds_new);
626 return true;
627 }
628 // else we cancelled for some reason.
629 return false;
630 }
631
632 private class MergeTask
633 extends Thread {
634
635 MetadataSet mds_cur;
636 MetadataSet mds_new;
637
638 MergeTask(MetadataSet mds_cur, MetadataSet mds_new) {
639 this.mds_cur = mds_cur;
640 this.mds_new = mds_new;
641 }
642
643 public void run() {
644 mergeMDS(mds_cur, mds_new);
645 // Fire setChanged() message.
646 fireSetChanged(mds_new);
647 }
648 }
649
650
651 /** Accepts .mdv files for a certain metadata set. */
652 private class MDVFilenameFilter implements FilenameFilter
653 {
654 private String mds_namespace = null;
655
656 public MDVFilenameFilter(String mds_namespace)
657 {
658 this.mds_namespace = mds_namespace.toLowerCase();
659 }
660
661 public boolean accept(File dir, String name)
662 {
663 String copy = name.toLowerCase();
664 if (copy.startsWith(mds_namespace) && copy.endsWith(".mdv")) {
665 return true;
666 }
667
668 return false;
669 }
670 }
671
672 /** This method reloads all of the metadata sets that have been marked as included in this collection by entries in the collection configuration file.
673 */
674 public void load() {
675 File source = new File(Gatherer.c_man.getCollectionMetadata());
676 File files[] = source.listFiles();
677 for(int i = 0; files != null && i < files.length; i++) {
678 if(files[i].getName().endsWith(".mds")) {
679 importMDS(files[i], false);
680 }
681 }
682 // If no current 'hidden' metadata set exists, create one.
683 if(getSet(HIDDEN) == null) {
684 createHidden();
685 }
686 }
687 /** 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.
688 * @param mds_current The currently loaded MetadataSet.
689 * @param mds_new A new MetadataSet you wish to merge in.
690 * @return A boolean with value <i>true</i> indicating if the merge was successful, otherwise <i>false</i> if errors were detected.
691 */
692 public boolean mergeMDS(MetadataSet mds_cur, MetadataSet mds_new) {
693 // For a super quick check for equivelent trees, we compare the last changed values.
694 if(mds_cur.getLastChanged().equals(mds_new.getLastChanged())) {
695 // Exactly the same. Nothing to change.
696 return true;
697 }
698 // Show initial progress prompt.
699 prompt.startMerge(mds_new.size());
700 boolean cancel = false;
701 // For each element in the new set
702 for(int i = 0; !cancel && i < mds_new.size(); i++) {
703 boolean cont = false;
704 Element mde_new = mds_new.getElement(i);
705 GValueModel mde_values = mds_new.getValueTree(new ElementWrapper(mde_new));
706 // See if the element already exists in the current set
707 Element mde_cur = mds_cur.getElement(mde_new.getAttribute("name"));
708 int option = Declarations.NO_ACTION;
709 while(!cont && !cancel) {
710 // We may be dealing with a brand new element, or possibly a
711 // renamed one.
712 if(mde_cur == null) {
713 // Provide merge, rename and skip options.
714 option = prompt.mDSPrompt(mds_cur, null, mds_new, mde_new);
715 }
716 else {
717 // If the two elements have equal structure we only have
718 // to worry about merging the values.
719 if(MSMUtils.elementsEqual(mds_cur, mde_cur, mds_new, mde_new, false)) {
720 cancel = !mergeMDV(mds_cur, mde_cur, mds_new, mde_new);
721 cont = true;
722 }
723 else {
724 // Provide add, merge and skip options.
725 option = prompt.mDSPrompt(mds_cur, mde_cur, mds_new, mde_new);
726 }
727 }
728 String reason = null;
729 switch(option) {
730 case Declarations.ADD:
731 // Only available to brand new elements, this options
732 // simply adds the element to the set.
733 reason = mds_cur.addElement(mde_new, mde_values);
734 if(reason == null) {
735 cont = true;
736 }
737 else {
738 prompt.addFailed(mde_new, reason);
739 cont = false;
740 }
741 break;
742 case Declarations.CANCEL:
743 cancel = true;
744 cont = true;
745 break;
746 case Declarations.FORCE_MERGE:
747 // If the mde_cur is null, that means the users has asked
748 // to merge but hasn't choosen any element to merge with.
749 // Make the user select an element.
750 mde_cur = prompt.selectElement(mds_cur);
751 case Declarations.MERGE:
752 // This case in turn calls the mergeMDE method to perform
753 // the actual merging of the Elements.
754 if(mde_cur != null) {
755 cancel = !mergeMDE(mds_cur, mde_cur, mds_new, mde_new);
756 }
757 cont = true;
758 break;
759 case Declarations.RENAME:
760 // This case adds the Element, but requires the user to
761 // enter a unique name.
762 String new_name = prompt.rename(mde_new);
763 if(new_name != null && new_name.length() > 0) {
764 reason = mds_cur.addElement(mde_new, new_name, mde_values);
765 if(reason == null) {
766 mde_cur = mds_cur.getElement(new_name);
767 cont = true;
768 }
769 else {
770 prompt.renameFailed(mde_new, new_name, reason);
771 cont = false;
772 }
773 }
774 else {
775 if(new_name != null) {
776 prompt.renameFailed(mde_new, new_name,
777 "MSMPrompt.Invalid_Name");
778 }
779 cont = false;
780 }
781 break;
782 case Declarations.REPLACE:
783 // Removes the existing Element then adds the new.
784
785 mds_cur.removeElement(mde_cur);
786
787 reason = mds_cur.addElement(mde_new, mde_values);
788 if(reason == null) {
789 cont = true;
790 }
791 else {
792 prompt.removeFailed(mde_cur, reason);
793 cont = false;
794 }
795 break;
796 case Declarations.SKIP:
797 // Does not change the set.
798 cont = true;
799 break;
800 }
801 // Add this action to profile for later reference.
802 if(profiler == null) {
803 ///ystem.err.println("No Profiler");
804 }
805 //profiler.addAction(mds_new.getFile().getAbsolutePath(), MSMUtils.getFullName(mde_new), option, MSMUtils.getFullName(mde_cur));
806 }
807 prompt.incrementMerge();
808 }
809 prompt.endMerge();
810 return true;
811 }
812
813 /** 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.
814 * @param mde_cur The Element that already exists in the current metadata sets.
815 * @param mde_new A new Element which has the same name as the current one but different data.
816 * @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.
817 * TODO Implement
818 */
819 public boolean mergeMDE(MetadataSet mds_cur, Element mde_cur, MetadataSet mds_new, Element mde_new) {
820 for(Node mdn_new = mde_new.getFirstChild(); mdn_new != null; mdn_new = mdn_new.getNextSibling()) {
821 // Only merge the nodes whose name is 'Attribute'
822 if(mdn_new.getNodeName().equals("Attribute")) {
823 Element att_new = (Element) mdn_new;
824 int action = Declarations.NO_ACTION;
825 Element replace_att = null; // replace this att with the new one
826 // Unfortunately some attributes, such as author, can have several occurances, so match each in turn.
827 Element temp[] = MSMUtils.getAttributeNodesNamed(mde_cur, att_new.getAttribute("name"));
828 if (temp==null) {
829 action = Declarations.ADD;
830 } else {
831
832 // look for an exact match
833 for(int i = 0; temp != null && i < temp.length; i++) {
834 Element att_cur = temp[i];
835 if(MSMUtils.attributesEqual(att_cur, att_new)) {
836 action = Declarations.SKIP;
837 break;
838 }
839 att_cur = null;
840 }
841 if (action == Declarations.NO_ACTION) {
842 // we didn't find a match, so we have to prompt teh user for what to do
843 Object result = prompt.mDEPrompt(mde_cur, temp, mde_new, att_new);
844 if (result instanceof Integer) {
845 action = ((Integer)result).intValue();
846 } else {
847 // we have a replace action, and the returned object is the Attribute to replace
848 action = Declarations.REPLACE;
849 replace_att = (Element)result;
850 }
851 }
852 }
853
854 // now do the required action
855 switch (action) {
856 case Declarations.REPLACE:
857 // Out with the old.
858 mde_cur.removeChild(replace_att);
859 case Declarations.ADD:
860 // Simply add the new attribute. No clash is possible as we have already tested for it.
861 MSMUtils.add(mde_cur, att_new);
862 break;
863 case Declarations.SKIP:
864 // Do nothing. Move on to next attribute.
865 break;
866 case Declarations.CANCEL:
867 return false;
868 default:
869 }
870
871 att_new = null;
872 temp = null;
873 replace_att = null;
874 } // if node nmae = attribute
875 } //for each child node
876 return mergeMDV(mds_cur, mde_cur, mds_new, mde_new);
877 }
878
879 /** Merge two metadata value trees.
880 * @param mds_cur The current MetadataSet.
881 * @param mde_cur The current Element which acts as a value tree root.
882 * @param mds_new The MetadataSet we are merging in.
883 * @param mde_new The Element which acts as a value tree that we are merging in.
884 */
885 public boolean mergeMDV(MetadataSet mds_cur, Element mde_cur,
886 MetadataSet mds_new, Element mde_new) {
887 // Remember we may be asked to merge with a current mdv of null.
888 return MSMUtils.updateValueTree(mds_cur, mde_cur, mds_new, mde_new);
889 }
890
891 public void removeElement(ElementWrapper element) {
892 // Retrieve the metadata set this element belongs to.
893 String namespace = element.getNamespace();
894 MetadataSet set = (MetadataSet) mds_hashtable.get(namespace);
895 if(set != null) {
896 // Bugger. Get the old name -before- we remove the element from the set.
897 String old_name = element.toString();
898 // Remove the element.
899 set.removeElement(element.getElement());
900 // Fire event.
901 fireElementChanged(new MSMEvent(this, null, old_name));
902 }
903 else {
904 ///ystem.err.println("no such set " + namespace);
905 }
906 // No such set. No such element.
907 }
908
909 /** Remove a piece of metadata from a record or records[] and fire all the relevant events.
910 * @param records A FileNode[] of records to be changed.
911 * @param metadata The Metadata to remove.
912 */
913 public void removeMetadata(long id, Metadata metadata, FileNode records[]) {
914 // Reset undo buffer
915 undo_buffer.clear();
916 // Simplier than the others. Simply remove the metadata. Note that we only bother prompting if there is more than one
917 int action = MetaEditPrompt.CONFIRM;
918 if(records.length == 1) {
919 action = MetaEditPrompt.REMOVE;
920 }
921 // Now remove metadata from the selected file nodes.
922 for(int i = 0; action != MetaEditPrompt.CANCEL && i < records.length; i++) {
923 action = removeMetadata(id, records[i], metadata, action, (records.length > 1));
924 }
925 // If we were cancelled we should undo any changes so far
926 if(action == MetaEditPrompt.CANCEL) {
927 for(Iterator keys = undo_buffer.keySet().iterator(); keys.hasNext(); ) {
928 FileNode record = (FileNode) keys.next();
929 undoRemove(id, record);
930 }
931 }
932 }
933 /** Remove the specified listener from ourselves.
934 * @param listener The MSMListener in question.
935 */
936 public void removeMSMListener(MSMListener listener) {
937 listeners.remove(listener);
938 }
939
940 public void removeSet(MetadataSet set) {
941 mds_hashtable.remove(set.getNamespace());
942 fireSetChanged(set);
943 }
944
945 /** Rename the identifier of a given element to the name given.
946 * @param element The metadata element effected, as an ElementWrapper.
947 * @param new_name The String to use as the new name.
948 */
949 /* private void renameElement(ElementWrapper element, String new_name) {
950 Element e = element.getElement();
951 String old_name = element.toString();
952 MSMUtils.setIdentifier(e, new_name);
953 fireElementChanged(new MSMEvent(this, element, old_name));
954 old_name = null;
955 e = null;
956 } */
957 /** 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.
958 */
959 public void save() {
960 // Create the correct file to save these sets to...
961 File file = new File(Gatherer.self.getCollectionMetadata());
962 if (!file.exists()) {
963 Gatherer.println("trying to save a collection and the metadata directory does not exist - creating it!");
964 file.mkdir();
965 }
966 // And make back ups of all existing metadata set files.
967 File temp[] = file.listFiles();
968 for(int i = temp.length - 1; i >= 0; i--) {
969 if(temp[i].getName().endsWith(".mds") || temp[i].getName().endsWith(".mdv")) {
970 File backup = new File(temp[i].getAbsolutePath() + "~");
971 backup.deleteOnExit();
972 if(!temp[i].renameTo(backup)) {
973 Gatherer.println("Error in MetadataSetManager.save(): FileRenamedException");
974 }
975 }
976 }
977 // Now save the latest versions of the metadata sets.
978 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
979 String namespace = (String) keys.nextElement();
980 MetadataSet set = (MetadataSet) mds_hashtable.get(namespace);
981 try {
982 File mds_file = new File(file, set.getNamespace() + ".mds");
983 Utility.export(set.getDocument(), mds_file);
984 set.setFile(mds_file);
985 // Now for each element attempt to save its value tree.
986 NodeList elements = set.getElements();
987 for(int i = elements.getLength() - 1; i >= 0; i--) {
988 ElementWrapper value_element = new ElementWrapper((Element)elements.item(i));
989 if(value_element.hasValueTree()) {
990 GValueModel value_tree = set.getValueTree(value_element);
991 if(value_tree != null) {
992 File value_file = new File(file, value_element.getName() + ".mdv");
993 ///ystem.err.println("Saving value file: " + value_file.toString());
994 Utility.export(value_tree.getDocument(), value_file);
995 // If this is a hierarchy element, write hierarchy file.
996 if(value_element.getNamespace().equals(MetadataSetManager.HIDDEN) || value_tree.isHierarchy()) {
997 MetadataXML.write(value_element, value_tree, this, Gatherer.c_man.getCollectionEtc());
998 }
999 }
1000 }
1001 }
1002 }
1003 catch (Exception error) {
1004 error.printStackTrace();
1005 }
1006 }
1007 profiler.save();
1008 }
1009 /** 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.
1010 * @param source The source FileNode.
1011 * @param destination The new FileNode.
1012 */
1013 public final boolean searchForMetadata(FileNode destination, FileNode source, boolean folder_level) {
1014 return searchForMetadata(destination, source, folder_level, false);
1015 }
1016 public final boolean searchForMetadata(FileNode destination, FileNode source, boolean folder_level, boolean dummy_run) {
1017 ///atherer.println("MetadataSetManager.searchForMetadata()");
1018 // for some reason, the loader returns 'dialog_cancelled' ie true if cancelled, false if OK. why???
1019 // since we want to return true if successful, we'll return the opposite
1020 return (loader.searchForMetadata(destination, source, folder_level, dummy_run)?false:true);
1021 }
1022 /** Build a vector of all the metadata sets that contain an element with the given name.
1023 * @param name The name of an element as a String.
1024 * @return A Vector of metadata sets.
1025 * @see MSMPrompt (org.greenstone.gatherer.msm.MSMPrompt#selectSet)
1026 */
1027 public Vector setsThatContain(String name) {
1028 Vector result = new Vector();
1029 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
1030 MetadataSet set = (MetadataSet) mds_hashtable.get(keys.nextElement());
1031 if(set.getElement(name) != null) {
1032 result.add(set);
1033 }
1034 }
1035 return result;
1036 }
1037
1038 public final int size() {
1039 return getSets().size();
1040 }
1041
1042 /** Update a piece of metadata connected to a record or records, ensuring the value tree is built properly, and correct messaging fired.
1043 * @param records A FileNode[] of records, or directories, to add the specified metadata to.
1044 * @param element The metadata element, contained within an ElementWrapper to base metadata on.
1045 * @param value The value to assign to the metadata as a String.
1046 * @param action The default action to take in the prompt.
1047 * @param file_level If true then the metadata can be replaced normally, if false then we should actually use an add method instead.
1048 * @return The Metadata we just assigned.
1049 */
1050 public Metadata updateMetadata(long id, Metadata old_metadata, FileNode records[], String value_str, int action, boolean file_level) {
1051 // Retrieve the new value node from the same value tree as the old metadata.
1052 ElementWrapper element = old_metadata.getElement();
1053 GValueModel model = getValueTree(element);
1054 GValueNode value = null;
1055 if(model != null) {
1056 value = model.addValue(value_str);
1057 }
1058 else {
1059 value = new GValueNode(element.toString(), value_str);
1060 }
1061 // Create new metadata.
1062 Metadata new_metadata = new Metadata(value);
1063 // Reset the undo buffer
1064 undo_buffer.clear();
1065 // And update the old with it.
1066 if(action == -1) {
1067 //Note that we only bother prompting if there is more than one
1068 action = MetaEditPrompt.CONFIRM;
1069 if(records.length == 1) {
1070 action = MetaEditPrompt.OVERWRITE;
1071 }
1072 }
1073 // And then update each selection file node.
1074 for(int i = 0; action != MetaEditPrompt.CANCEL && i < records.length; i++) {
1075 action = updateMetadata(id, records[i], old_metadata, new_metadata, action, (records.length > 1), file_level);
1076 }
1077 // If we were cancelled we should undo any changes so far
1078 if(action == MetaEditPrompt.CANCEL) {
1079 for(Iterator keys = undo_buffer.keySet().iterator(); keys.hasNext(); ) {
1080 FileNode record = (FileNode) keys.next();
1081 undoUpdate(id, record);
1082 }
1083 }
1084 // All done. Any events would have been fired within the record recursion.
1085 return new_metadata;
1086 }
1087
1088 /** 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).
1089 * 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).
1090 * @param id a long unique identifier shared by all actions caused by the same gesture.
1091 * @param record the FileNode we are adding the metadata to.
1092 * @param data the new Metadata.
1093 * @param action the default action as an int. May require user interaction.
1094 * @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).
1095 * @param multiple_selection <i>true</i> if more than one file or folder was selected.
1096 * @return an int specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1097 */
1098 private int addMetadata(long id, FileNode record, Metadata data, int action, boolean multiple_selection) {
1099 // Super special exception for accumulate all action. We are going to add this metadata anyway, regardless of whats already there, so just add it.
1100 if(action == MetaEditPrompt.ACCUMULATE_ALL || action == MetaEditPrompt.OVERWRITE_ALL) {
1101 fireMetadataChanged(id, record, null, data, action - 1); // Transform action to accumulate or overwrite
1102 }
1103 else {
1104 // Recover the metadata from this file.
1105 ArrayList metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1106 // Most important test, we don't have to add the metadata if its already there!
1107 if(!metadata.contains(data)) {
1108 // Record undo information for this file node.
1109 ArrayList undo = new ArrayList();
1110 // Prepare for MEP
1111 int user_action = MetaEditPrompt.ACCUMULATE;
1112 String values = "";
1113 // See if there is any existing metadata with the same name. If so make a string from all the values (bob, jim etc).
1114 int metadata_size = metadata.size();
1115 for(int i = 0; i < metadata_size; i++) {
1116 Metadata current_data = (Metadata)metadata.get(i);
1117 if(current_data.getElement().equals(data.getElement())) {
1118 if(values.length() > 0) {
1119 values = values + ", ";
1120 }
1121 values = values + current_data.getValue();
1122 }
1123 }
1124 // If we are confirming prompt for user_action.
1125 if(values.length() > 0 && action == MetaEditPrompt.CONFIRM) {
1126 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.ADD_PROMPT, multiple_selection, record.getFile(), data.getElement().toString(), values, data.getValue());
1127 user_action = mep.display();
1128 }
1129 if(user_action == MetaEditPrompt.ACCUMULATE_ALL || user_action == MetaEditPrompt.CANCEL || user_action == MetaEditPrompt.OVERWRITE_ALL) {
1130 action = user_action;
1131 }
1132 // 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.
1133 if(action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.OVERWRITE) {
1134 for(int i = metadata_size; i != 0; i--) {
1135 Metadata old_data = (Metadata)metadata.get(i - 1);
1136 if(old_data.getElement().equals(data.getElement()) && old_data.isFileLevel()) {
1137 // We have a match. Remove this metadata.
1138 fireMetadataChanged(id, record, old_data, null, MetaEditPrompt.REMOVE);
1139 // Add it to our undo buffer.
1140 undo.add(old_data);
1141 }
1142 }
1143 }
1144 // Ensure the metadata will accumulate or overwrite as the user wishes.
1145 if(user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL) {
1146 data.setAccumulate(true);
1147 }
1148 else if(user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.OVERWRITE_ALL) {
1149 data.setAccumulate(false);
1150 }
1151 // 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...
1152 if((user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL || user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.OVERWRITE_ALL) && !metadata.contains(data)) {
1153 ///ystem.err.println("Adding metadata " + data);
1154 fireMetadataChanged(id, record, null, data, ((user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL) ? MetaEditPrompt.ACCUMULATE : MetaEditPrompt.OVERWRITE));
1155 // The last element in undo is the new element.
1156 undo.add(data);
1157 }
1158 // Store the undo list in our undo buffer.
1159 undo_buffer.put(record, undo);
1160 }
1161 }
1162 // If we've been cancelled, roll back the addition.
1163 if(action == MetaEditPrompt.CANCEL) {
1164 undoAdd(id, record);
1165 }
1166 return action;
1167 }
1168 /** addMetadata(long, FileNode, Metadata, int, boolean) */
1169
1170 /** Create the hidden mds, used for custom classifiers. */
1171 private MetadataSet createHidden() {
1172 MetadataSet hidden_mds = new MetadataSet(Utility.METADATA_SET_TEMPLATE);
1173 hidden_mds.setAttribute("creator","The Gatherer");
1174 hidden_mds.setAttribute("contact","gatherer@greenstone");
1175 hidden_mds.setAttribute("description","A hidden metadata set used to create custom classifiers.");
1176 hidden_mds.setAttribute("family","Gatherer Hidden Metadata");
1177 hidden_mds.setAttribute("lastchanged","");
1178 hidden_mds.setAttribute("name","Gatherer Hidden Metadata");
1179 hidden_mds.setAttribute("namespace",HIDDEN);
1180 mds_hashtable.put(HIDDEN, hidden_mds);
1181 fireSetChanged(hidden_mds);
1182 return hidden_mds;
1183 }
1184
1185 /** Creates a new profiler, which in turn will attempt to load previous profile information. */
1186 private void loadProfiler() {
1187 profiler = new MSMProfiler();
1188 addMSMListener(profiler);
1189 }
1190
1191 /** 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()).
1192 * @param id a unique long identifier common to all actions caused by a single gesture.
1193 * @param record the FileNode who we are removing metadata from.
1194 * @param data the <strong>Metadata</strong> you wish removed from the tree.
1195 * @param action an <i>int</i> specifying the wanted prompting action.
1196 * @param fire_event <i>true</i> if this action should fire metadata changed events.
1197 * @param multiple_selection the number of records in the selection, as an <i>int</i>. Used to determine prompt controls.
1198 * @return an <i>int</i> specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1199 */
1200 private int removeMetadata(long id, FileNode record, Metadata data, int action, boolean multiple_selection) {
1201 ArrayList metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1202 int user_action = MetaEditPrompt.REMOVE;
1203 // See if we even have this metadata.
1204 if(metadata.contains(data)) {
1205 ArrayList undo = new ArrayList();
1206 // We do have it. If action == CONFIRM, show user prompt.
1207 if(action == MetaEditPrompt.CONFIRM) {
1208 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.REMOVE_PROMPT, multiple_selection, record.getFile(), data.getElement().toString(), data.getValue(), "");
1209 user_action = mep.display();
1210 }
1211 // Set action to match the user_action under certain circumstances.
1212 if(user_action == MetaEditPrompt.CANCEL || user_action == MetaEditPrompt.REMOVE_ALL) {
1213 action = user_action;
1214 }
1215 if(action == MetaEditPrompt.REMOVE_ALL || user_action == MetaEditPrompt.REMOVE) {
1216 fireMetadataChanged(id, record, data, null, MetaEditPrompt.REMOVE);
1217 undo.add(data);
1218 }
1219 // Store undo information
1220 undo_buffer.put(record, undo);
1221 }
1222 // If we've been cancelled higher up, undo action.
1223 if(action == MetaEditPrompt.CANCEL) {
1224 undoRemove(id, record);
1225 }
1226 return action;
1227 }
1228
1229 /** Rollback any changes made as part of a single metadata add process (only valid during the action itself, ie if a user presses cancel).
1230 * @param id the unique identify of all actions created as part of a single gesture, as a <i>long</i>.
1231 * @param record the FileNode whose metadata was changed.
1232 */
1233 private void undoAdd(long id, FileNode record) {
1234 // Retrieve the undo data from the buffer
1235 ArrayList undo = (ArrayList) undo_buffer.get(record);
1236 // If there is no undo then we can't do anything, but there should be
1237 if(undo != null && undo.size() > 0) {
1238 // The last piece of data in an add actions undo buffer is the metadata that was added
1239 Metadata data = (Metadata) undo.remove(undo.size() - 1);
1240 // Remove the data
1241 fireMetadataChanged(id, record, data, null, MetaEditPrompt.REMOVE);
1242 // If we removed other metadata when adding this metadata restore it too
1243 for(int i = 0; i < undo.size(); i++) {
1244 Metadata old_data = (Metadata) undo.get(i);
1245 fireMetadataChanged(id, record, null, old_data, MetaEditPrompt.ACCUMULATE);
1246 }
1247 }
1248 }
1249 /** Rollback any changes made as part of a single metadata remove process (only valid during the action itself, ie if a user presses cancel).
1250 * @param id the unique identify of all actions created as part of a single gesture, as a long.
1251 * @param record the FileNode metadata was removed from.
1252 */
1253 private void undoRemove(long id, FileNode record) {
1254 // Retrieve undo information
1255 ArrayList undo = (ArrayList) undo_buffer.get(record);
1256 // Ensure that we have something to undo
1257 if(undo != null && undo.size() == 1) {
1258 // The undo buffer should contain exactly one entry, the metadata removed
1259 Metadata data = (Metadata) undo.get(0);
1260 fireMetadataChanged(id, record, null, data, MetaEditPrompt.ACCUMULATE);
1261 }
1262 }
1263 /** 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).
1264 * @param id the unique identify of all actions created as part of a single gesture, as a long.
1265 * @param record the FileNode whose metadata was changed.
1266 */
1267 private void undoUpdate(long id, FileNode record) {
1268 // Retrieve undo information
1269 ArrayList undo = (ArrayList) undo_buffer.get(record);
1270 if(undo != null && undo.size() == 2) {
1271 Metadata old_data = (Metadata) undo.get(0);
1272 Metadata new_data = (Metadata) undo.get(1);
1273 fireMetadataChanged(id, record, new_data, null, MetaEditPrompt.REMOVE);
1274 if(old_data != new_data) { // Correct reference comparison
1275 fireMetadataChanged(id, record, null, old_data, MetaEditPrompt.ACCUMULATE);
1276 }
1277 }
1278 }
1279
1280 /** 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.
1281 * @param id the unique identify of all actions created as part of a single gesture, as a <i>long</i>.
1282 * @param record the FileNode whose metadata we are changing.
1283 * @param old_data The old existing <strong>Metadata</strong>.
1284 * @param new_data The new updated <strong>Metadata</strong>.
1285 * @param action An <i>int</i> indicating what we are going to do about it.
1286 * @param multiple_selection The number of records in the selection, as an <i>int</i>. Used to determine prompt controls.
1287 * @return An <i>int</i> specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1288 */
1289 private int updateMetadata(long id, FileNode record, Metadata old_data, Metadata new_data, int action, boolean multiple_selection, boolean file_level) {
1290 ArrayList metadata;
1291 if(file_level) {
1292 metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1293 }
1294 else {
1295 metadata = Gatherer.c_man.getCollection().gdm.getAllMetadata(record.getFile());
1296 }
1297 int user_action = MetaEditPrompt.OVERWRITE;
1298 // Standard case of updating an existing metadata value.
1299 if(metadata.contains(old_data)) {
1300 ArrayList undo = new ArrayList();
1301 // If we are to prompt the user, do so.
1302 if(action == MetaEditPrompt.CONFIRM) {
1303 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.UPDATE_PROMPT, multiple_selection, record.getFile(), old_data.getElement().toString(), old_data.getValue(), new_data.getValue());
1304 user_action = mep.display();
1305 }
1306 // Some user actions should have a continuous effect.
1307 if(user_action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.CANCEL) {
1308 action = user_action;
1309 }
1310 // And if the update chose update, do so.
1311 if(action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.UPDATE_ONCE) {
1312 ///ystem.err.println("Updating:\n"+old_data+"\nto\n"+new_data);
1313 // If this is file level then we can do a normal replace
1314 if(file_level) {
1315 fireMetadataChanged(id, record, old_data, new_data, MetaEditPrompt.OVERWRITE);
1316 undo.add(old_data);
1317 undo.add(new_data);
1318 }
1319 // 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.
1320 else {
1321 fireMetadataChanged(id, record, null, new_data, MetaEditPrompt.OVERWRITE);
1322 undo.add(new_data);
1323 undo.add(new_data);
1324 }
1325 }
1326 // Store the undo information
1327 undo_buffer.put(record, undo);
1328 }
1329 // If we've been cancelled undo.
1330 if(action == MetaEditPrompt.CANCEL) {
1331 undoUpdate(id, record);
1332 }
1333 return action;
1334 }
1335}
Note: See TracBrowser for help on using the repository browser.