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

Last change on this file since 7540 was 7540, checked in by mdewsnip, 20 years ago

Some minor tidy ups with removing dead code.

  • Property svn:keywords set to Author Date Id Revision
File size: 55.9 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 javax.swing.tree.TreePath;
44import org.greenstone.gatherer.Configuration;
45import org.greenstone.gatherer.Dictionary;
46import org.greenstone.gatherer.Gatherer;
47import org.greenstone.gatherer.cdm.CommandTokenizer;
48import org.greenstone.gatherer.file.FileNode;
49import org.greenstone.gatherer.gui.MetaEditPrompt;
50import org.greenstone.gatherer.mem.MetadataEditorManager;
51import org.greenstone.gatherer.msm.Declarations;
52import org.greenstone.gatherer.msm.MDSFileFilter;
53import org.greenstone.gatherer.msm.MetadataSet;
54import org.greenstone.gatherer.msm.MSMAction;
55import org.greenstone.gatherer.msm.MSMEvent;
56import org.greenstone.gatherer.msm.MSMPrompt;
57import org.greenstone.gatherer.msm.MSMUtils;
58import org.greenstone.gatherer.valuetree.GValueModel;
59import org.greenstone.gatherer.valuetree.GValueNode;
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 MetadataXMLFileParser 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 MetadataXMLFileParser();
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 id
103 * @param records A FileNode[] of records, or directories, to add the specified metadata to.
104 * @param element The metadata element, contained within an ElementWrapper to base metadata on.
105 * @param value_str The value to assign to the metadata as a String.
106 */
107 public Metadata addMetadata(long id, FileNode records[], ElementWrapper element, String value_str) {
108 Metadata metadata = null;
109 if (records.length == 1) {
110 metadata = addMetadata(id, records, element, value_str, MetaEditPrompt.ACCUMULATE_ALL);
111 }
112 else {
113 metadata = addMetadata(id, records, element, value_str, MetaEditPrompt.CONFIRM);
114 }
115 return metadata;
116 }
117 public Metadata addMetadata(long id, FileNode records[], ElementWrapper element, String value_str, int action) {
118 // Retrieve the appropriate value node from the value tree for this element, creating it if necessary.
119 GValueModel model = getValueTree(element);
120 GValueNode value = null;
121 if(model != null) {
122 value = model.addValue(value_str); // Only adds if not already present, otherwise just returns existing node.
123 }
124 else {
125 value = new GValueNode(element.toString(), value_str);
126 }
127 // Create new metadata.
128 Metadata metadata = new Metadata(element, value);
129 // Reset the undo buffer.
130 undo_buffer.clear();
131 // Assign to records. Note that we must watch for responses from the user prompts, and cease loop if break signalled.
132 // Now add the metadata to each selected file node.
133 for(int i = 0; action != MetaEditPrompt.CANCEL && i < records.length; i++) {
134 action = addMetadata(id, records[i], metadata, action, (records.length > 1));
135 }
136 // If we were cancelled we should undo any changes so far
137 if(action == MetaEditPrompt.CANCEL) {
138 for(Iterator keys = undo_buffer.keySet().iterator(); keys.hasNext(); ) {
139 FileNode record = (FileNode) keys.next();
140 undoAdd(id, record);
141 }
142 }
143 return metadata;
144 }
145
146 /** Adds a metadata set listener to this set, if it isn't alreay listening.
147 * @param listener The new MSMListener.
148 */
149 public void addMSMListener(MSMListener listener) {
150 if(!listeners.contains(listener)) {
151 listeners.add(listener);
152 }
153 }
154
155 public MetadataSet addSet(String namespace, String name) {
156 MetadataSet mds = new MetadataSet(Utility.METADATA_SET_TEMPLATE);
157 mds.setAttribute("creator", "The Greenstone Librarian Interface");
158 // Calculate lastchanged to right now on this machine by this user
159 String user_name = System.getProperty("user.name");
160 String machine_name = Utility.getMachineName();
161 mds.setAttribute("lastchanged", Utility.getDateString() + " - " + user_name + " on " + machine_name);
162 // And the remaining attributes.
163 //mds.setAttribute("name", name);
164 mds.setAttribute("namespace", namespace);
165 mds_hashtable.put(namespace, mds);
166 // Add the name element.
167 mds.setName(name);
168 fireSetChanged(mds);
169 return mds;
170 }
171
172 /** Add a value tree to a given metadata element represented as a GValueModel
173 * @param model The <strong>GValueTree</strong> model
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(MetadataSet set, int action) {
195 MetadataEditorManager mem = new MetadataEditorManager(set, action);
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
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
475 /** Retrieve the named metadata set.
476 * @param name The sets name as a String.
477 * @return The MetadataSet as named, or null if no such set.
478 */
479 public MetadataSet getSet(String name) {
480 if(mds_hashtable.containsKey(name)) {
481 return (MetadataSet) mds_hashtable.get(name);
482 }
483 else if(name.equals(HIDDEN)) {
484 return createHidden();
485 }
486 return null;
487 }
488
489 /** Method to retrieve all of the metadata sets loaded in this collection.
490 * @return A Vector of metadata sets.
491 */
492 public Vector getSets() {
493 return getSets(true);
494 }
495
496 public Vector getSets(boolean include_greenstone_extracted) {
497 Vector result = new Vector();
498 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
499 MetadataSet set = (MetadataSet)mds_hashtable.get(keys.nextElement());
500 if(!set.getNamespace().equals(HIDDEN) && (include_greenstone_extracted || !set.getNamespace().equals(Utility.EXTRACTED_METADATA_NAMESPACE))) {
501 result.add(set);
502 }
503 }
504 return result;
505 }
506
507 /** Find the total number of elements loaded.
508 * @return The element count as an int.
509 */
510 public int getSize() {
511 int count = 0;
512 if(mds_hashtable.size() > 0) {
513 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements();) {
514 MetadataSet mds = (MetadataSet)mds_hashtable.get(keys.nextElement());
515 if(mds.getNamespace().equals(HIDDEN)) {
516 count = count + mds.size();
517 }
518 }
519 }
520 return count;
521 }
522 /** Get the value tree that matches the given element.
523 * @param element The ElementWrapper representing the element.
524 * @return The GValueModel representing the value tree or null.
525 */
526 public GValueModel getValueTree(ElementWrapper element) {
527 GValueModel value_tree = null;
528 if(element != null) {
529 String namespace = element.getNamespace();
530 if(namespace.length() > 0) {
531 MetadataSet mds = (MetadataSet) mds_hashtable.get(namespace);
532 if(mds != null) {
533 value_tree = mds.getValueTree(element);
534 }
535 }
536 }
537 return value_tree;
538 }
539 /** 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.
540 * @return A boolean which is <i>true</i> if the metadata set has been imported successfully, <i>false</i> otherwise.
541 */
542 public boolean importMDS() {
543 JFileChooser chooser = new JFileChooser(new File(Utility.METADATA_DIR));
544 javax.swing.filechooser.FileFilter filter = new MDSFileFilter();
545 chooser.setFileFilter(filter);
546 int returnVal = chooser.showDialog(Gatherer.g_man, Dictionary.get("MSMPrompt.File_Import"));
547 if(returnVal == JFileChooser.APPROVE_OPTION) {
548 return importMDS(chooser.getSelectedFile(), true);
549 }
550 return false;
551 }
552
553 public boolean importMDS(File mds_file, boolean user_driven) {
554 // 1. Parse the new file.
555 MetadataSet mds_new = new MetadataSet(mds_file);
556 if(user_driven) {
557 // Display a prompt asking how much of the value structure the user wishes to import.
558 // ...but only if there are some MDV files to read values from
559 FilenameFilter mdv_filter = new MDVFilenameFilter(mds_new.getNamespace());
560 File[] mdv_files = mds_file.getParentFile().listFiles(mdv_filter);
561 if (mdv_files.length > 0) {
562 ExportMDSPrompt imdsp = new ExportMDSPrompt(this, false);
563 int result = imdsp.display();
564 if(result == ExportMDSPrompt.EXPORT) { // Here export means the user didn't cancel.
565 switch(imdsp.getSelectedCondition()) {
566 case MetadataSet.NO_VALUES:
567 mds_new = new MetadataSet(mds_new, MetadataSet.NO_VALUES);
568 break;
569 case MetadataSet.SUBJECTS_ONLY:
570 mds_new = new MetadataSet(mds_new, MetadataSet.SUBJECTS_ONLY);
571 break;
572 default: // ALL_VALUES
573 // Don't do anything.
574 }
575 }
576 else {
577 mds_new = null;
578 }
579 imdsp.dispose();
580 imdsp = null;
581 }
582 }
583 // Carry on importing the new collection
584 if(mds_new != null && mds_new.getDocument() != null) {
585 String family = mds_new.getNamespace();
586 // 2. See if we have another metadata set of the same family
587 // already. If so retrieve it and merge.
588 boolean matched = false;
589 for(Enumeration keys = mds_hashtable.keys();
590 keys.hasMoreElements();) {
591 String key = (String)keys.nextElement();
592 if(key.equals(family)) {
593 matched = true;
594 MetadataSet mds_cur = (MetadataSet)mds_hashtable.get(key);
595 ///ystem.err.println("Merging " + mds_new + " into " + mds_cur);
596 MergeTask task = new MergeTask(mds_cur, mds_new);
597 task.start();
598 }
599 }
600 if(!matched) {
601 ///ystem.err.println("Mapping " + family + " to " + mds_new);
602 mds_hashtable.put(family, mds_new);
603 }
604 fireSetChanged(mds_new);
605 return true;
606 }
607 // else we cancelled for some reason.
608 return false;
609 }
610
611 private class MergeTask
612 extends Thread {
613
614 MetadataSet mds_cur;
615 MetadataSet mds_new;
616
617 MergeTask(MetadataSet mds_cur, MetadataSet mds_new) {
618 this.mds_cur = mds_cur;
619 this.mds_new = mds_new;
620 }
621
622 public void run() {
623 mergeMDS(mds_cur, mds_new);
624 // Fire setChanged() message.
625 fireSetChanged(mds_new);
626 }
627 }
628
629
630 /** Accepts .mdv files for a certain metadata set. */
631 private class MDVFilenameFilter implements FilenameFilter
632 {
633 private String mds_namespace = null;
634
635 public MDVFilenameFilter(String mds_namespace)
636 {
637 this.mds_namespace = mds_namespace.toLowerCase();
638 }
639
640 public boolean accept(File dir, String name)
641 {
642 String copy = name.toLowerCase();
643 if (copy.startsWith(mds_namespace) && copy.endsWith(".mdv")) {
644 return true;
645 }
646
647 return false;
648 }
649 }
650
651 /** This method reloads all of the metadata sets that have been marked as included in this collection by entries in the collection configuration file.
652 */
653 public void load() {
654 File source = new File(Gatherer.c_man.getCollectionMetadata());
655 File files[] = source.listFiles();
656 for(int i = 0; files != null && i < files.length; i++) {
657 if(files[i].getName().endsWith(".mds")) {
658 importMDS(files[i], false);
659 }
660 }
661 // If no current 'hidden' metadata set exists, create one.
662 if(getSet(HIDDEN) == null) {
663 createHidden();
664 }
665 }
666 /** 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.
667 * @param mds_cur The currently loaded MetadataSet.
668 * @param mds_new A new MetadataSet you wish to merge in.
669 * @return A boolean with value <i>true</i> indicating if the merge was successful, otherwise <i>false</i> if errors were detected.
670 */
671 public boolean mergeMDS(MetadataSet mds_cur, MetadataSet mds_new) {
672 // For a super quick check for equivelent trees, we compare the last changed values.
673 if(mds_cur.getLastChanged().equals(mds_new.getLastChanged())) {
674 // Exactly the same. Nothing to change.
675 return true;
676 }
677 // Show initial progress prompt.
678 prompt.startMerge(mds_new.size());
679 boolean cancel = false;
680 // For each element in the new set
681 for(int i = 0; !cancel && i < mds_new.size(); i++) {
682 boolean cont = false;
683 Element mde_new = mds_new.getElement(i);
684 GValueModel mde_values = mds_new.getValueTree(new ElementWrapper(mde_new));
685 // See if the element already exists in the current set
686 Element mde_cur = mds_cur.getElement(mde_new.getAttribute("name"));
687 int option = Declarations.NO_ACTION;
688 while(!cont && !cancel) {
689 // We may be dealing with a brand new element, or possibly a
690 // renamed one.
691 if(mde_cur == null) {
692 // Provide merge, rename and skip options.
693 option = prompt.mDSPrompt(mds_cur, null, mds_new, mde_new);
694 }
695 else {
696 // If the two elements have equal structure we only have
697 // to worry about merging the values.
698 if(MSMUtils.elementsEqual(mds_cur, mde_cur, mds_new, mde_new, false)) {
699 cancel = !mergeMDV(mds_cur, mde_cur, mds_new, mde_new);
700 cont = true;
701 }
702 else {
703 // Provide add, merge and skip options.
704 option = prompt.mDSPrompt(mds_cur, mde_cur, mds_new, mde_new);
705 }
706 }
707 String reason = null;
708 switch(option) {
709 case Declarations.ADD:
710 // Only available to brand new elements, this options
711 // simply adds the element to the set.
712 reason = mds_cur.addElement(mde_new, mde_values);
713 if(reason == null) {
714 cont = true;
715 }
716 else {
717 prompt.addFailed(mde_new, reason);
718 cont = false;
719 }
720 break;
721 case Declarations.CANCEL:
722 cancel = true;
723 cont = true;
724 break;
725 case Declarations.FORCE_MERGE:
726 // If the mde_cur is null, that means the users has asked
727 // to merge but hasn't choosen any element to merge with.
728 // Make the user select an element.
729 mde_cur = prompt.selectElement(mds_cur);
730 case Declarations.MERGE:
731 // This case in turn calls the mergeMDE method to perform
732 // the actual merging of the Elements.
733 if(mde_cur != null) {
734 cancel = !mergeMDE(mds_cur, mde_cur, mds_new, mde_new);
735 }
736 cont = true;
737 break;
738 case Declarations.RENAME:
739 // This case adds the Element, but requires the user to
740 // enter a unique name.
741 String new_name = prompt.rename(mde_new);
742 if(new_name != null && new_name.length() > 0) {
743 reason = mds_cur.addElement(mde_new, new_name, mde_values);
744 if(reason == null) {
745 mde_cur = mds_cur.getElement(new_name);
746 cont = true;
747 }
748 else {
749 prompt.renameFailed(mde_new, new_name, reason);
750 cont = false;
751 }
752 }
753 else {
754 if(new_name != null) {
755 prompt.renameFailed(mde_new, new_name,
756 "MSMPrompt.Invalid_Name");
757 }
758 cont = false;
759 }
760 break;
761 case Declarations.REPLACE:
762 // Removes the existing Element then adds the new.
763
764 mds_cur.removeElement(mde_cur);
765
766 reason = mds_cur.addElement(mde_new, mde_values);
767 if(reason == null) {
768 cont = true;
769 }
770 else {
771 prompt.removeFailed(mde_cur, reason);
772 cont = false;
773 }
774 break;
775 case Declarations.SKIP:
776 // Does not change the set.
777 cont = true;
778 break;
779 }
780 // Add this action to profile for later reference.
781 if(profiler == null) {
782 ///ystem.err.println("No Profiler");
783 }
784 //profiler.addAction(mds_new.getFile().getAbsolutePath(), MSMUtils.getFullName(mde_new), option, MSMUtils.getFullName(mde_cur));
785 }
786 prompt.incrementMerge();
787 }
788 prompt.endMerge();
789 return true;
790 }
791
792 /** 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.
793 * @param mde_cur The Element that already exists in the current metadata sets.
794 * @param mde_new A new Element which has the same name as the current one but different data.
795 * @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.
796 * TODO Implement
797 */
798 public boolean mergeMDE(MetadataSet mds_cur, Element mde_cur, MetadataSet mds_new, Element mde_new) {
799 for(Node mdn_new = mde_new.getFirstChild(); mdn_new != null; mdn_new = mdn_new.getNextSibling()) {
800 // Only merge the nodes whose name is 'Attribute'
801 if(mdn_new.getNodeName().equals("Attribute")) {
802 Element att_new = (Element) mdn_new;
803 int action = Declarations.NO_ACTION;
804 Element replace_att = null; // replace this att with the new one
805 // Unfortunately some attributes, such as author, can have several occurances, so match each in turn.
806 Element temp[] = MSMUtils.getAttributeNodesNamed(mde_cur, att_new.getAttribute("name"));
807 if (temp==null) {
808 action = Declarations.ADD;
809 } else {
810
811 // look for an exact match
812 for(int i = 0; temp != null && i < temp.length; i++) {
813 Element att_cur = temp[i];
814 if(MSMUtils.attributesEqual(att_cur, att_new)) {
815 action = Declarations.SKIP;
816 break;
817 }
818 att_cur = null;
819 }
820 if (action == Declarations.NO_ACTION) {
821 // we didn't find a match, so we have to prompt teh user for what to do
822 Object result = prompt.mDEPrompt(mde_cur, temp, mde_new, att_new);
823 if (result instanceof Integer) {
824 action = ((Integer)result).intValue();
825 } else {
826 // we have a replace action, and the returned object is the Attribute to replace
827 action = Declarations.REPLACE;
828 replace_att = (Element)result;
829 }
830 }
831 }
832
833 // now do the required action
834 switch (action) {
835 case Declarations.REPLACE:
836 // Out with the old.
837 mde_cur.removeChild(replace_att);
838 case Declarations.ADD:
839 // Simply add the new attribute. No clash is possible as we have already tested for it.
840 MSMUtils.add(mde_cur, att_new);
841 break;
842 case Declarations.SKIP:
843 // Do nothing. Move on to next attribute.
844 break;
845 case Declarations.CANCEL:
846 return false;
847 default:
848 }
849
850 att_new = null;
851 temp = null;
852 replace_att = null;
853 } // if node nmae = attribute
854 } //for each child node
855 return mergeMDV(mds_cur, mde_cur, mds_new, mde_new);
856 }
857
858 /** Merge two metadata value trees.
859 * @param mds_cur The current MetadataSet.
860 * @param mde_cur The current Element which acts as a value tree root.
861 * @param mds_new The MetadataSet we are merging in.
862 * @param mde_new The Element which acts as a value tree that we are merging in.
863 */
864 public boolean mergeMDV(MetadataSet mds_cur, Element mde_cur,
865 MetadataSet mds_new, Element mde_new) {
866 // Remember we may be asked to merge with a current mdv of null.
867 return MSMUtils.updateValueTree(mds_cur, mde_cur, mds_new, mde_new);
868 }
869
870 public void removeElement(ElementWrapper element) {
871 // Retrieve the metadata set this element belongs to.
872 String namespace = element.getNamespace();
873 MetadataSet set = (MetadataSet) mds_hashtable.get(namespace);
874 if(set != null) {
875 // Bugger. Get the old name -before- we remove the element from the set.
876 String old_name = element.toString();
877 // Remove the element.
878 set.removeElement(element.getElement());
879 // Fire event.
880 fireElementChanged(new MSMEvent(this, null, old_name));
881 }
882 else {
883 ///ystem.err.println("no such set " + namespace);
884 }
885 // No such set. No such element.
886 }
887
888 /** Remove a piece of metadata from a record or records[] and fire all the relevant events.
889 * @param records A FileNode[] of records to be changed.
890 * @param metadata The Metadata to remove.
891 */
892 public void removeMetadata(long id, Metadata metadata, FileNode records[]) {
893 // Reset undo buffer
894 undo_buffer.clear();
895 // Simplier than the others. Simply remove the metadata. Note that we only bother prompting if there is more than one
896 int action = MetaEditPrompt.CONFIRM;
897 if(records.length == 1) {
898 action = MetaEditPrompt.REMOVE;
899 }
900 // Now remove metadata from the selected file nodes.
901 for(int i = 0; action != MetaEditPrompt.CANCEL && i < records.length; i++) {
902 action = removeMetadata(id, records[i], metadata, action, (records.length > 1));
903 }
904 // If we were cancelled we should undo any changes so far
905 if(action == MetaEditPrompt.CANCEL) {
906 for(Iterator keys = undo_buffer.keySet().iterator(); keys.hasNext(); ) {
907 FileNode record = (FileNode) keys.next();
908 undoRemove(id, record);
909 }
910 }
911 }
912 /** Remove the specified listener from ourselves.
913 * @param listener The MSMListener in question.
914 */
915 public void removeMSMListener(MSMListener listener) {
916 listeners.remove(listener);
917 }
918
919 public void removeSet(MetadataSet set) {
920 mds_hashtable.remove(set.getNamespace());
921 fireSetChanged(set);
922 }
923
924 /** Rename the identifier of a given element to the name given.
925 * @param element The metadata element effected, as an ElementWrapper.
926 * @param new_name The String to use as the new name.
927 */
928 /* private void renameElement(ElementWrapper element, String new_name) {
929 Element e = element.getElement();
930 String old_name = element.toString();
931 MSMUtils.setIdentifier(e, new_name);
932 fireElementChanged(new MSMEvent(this, element, old_name));
933 old_name = null;
934 e = null;
935 } */
936 /** 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.
937 */
938 public void save() {
939 // Create the correct file to save these sets to...
940 File file = new File(Gatherer.self.getCollectionMetadata());
941 if (!file.exists()) {
942 Gatherer.println("trying to save a collection and the metadata directory does not exist - creating it!");
943 file.mkdir();
944 }
945 // And make back ups of all existing metadata set files.
946 File temp[] = file.listFiles();
947 for(int i = temp.length - 1; i >= 0; i--) {
948 if(temp[i].getName().endsWith(".mds") || temp[i].getName().endsWith(".mdv")) {
949 File backup = new File(temp[i].getAbsolutePath() + "~");
950 backup.deleteOnExit();
951 if(!temp[i].renameTo(backup)) {
952 Gatherer.println("Error in MetadataSetManager.save(): FileRenamedException");
953 }
954 }
955 }
956 // Now save the latest versions of the metadata sets.
957 for(Enumeration keys = mds_hashtable.keys(); keys.hasMoreElements(); ) {
958 String namespace = (String) keys.nextElement();
959 MetadataSet set = (MetadataSet) mds_hashtable.get(namespace);
960 try {
961 File mds_file = new File(file, set.getNamespace() + ".mds");
962 Utility.export(set.getDocument(), mds_file);
963 set.setFile(mds_file);
964 // Now for each element attempt to save its value tree.
965 NodeList elements = set.getElements();
966 for(int i = elements.getLength() - 1; i >= 0; i--) {
967 ElementWrapper value_element = new ElementWrapper((Element)elements.item(i));
968 if(value_element.hasValueTree()) {
969 GValueModel value_tree = set.getValueTree(value_element);
970 if(value_tree != null) {
971 File value_file = new File(file, value_element.getName() + ".mdv");
972 ///ystem.err.println("Saving value file: " + value_file.toString());
973 Utility.export(value_tree.getDocument(), value_file);
974 // If this is a hierarchy element, write hierarchy file.
975 if(value_element.getNamespace().equals(MetadataSetManager.HIDDEN) || value_tree.isHierarchy()) {
976 write(value_element, value_tree, Gatherer.c_man.getCollectionEtc());
977 }
978 }
979 }
980 }
981 }
982 catch (Exception error) {
983 error.printStackTrace();
984 }
985 }
986 profiler.save();
987 }
988 /** 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.
989 * @param source The source FileNode.
990 * @param destination The new FileNode.
991 */
992 public final boolean searchForMetadata(FileNode destination, FileNode source, boolean folder_level) {
993 return searchForMetadata(destination, source, folder_level, false);
994 }
995 public final boolean searchForMetadata(FileNode destination, FileNode source, boolean folder_level, boolean dummy_run) {
996 ///atherer.println("MetadataSetManager.searchForMetadata()");
997 // for some reason, the loader returns 'dialog_cancelled' ie true if cancelled, false if OK. why???
998 // since we want to return true if successful, we'll return the opposite
999 return (loader.searchForMetadata(destination, source, folder_level, dummy_run)?false:true);
1000 }
1001
1002 public final int size() {
1003 return getSets().size();
1004 }
1005
1006 /** Update a piece of metadata connected to a record or records, ensuring the value tree is built properly, and correct messaging fired.
1007 * @param id
1008 * @param old_metadata The metadata element,
1009 * @param records A FileNode[] of records, or directories, to add the specified metadata to.
1010 * @param value_str The value to assign to the metadata as a String.
1011 * @param action The default action to take in the prompt.
1012 * @param file_level If true then the metadata can be replaced normally, if false then we should actually use an add method instead.
1013 * @return The Metadata we just assigned.
1014 */
1015 public Metadata updateMetadata(long id, Metadata old_metadata, FileNode records[], String value_str, int action, boolean file_level) {
1016 // Retrieve the new value node from the same value tree as the old metadata.
1017 ElementWrapper element = old_metadata.getElement();
1018 GValueModel model = getValueTree(element);
1019 GValueNode value = null;
1020 if(model != null) {
1021 value = model.addValue(value_str);
1022 }
1023 else {
1024 value = new GValueNode(element.toString(), value_str);
1025 }
1026 // Create new metadata.
1027 Metadata new_metadata = new Metadata(value);
1028 // Reset the undo buffer
1029 undo_buffer.clear();
1030 // And update the old with it.
1031 if(action == -1) {
1032 //Note that we only bother prompting if there is more than one
1033 action = MetaEditPrompt.CONFIRM;
1034 if(records.length == 1) {
1035 action = MetaEditPrompt.OVERWRITE;
1036 }
1037 }
1038 // And then update each selection file node.
1039 for(int i = 0; action != MetaEditPrompt.CANCEL && i < records.length; i++) {
1040 action = updateMetadata(id, records[i], old_metadata, new_metadata, action, (records.length > 1), file_level);
1041 }
1042 // If we were cancelled we should undo any changes so far
1043 if(action == MetaEditPrompt.CANCEL) {
1044 for(Iterator keys = undo_buffer.keySet().iterator(); keys.hasNext(); ) {
1045 FileNode record = (FileNode) keys.next();
1046 undoUpdate(id, record);
1047 }
1048 }
1049 // All done. Any events would have been fired within the record recursion.
1050 return new_metadata;
1051 }
1052
1053 /** 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).
1054 * 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 MetadataXMLFileManager (which, given this method may have been called from MetadataXMLFileManager as well, means the cycle is complete. Um, that doesn't mean theres an infinite loop... I hope).
1055 * @param id a long unique identifier shared by all actions caused by the same gesture.
1056 * @param record the FileNode we are adding the metadata to.
1057 * @param data the new Metadata.
1058 * @param action the default action as an int. May require user interaction.
1059 * @param multiple_selection <i>true</i> if more than one file or folder was selected.
1060 * @return an int specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1061 */
1062 private int addMetadata(long id, FileNode record, Metadata data, int action, boolean multiple_selection) {
1063 // Super special exception for accumulate all action. We are going to add this metadata anyway, regardless of whats already there, so just add it.
1064 if(action == MetaEditPrompt.ACCUMULATE_ALL || action == MetaEditPrompt.OVERWRITE_ALL) {
1065 fireMetadataChanged(id, record, null, data, action - 1); // Transform action to accumulate or overwrite
1066 }
1067 else {
1068 // Recover the metadata from this file.
1069 ArrayList metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1070 // Most important test, we don't have to add the metadata if its already there!
1071 if(!metadata.contains(data)) {
1072 // Record undo information for this file node.
1073 ArrayList undo = new ArrayList();
1074 // Prepare for MEP
1075 int user_action = MetaEditPrompt.ACCUMULATE;
1076 String values = "";
1077 // See if there is any existing metadata with the same name. If so make a string from all the values (bob, jim etc).
1078 int metadata_size = metadata.size();
1079 for(int i = 0; i < metadata_size; i++) {
1080 Metadata current_data = (Metadata)metadata.get(i);
1081 if(current_data.getElement().equals(data.getElement())) {
1082 if(values.length() > 0) {
1083 values = values + ", ";
1084 }
1085 values = values + current_data.getValue();
1086 }
1087 }
1088 // If we are confirming prompt for user_action.
1089 if(values.length() > 0 && action == MetaEditPrompt.CONFIRM) {
1090 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.ADD_PROMPT, multiple_selection, record.getFile(), data.getElement().toString(), values, data.getValue());
1091 user_action = mep.display();
1092 }
1093 if(user_action == MetaEditPrompt.ACCUMULATE_ALL || user_action == MetaEditPrompt.CANCEL || user_action == MetaEditPrompt.OVERWRITE_ALL) {
1094 action = user_action;
1095 }
1096 // 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.
1097 if(action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.OVERWRITE) {
1098 for(int i = metadata_size; i != 0; i--) {
1099 Metadata old_data = (Metadata)metadata.get(i - 1);
1100 if(old_data.getElement().equals(data.getElement()) && old_data.isFileLevel()) {
1101 // We have a match. Remove this metadata.
1102 fireMetadataChanged(id, record, old_data, null, MetaEditPrompt.REMOVE);
1103 // Add it to our undo buffer.
1104 undo.add(old_data);
1105 }
1106 }
1107 }
1108 // Ensure the metadata will accumulate or overwrite as the user wishes.
1109 if(user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL) {
1110 data.setAccumulate(true);
1111 }
1112 else if(user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.OVERWRITE_ALL) {
1113 data.setAccumulate(false);
1114 }
1115 // 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...
1116 if((user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL || user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.OVERWRITE_ALL) && !metadata.contains(data)) {
1117 ///ystem.err.println("Adding metadata " + data);
1118 fireMetadataChanged(id, record, null, data, ((user_action == MetaEditPrompt.ACCUMULATE || user_action == MetaEditPrompt.ACCUMULATE_ALL) ? MetaEditPrompt.ACCUMULATE : MetaEditPrompt.OVERWRITE));
1119 // The last element in undo is the new element.
1120 undo.add(data);
1121 }
1122 // Store the undo list in our undo buffer.
1123 undo_buffer.put(record, undo);
1124 }
1125 }
1126 // If we've been cancelled, roll back the addition.
1127 if(action == MetaEditPrompt.CANCEL) {
1128 undoAdd(id, record);
1129 }
1130 return action;
1131 }
1132 /** addMetadata(long, FileNode, Metadata, int, boolean) */
1133
1134 /** Create the hidden mds, used for custom classifiers. */
1135 private MetadataSet createHidden() {
1136 MetadataSet hidden_mds = new MetadataSet(Utility.METADATA_SET_TEMPLATE);
1137 hidden_mds.setAttribute("creator","The Gatherer");
1138 hidden_mds.setAttribute("contact","gatherer@greenstone");
1139 hidden_mds.setAttribute("description","A hidden metadata set used to create custom classifiers.");
1140 hidden_mds.setAttribute("family","Gatherer Hidden Metadata");
1141 hidden_mds.setAttribute("lastchanged","");
1142 hidden_mds.setAttribute("name","Gatherer Hidden Metadata");
1143 hidden_mds.setAttribute("namespace",HIDDEN);
1144 mds_hashtable.put(HIDDEN, hidden_mds);
1145 fireSetChanged(hidden_mds);
1146 return hidden_mds;
1147 }
1148
1149 /** Creates a new profiler, which in turn will attempt to load previous profile information. */
1150 private void loadProfiler() {
1151 profiler = new MSMProfiler();
1152 addMSMListener(profiler);
1153 }
1154
1155 /** 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()).
1156 * @param id a unique long identifier common to all actions caused by a single gesture.
1157 * @param record the FileNode who we are removing metadata from.
1158 * @param data the <strong>Metadata</strong> you wish removed from the tree.
1159 * @param action an <i>int</i> specifying the wanted prompting action.
1160 * @param multiple_selection the number of records in the selection, as an <i>int</i>. Used to determine prompt controls.
1161 * @return an <i>int</i> specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1162 */
1163 private int removeMetadata(long id, FileNode record, Metadata data, int action, boolean multiple_selection) {
1164 ArrayList metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1165 int user_action = MetaEditPrompt.REMOVE;
1166 // See if we even have this metadata.
1167 if(metadata.contains(data)) {
1168 ArrayList undo = new ArrayList();
1169 // We do have it. If action == CONFIRM, show user prompt.
1170 if(action == MetaEditPrompt.CONFIRM) {
1171 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.REMOVE_PROMPT, multiple_selection, record.getFile(), data.getElement().toString(), data.getValue(), "");
1172 user_action = mep.display();
1173 }
1174 // Set action to match the user_action under certain circumstances.
1175 if(user_action == MetaEditPrompt.CANCEL || user_action == MetaEditPrompt.REMOVE_ALL) {
1176 action = user_action;
1177 }
1178 if(action == MetaEditPrompt.REMOVE_ALL || user_action == MetaEditPrompt.REMOVE) {
1179 fireMetadataChanged(id, record, data, null, MetaEditPrompt.REMOVE);
1180 undo.add(data);
1181 }
1182 // Store undo information
1183 undo_buffer.put(record, undo);
1184 }
1185 // If we've been cancelled higher up, undo action.
1186 if(action == MetaEditPrompt.CANCEL) {
1187 undoRemove(id, record);
1188 }
1189 return action;
1190 }
1191
1192 /** Rollback any changes made as part of a single metadata add process (only valid during the action itself, ie if a user presses cancel).
1193 * @param id the unique identify of all actions created as part of a single gesture, as a <i>long</i>.
1194 * @param record the FileNode whose metadata was changed.
1195 */
1196 private void undoAdd(long id, FileNode record) {
1197 // Retrieve the undo data from the buffer
1198 ArrayList undo = (ArrayList) undo_buffer.get(record);
1199 // If there is no undo then we can't do anything, but there should be
1200 if(undo != null && undo.size() > 0) {
1201 // The last piece of data in an add actions undo buffer is the metadata that was added
1202 Metadata data = (Metadata) undo.remove(undo.size() - 1);
1203 // Remove the data
1204 fireMetadataChanged(id, record, data, null, MetaEditPrompt.REMOVE);
1205 // If we removed other metadata when adding this metadata restore it too
1206 for(int i = 0; i < undo.size(); i++) {
1207 Metadata old_data = (Metadata) undo.get(i);
1208 fireMetadataChanged(id, record, null, old_data, MetaEditPrompt.ACCUMULATE);
1209 }
1210 }
1211 }
1212 /** Rollback any changes made as part of a single metadata remove process (only valid during the action itself, ie if a user presses cancel).
1213 * @param id the unique identify of all actions created as part of a single gesture, as a long.
1214 * @param record the FileNode metadata was removed from.
1215 */
1216 private void undoRemove(long id, FileNode record) {
1217 // Retrieve undo information
1218 ArrayList undo = (ArrayList) undo_buffer.get(record);
1219 // Ensure that we have something to undo
1220 if(undo != null && undo.size() == 1) {
1221 // The undo buffer should contain exactly one entry, the metadata removed
1222 Metadata data = (Metadata) undo.get(0);
1223 fireMetadataChanged(id, record, null, data, MetaEditPrompt.ACCUMULATE);
1224 }
1225 }
1226 /** 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).
1227 * @param id the unique identify of all actions created as part of a single gesture, as a long.
1228 * @param record the FileNode whose metadata was changed.
1229 */
1230 private void undoUpdate(long id, FileNode record) {
1231 // Retrieve undo information
1232 ArrayList undo = (ArrayList) undo_buffer.get(record);
1233 if(undo != null && undo.size() == 2) {
1234 Metadata old_data = (Metadata) undo.get(0);
1235 Metadata new_data = (Metadata) undo.get(1);
1236 fireMetadataChanged(id, record, new_data, null, MetaEditPrompt.REMOVE);
1237 if(old_data != new_data) { // Correct reference comparison
1238 fireMetadataChanged(id, record, null, old_data, MetaEditPrompt.ACCUMULATE);
1239 }
1240 }
1241 }
1242
1243 /** 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.
1244 * @param id the unique identify of all actions created as part of a single gesture, as a <i>long</i>.
1245 * @param record the FileNode whose metadata we are changing.
1246 * @param old_data The old existing <strong>Metadata</strong>.
1247 * @param new_data The new updated <strong>Metadata</strong>.
1248 * @param action An <i>int</i> indicating what we are going to do about it.
1249 * @param multiple_selection The number of records in the selection, as an <i>int</i>. Used to determine prompt controls.
1250 * @return An <i>int</i> specifying the current action. Thus changes in lower parts of the tree continue to effect other disjoint subtrees.
1251 */
1252 private int updateMetadata(long id, FileNode record, Metadata old_data, Metadata new_data, int action, boolean multiple_selection, boolean file_level) {
1253 ArrayList metadata;
1254 if(file_level) {
1255 metadata = Gatherer.c_man.getCollection().gdm.getMetadata(record.getFile());
1256 }
1257 else {
1258 metadata = Gatherer.c_man.getCollection().gdm.getAllMetadata(record.getFile());
1259 }
1260 int user_action = MetaEditPrompt.OVERWRITE;
1261 // Standard case of updating an existing metadata value.
1262 if(metadata.contains(old_data)) {
1263 ArrayList undo = new ArrayList();
1264 // If we are to prompt the user, do so.
1265 if(action == MetaEditPrompt.CONFIRM) {
1266 MetaEditPrompt mep = new MetaEditPrompt(MetaEditPrompt.UPDATE_PROMPT, multiple_selection, record.getFile(), old_data.getElement().toString(), old_data.getValue(), new_data.getValue());
1267 user_action = mep.display();
1268 }
1269 // Some user actions should have a continuous effect.
1270 if(user_action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.CANCEL) {
1271 action = user_action;
1272 }
1273 // And if the update chose update, do so.
1274 if(action == MetaEditPrompt.OVERWRITE_ALL || user_action == MetaEditPrompt.OVERWRITE || user_action == MetaEditPrompt.UPDATE_ONCE) {
1275 ///ystem.err.println("Updating:\n"+old_data+"\nto\n"+new_data);
1276 // If this is file level then we can do a normal replace
1277 if(file_level) {
1278 fireMetadataChanged(id, record, old_data, new_data, MetaEditPrompt.OVERWRITE);
1279 undo.add(old_data);
1280 undo.add(new_data);
1281 }
1282 // 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.
1283 else {
1284 fireMetadataChanged(id, record, null, new_data, MetaEditPrompt.OVERWRITE);
1285 undo.add(new_data);
1286 undo.add(new_data);
1287 }
1288 }
1289 // Store the undo information
1290 undo_buffer.put(record, undo);
1291 }
1292 // If we've been cancelled undo.
1293 if(action == MetaEditPrompt.CANCEL) {
1294 undoUpdate(id, record);
1295 }
1296 return action;
1297 }
1298
1299
1300 private void write(ElementWrapper element, GValueModel model, String etc_dir) {
1301 try {
1302 File out_file = new File(etc_dir + element.getName() + ".txt");
1303 FileOutputStream fos = new FileOutputStream(out_file);
1304 OutputStreamWriter osw = new OutputStreamWriter(fos);
1305 BufferedWriter bw = new BufferedWriter(osw, Utility.BUFFER_SIZE);
1306 Vector all_values = model.traverseTree();
1307 for(int i = 0; i < all_values.size(); i++) {
1308 GValueNode node = (GValueNode)all_values.get(i);
1309 TreePath path = new TreePath(node.getPath());
1310 String full_value = node.getFullPath(false);
1311 String index = model.getHIndex(full_value);
1312
1313 write(bw, "\"" + Utility.stripNL(full_value) + "\"\t" + index + "\t\"" + Utility.stripNL(node.toString(GValueNode.GREENSTONE)) + "\"");
1314 }
1315 // Very important we do this, or else buffer may not be flushed
1316 bw.flush();
1317 bw.close();
1318 }
1319 catch(Exception error) {
1320 error.printStackTrace();
1321 }
1322 }
1323
1324
1325 private void write(Writer w, String text)
1326 throws Exception {
1327 text = text + "\r\n";
1328 char buffer[] = text.toCharArray();
1329 w.write(buffer, 0, buffer.length);
1330 }
1331}
Note: See TracBrowser for help on using the repository browser.