source: trunk/gli/src/org/greenstone/gatherer/collection/CollectionManager.java@ 14050

Last change on this file since 14050 was 14050, checked in by xiao, 17 years ago

Changes made to look for collectionConfig.xml in gs3 mode and collect.cfg in gs2 mode, rather than presumably only for the file collect.cfg; Calling convertToGS3Collection method is no longer needed; Add new implementation of method updateCollectionConfigXML when in gs3 mode to update collectionConfig.xml file.

  • Property svn:keywords set to Author Date Id Revision
File size: 67.2 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.collection;
38
39import java.io.*;
40import java.util.*;
41import javax.swing.*;
42import javax.swing.event.*;
43import javax.swing.filechooser.FileSystemView;
44import javax.swing.tree.*;
45import org.greenstone.gatherer.Configuration;
46import org.greenstone.gatherer.DebugStream;
47import org.greenstone.gatherer.Dictionary;
48import org.greenstone.gatherer.Gatherer;
49import org.greenstone.gatherer.cdm.CollectionDesignManager;
50import org.greenstone.gatherer.cdm.CollectionMeta;
51import org.greenstone.gatherer.cdm.CollectionMetaManager;
52import org.greenstone.gatherer.cdm.CommandTokenizer;
53import org.greenstone.gatherer.greenstone.Classifiers;
54import org.greenstone.gatherer.greenstone.LocalGreenstone;
55import org.greenstone.gatherer.greenstone.LocalLibraryServer;
56import org.greenstone.gatherer.greenstone.Plugins;
57import org.greenstone.gatherer.greenstone3.ServletConfiguration;
58import org.greenstone.gatherer.gui.LockFileDialog;
59import org.greenstone.gatherer.gui.ModalProgressPopup;
60import org.greenstone.gatherer.gui.WarningDialog;
61import org.greenstone.gatherer.metadata.DocXMLFileManager;
62import org.greenstone.gatherer.metadata.MetadataChangedListener;
63import org.greenstone.gatherer.metadata.MetadataSet;
64import org.greenstone.gatherer.metadata.MetadataSetManager;
65import org.greenstone.gatherer.metadata.MetadataXMLFileManager;
66import org.greenstone.gatherer.metadata.ProfileXMLFileManager;
67import org.greenstone.gatherer.remote.RemoteGreenstoneServer;
68import org.greenstone.gatherer.shell.GShell;
69import org.greenstone.gatherer.shell.GShellEvent;
70import org.greenstone.gatherer.shell.GShellListener;
71import org.greenstone.gatherer.shell.GShellProgressMonitor;
72import org.greenstone.gatherer.util.Codec;
73import org.greenstone.gatherer.util.StaticStrings;
74import org.greenstone.gatherer.util.Utility;
75import org.greenstone.gatherer.util.XMLTools;
76import org.w3c.dom.*;
77
78/** This class manages many aspects of the collection, from its creation via scripts, data access via methods and its importing and building into the final collection. It is also resposible for firing appropriate event when significant changes have occured within the collection, and for creating a new metadata set manager as necessary.
79 * @author John Thompson
80 * @version 2.3
81 */
82public class CollectionManager
83 implements GShellListener, MetadataChangedListener
84{
85 /** Are we currently in the process of building? */
86 static private boolean building = false;
87 /** Are we currently in the process of importing? */
88 static private boolean importing = false;
89 /** The objects listening for CollectionContentsChanged events. */
90 static private ArrayList collection_contents_changed_listeners = new ArrayList();
91 /** The collection this manager is managing! */
92 static private Collection collection = null;
93 /** The collection tree (used in both Gather and Enrich panes). */
94 static private CollectionTree collection_tree = null;
95 /** The collection tree model. */
96 static private CollectionTreeModel collection_tree_model = null;
97 /** An inner class listener responsible for noting tree changes and resetting saved when they occur. */
98 static private FMTreeModelListener fm_tree_model_listener = null;
99 /** The monitor resposible for parsing the build process. */
100 static private GShellProgressMonitor build_monitor = null;
101 /** The monitor resposible for parsing the import process. */
102 static private GShellProgressMonitor import_monitor = null;
103
104 /** The name of the standard lock file. */
105 static final public String LOCK_FILE = "gli.lck";
106
107 /** Used to indicate the source of the message is the file collection methods. */
108 static final public int COLLECT = 3;
109 /** Used to indicate the source of the message is the building methods. */
110 static final public int BUILDING = 5;
111
112
113 /** Constructor. */
114 public CollectionManager() {
115 // Initialisation.
116 this.building = false;
117 this.importing = false;
118 this.collection = null;
119
120 MetadataXMLFileManager.addMetadataChangedListener(this);
121
122 // If using a remote Greenstone server, delete the local collect directory because it will be out of date
123 if (Gatherer.isGsdlRemote) {
124 System.err.println("Deleting user's local collect directory...");
125 Utility.delete(new File(Gatherer.getCollectDirectoryPath()));
126 System.err.println("Done.");
127 new File(Gatherer.getCollectDirectoryPath()).mkdirs();
128 }
129 }
130
131
132 static public void addCollectionContentsChangedListener(CollectionContentsChangedListener listener)
133 {
134 collection_contents_changed_listeners.add(listener);
135 }
136
137
138 /** This method calls the builcol.pl scripts via a GShell so as to not lock up the processor.
139 * @see org.greenstone.gatherer.Configuration
140 * @see org.greenstone.gatherer.Gatherer
141 * @see org.greenstone.gatherer.collection.Collection
142 * @see org.greenstone.gatherer.gui.BuildOptions
143 * @see org.greenstone.gatherer.shell.GShell
144 * @see org.greenstone.gatherer.shell.GShellListener
145 * @see org.greenstone.gatherer.shell.GShellProgressMonitor
146 * @see org.greenstone.gatherer.util.Utility
147 */
148 public void buildCollection(boolean incremental_build)
149 {
150
151 DebugStream.println("In CollectionManager.buildCollection(), incremental_build: " + incremental_build);
152 DebugStream.println("Is event dispatch thread: " + SwingUtilities.isEventDispatchThread());
153 building = true;
154
155 // Generate the buildcol.pl command
156 ArrayList command_parts_list = new ArrayList();
157 if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) {
158 command_parts_list.add(Configuration.perl_path);
159 command_parts_list.add("-S");
160 }
161 command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "buildcol.pl");
162 command_parts_list.add("-gli");
163 command_parts_list.add("-language");
164 command_parts_list.add(Configuration.getLanguage());
165 command_parts_list.add("-collectdir");
166 command_parts_list.add(getCollectDirectory());
167
168 // If the user hasn't manually specified "-keepold" or "-removeold" then pick one based on incremental_build
169 if (!collection.build_options.getValueEnabled("keepold") && !collection.build_options.getValueEnabled("removeold")) {
170 command_parts_list.add(incremental_build ? "-keepold" : "-removeold");
171 }
172
173 String[] build_options = collection.build_options.getValues();
174 for (int i = 0; i < build_options.length; i++) {
175 command_parts_list.add(build_options[i]);
176 }
177
178 command_parts_list.add(collection.getName());
179
180 // Run the buildcol.pl command
181 String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
182 GShell shell = new GShell(command_parts, GShell.BUILD, BUILDING, this, build_monitor, GShell.GSHELL_BUILD);
183 shell.addGShellListener(Gatherer.g_man.create_pane);
184 shell.addGShellListener(Gatherer.g_man.format_pane);
185 shell.start();
186
187 }
188
189
190 /** Used to determine whether the currently active collection has been built.
191 * @return A boolean indicating the built status of the collection.
192 */
193 public boolean built() {
194 if(collection != null) {
195 // Determine if the collection has been built by looking for the build.cfg or buildConfig.xml file
196 String file_name = (Gatherer.GS3)? Utility.BUILD_CONFIG_XML : Utility.BUILD_CFG;
197 File build_cfg_file = new File(getLoadedCollectionIndexDirectoryPath() + file_name);
198 return build_cfg_file.exists();
199 }
200 return false;
201 }
202
203
204 /** a test method to see if we can delete a directory/file - returns false is the file or any of the contents of a directory cannot be deleted */
205 static private boolean canDelete(File file)
206 {
207 if (!file.isDirectory()) {
208 return file.canWrite();
209 }
210 File [] file_list = file.listFiles();
211 for (int i=0; i<file_list.length; i++) {
212 if (!canDelete(file_list[i])) {
213 return false;
214 }
215 }
216 return true;
217 }
218
219
220 /** Called to close the current collection and remove its lock file.
221 * @see org.greenstone.gatherer.Gatherer
222 * @see org.greenstone.gatherer.collection.Collection
223 * @see org.greenstone.gatherer.util.Utility
224 */
225 public void closeCollection() {
226 DebugStream.println("Close collection: " + collection.getName());
227
228 // Remove the lock on this file, then remove the collection.
229 File lock_file = new File(getLoadedCollectionDirectoryPath() + LOCK_FILE);
230 lock_file.delete();
231 if (lock_file.exists()) {
232 System.err.println("Warning: Lockfile was not successfully deleted.");
233 }
234
235 // Remove the lock file on the server
236 if (Gatherer.isGsdlRemote) {
237 RemoteGreenstoneServer.deleteCollectionFile(collection.getName(), lock_file);
238 }
239
240 MetadataSetManager.clearMetadataSets();
241 MetadataXMLFileManager.clearMetadataXMLFiles();
242 DocXMLFileManager.clearDocXMLFiles();
243 ProfileXMLFileManager.clearProfileXMLFile();
244
245 collection.destroy();
246 collection = null;
247 collection_tree_model = null;
248 //Configuration.setCollectionConfiguration(null);
249 Gatherer.refresh(Gatherer.COLLECTION_CLOSED);
250 if (Gatherer.g_man != null) {
251 Gatherer.g_man.updateUI(); // !!! Necessary?
252 }
253 }
254
255//This method is no longer used in gs3 since the modification of CollectionConfiguration.java
256// public void convertToGS3Collection() {
257// // Generate the convert_coll_from_gs2.pl command
258// ArrayList command_parts_list = new ArrayList();
259// if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) {
260// command_parts_list.add(Configuration.perl_path);
261// command_parts_list.add("-S");
262// }
263// command_parts_list.add(Configuration.getGS3ScriptPath() + "convert_coll_from_gs2.pl");
264// command_parts_list.add("-collectdir");
265// command_parts_list.add(getCollectDirectory());
266// command_parts_list.add(collection.getName());
267//
268// // Run the convert_coll_from_gs2.pl command
269// String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
270// GShell process = new GShell(command_parts, GShell.CONVERT, COLLECT, this, null, GShell.GSHELL_CONVERT);
271// process.addGShellListener(this);
272// process.run(); // Don't bother threading this... yet
273//
274// }
275
276 /** When basing a new collection on an existing one, we need to copy
277 * over some extra directories: images and macros
278 */
279 private boolean copyExtraBaseCollStuff(File new_coll_dir, File base_coll_dir) {
280 if (!new_coll_dir.isDirectory() || !base_coll_dir.isDirectory()) {
281 return false;
282 }
283 DebugStream.println("Copying images and macros dirs from the base collection");
284 try {
285 // do the images dir
286 File base_coll_images = new File(base_coll_dir, "images");
287 if (base_coll_images.isDirectory()) {
288 // copy all the images over
289 File new_coll_images = new File(new_coll_dir, "images");
290 new_coll_images.mkdirs();
291
292 // copy the contents over
293 Gatherer.f_man.getQueue().copyDirectoryContents(base_coll_images, new_coll_images);
294 }
295 }
296 catch (Exception e) {
297 DebugStream.println("Couldn't copy over the images dir from the base collection: "+e.toString());
298 }
299 try {
300 // do the macros dir
301 File base_coll_macros = new File(base_coll_dir, "macros");
302 if (base_coll_macros.isDirectory()) {
303 // copy all the macros over
304 File new_coll_macros = new File(new_coll_dir, "macros");
305 new_coll_macros.mkdirs();
306
307 // copy the contents over
308 Gatherer.f_man.getQueue().copyDirectoryContents(base_coll_macros, new_coll_macros);
309 }
310 }
311 catch (Exception e) {
312 DebugStream.println("Couldn't copy over the macros dir from the base collection: "+e.toString());
313 }
314 return true;
315 }
316
317 /** Used to set the current collection to the given collection. Note that this call should -always- be proceeded by a ready call, and if the collection is ready and the saved flag is unset then the user should be prompted to save. Also note that this method creates yet another GShell to run buildcol.pl.
318 * @param description a description of the collection as a String
319 * @param email the email address of the author/maintainer as a String
320 * @param name the short name of the collection, which will subsequently be used to refer to this particular collection, as a String
321 * @param title the longer title of the collection as a String
322 * @param base_collection_directory if the user has chosen to base their new collection on an existing one, this is the directory where this base collection can be found, as a File, otherwise its null
323 * @param metadata_sets if the user has decided to select several metadata sets with which to initially populate the GLI then this is an ArrayList of metadata set file names, otherwise its null
324 */
325 public void createCollection(String description, String email, String name, String title, File base_collection_directory, ArrayList metadata_sets)
326 {
327 // Display a modal progress popup to indicate that the collection is being loaded
328 ModalProgressPopup create_collection_progress_popup = new ModalProgressPopup(Dictionary.get("CollectionManager.Creating_Collection"), Dictionary.get("CollectionManager.Creating_Collection_Please_Wait"));
329 create_collection_progress_popup.display();
330
331 // Create the collection on a separate thread so the progress bar updates correctly
332 (new CreateCollectionTask(description, email, name, title, base_collection_directory, metadata_sets, create_collection_progress_popup)).start();
333 }
334
335
336 private class CreateCollectionTask
337 extends Thread
338 {
339 private String description = null;
340 private String email = null;
341 private String name = null;
342 private String title = null;
343 private File base_collection_directory = null;
344 private ArrayList metadata_sets = null;
345 private ModalProgressPopup create_collection_progress_popup = null;
346
347 public CreateCollectionTask(String description, String email, String name, String title, File base_collection_directory, ArrayList metadata_sets, ModalProgressPopup create_collection_progress_popup)
348 {
349 this.description = description;
350 this.email = email;
351 this.name = name;
352 this.title = title;
353 this.base_collection_directory = base_collection_directory;
354 this.metadata_sets = metadata_sets;
355 this.create_collection_progress_popup = create_collection_progress_popup;
356 }
357
358 public void run()
359 {
360 createCollectionInternal(description, email, name, title, base_collection_directory, metadata_sets);
361 create_collection_progress_popup.close();
362 }
363 }
364
365
366 private void createCollectionInternal(String description, String email, String name, String title, File base_collection_directory, ArrayList metadata_sets)
367 {
368 try {
369 // first make sure that the collect directory exists
370 File collect_dir = new File(getCollectDirectory());
371 if (!collect_dir.exists()) {
372 collect_dir.mkdirs();
373 }
374
375 // Create the new collection
376 makeCollection(name, email);
377
378 // Check that the collection has been created successfully
379 String collection_directory_path = getCollectionDirectoryPath(name);
380 if (!new File(collection_directory_path).exists()) {
381 // If there is no collection directory then the creation was unsuccessful, or cancelled
382
383 return;
384 }
385
386 // Check for the existence of the collection configuration file
387 String file_name = ((Gatherer.GS3 == true)? Utility.COLLECTION_CONFIG_XML : Utility.COLLECT_CFG);
388 File collect_cfg_file = new File(collection_directory_path + "etc" + File.separator + file_name);
389
390 if (!collect_cfg_file.exists()) {
391 System.err.println("Error: no " + file_name + " file has been created!");
392 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Create_Collection_With_Reason", Dictionary.get("CollectionManager.No_Config_File")), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
393 return;
394 }
395
396 // ACTIVE_DIR/log/
397 File log_dir = new File(collection_directory_path + "log");
398 log_dir.mkdirs();
399
400 // Make sure an import folder exists
401 File collection_import_directory = new File(collection_directory_path + "import");
402 if (!collection_import_directory.exists()) {
403 collection_import_directory.mkdirs();
404 if (Gatherer.isGsdlRemote) {
405 RemoteGreenstoneServer.newCollectionDirectory(name, collection_import_directory);
406 }
407 }
408
409 // Now create the collection object around the directory.
410 collection = new Collection(new File(collection_directory_path, name + ".col"));
411
412 // "-removeold" is on by default for import.pl
413 collection.import_options.setValue("removeold", true, null);
414
415 MetadataSetManager.clearMetadataSets();
416 MetadataXMLFileManager.clearMetadataXMLFiles();
417 DocXMLFileManager.clearDocXMLFiles();
418
419 // Import default metadata sets, if any
420 // for (int i = 0; metadata_sets != null && i < metadata_sets.size(); i++) {
421 // importMetadataSet((MetadataSet) metadata_sets.get(i));
422 // }
423
424 ProfileXMLFileManager.loadProfileXMLFile(new File(collection_directory_path + "metadata"));
425
426 // Before creating the CollectionDesignManager check if we are basing it upon some other collection
427 if (base_collection_directory != null) {
428 DebugStream.println("Basing new collection on existing one: " + base_collection_directory);
429
430 // If we're using a remote Greenstone server, download the collection shell to get the files needed
431 if (Gatherer.isGsdlRemote) {
432 String base_collection_name = base_collection_directory.getName();
433 RemoteGreenstoneServer.downloadCollection(base_collection_name);
434 }
435
436 collection.setBaseCollection(base_collection_directory.getAbsolutePath());
437 // copy over other needed directories
438 copyExtraBaseCollStuff(new File(collection_directory_path), base_collection_directory);
439
440 // Try to import any existing metadata sets for this collection
441 // Look in base_collection_directory/metadata and import any metadata sets found.
442 File base_metadata_directory = new File(base_collection_directory, "metadata");
443 ArrayList base_metadata_sets = MetadataSetManager.listMetadataSets(base_metadata_directory);
444 if (base_metadata_sets != null) {
445 for (int i = 0; i < base_metadata_sets.size(); i++) {
446 importMetadataSet((MetadataSet) base_metadata_sets.get(i));
447 }
448 }
449 else {
450 DebugStream.println("This base collection has no metadata directory.");
451 }
452
453 // Now we update our collect.cfg
454 DebugStream.println("Copy and update " + file_name + " from base collection.");
455
456 if (Gatherer.GS3 == true) {
457 updateCollectionConfigXML(new File(base_collection_directory, Utility.CONFIG_GS3_FILE),
458 new File(collection_directory_path, Utility.CONFIG_GS3_FILE));
459 } else {
460 updateCollectionCFG(new File(base_collection_directory, Utility.CONFIG_FILE),
461 new File(collection_directory_path, Utility.CONFIG_FILE),
462 description, email, title);
463 }
464 }
465
466 // Load the default metadata sets
467 addDefaultMetadataSets();
468
469 // Make sure we always have the extracted metadata set
470 addRequiredMetadataSets();
471
472 collection.cdm = new CollectionDesignManager(new File(getLoadedCollectionCfgFilePath()));
473
474 // We always set title and description here rather than calling mkcol.pl with Unicode arguments
475 CollectionMeta collection_name_collectionmeta = collection.cdm.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_COLLECTIONNAME_STR);
476 collection_name_collectionmeta.setValue(title);
477 CollectionMeta collection_extra_collectionmeta = collection.cdm.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_COLLECTIONEXTRA_STR);
478 collection_extra_collectionmeta.setValue(description);
479
480 // Now that we have a CDM, update several settings, such as if we created this collection by basing it on another, set it as public automatically. This update is done to the internal xml structure which may be saved into collect.cfg or collectionConfig.xml accordingly.
481 if (base_collection_directory != null) {
482 // Update the creator and maintainer
483 CollectionMeta creator_collectionmeta = new CollectionMeta(collection.cdm.collect_config.getCreator());
484 creator_collectionmeta.setValue(email);
485 creator_collectionmeta = null;
486 CollectionMeta maintainer_collectionmeta = new CollectionMeta(collection.cdm.collect_config.getMaintainer());
487 maintainer_collectionmeta.setValue(email);
488 maintainer_collectionmeta = null;
489
490 // All collections based on others are automatically public
491 CollectionMeta public_collectionmeta = new CollectionMeta(collection.cdm.collect_config.getPublic());
492 public_collectionmeta.setValue(StaticStrings.TRUE_STR);
493 public_collectionmeta = null;
494
495 // Finally reset the icons
496 CollectionMeta icon_collection_collectionmeta = collection.cdm.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_ICONCOLLECTION_STR);
497 icon_collection_collectionmeta.setValue(StaticStrings.EMPTY_STR);
498 icon_collection_collectionmeta = null;
499 CollectionMeta icon_collection_small_collectionmeta = collection.cdm.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_ICONCOLLECTIONSMALL_STR);
500 icon_collection_small_collectionmeta.setValue(StaticStrings.EMPTY_STR);
501 icon_collection_small_collectionmeta = null;
502 }
503
504 saveCollection();
505
506 // Create a lock file
507 createLockFile(new File(collection_directory_path, LOCK_FILE));
508
509 // We're done. Let everyone know.
510 Gatherer.refresh(Gatherer.COLLECTION_OPENED);
511 }
512 catch (Exception error) {
513 DebugStream.printStackTrace(error);
514 }
515 }
516
517
518 private void createLockFile(File lock_file)
519 {
520 try {
521 Document default_lockfile = XMLTools.parseXMLFile("xml/" + LOCK_FILE, true);
522 String user_name = System.getProperty("user.name");
523 Element person_element = (Element) XMLTools.getNodeFromNamed(default_lockfile.getDocumentElement(), "User");
524 person_element.appendChild(default_lockfile.createTextNode(user_name));
525 person_element = null;
526 user_name = null;
527 String machine_name = Utility.getMachineName();
528 Element machine_element = (Element) XMLTools.getNodeFromNamed(default_lockfile.getDocumentElement(), "Machine");
529 machine_element.appendChild(default_lockfile.createTextNode(machine_name));
530 machine_element = null;
531 machine_name = null;
532 String date_time = Utility.getDateString();
533 Element date_element = (Element) XMLTools.getNodeFromNamed(default_lockfile.getDocumentElement(), "Date");
534 date_element.appendChild(default_lockfile.createTextNode(date_time));
535 date_element = null;
536 date_time = null;
537 XMLTools.writeXMLFile(lock_file, default_lockfile);
538 }
539 catch (Exception exception) {
540 DebugStream.printStackTrace(exception);
541 }
542 }
543
544
545 public boolean deleteCollection(String collection_name)
546 {
547 // First we must release the collection from the local library, if it's running
548 if (LocalLibraryServer.isRunning() == true) {
549 LocalLibraryServer.releaseCollection(collection_name);
550 }
551
552 // Delete the collection on the server if we're using a remote Greenstone
553 if (Gatherer.isGsdlRemote) {
554 RemoteGreenstoneServer.deleteCollection(collection_name);
555 }
556
557 // Now delete the collection directory
558 return Utility.delete(new File(getCollectionDirectoryPath(collection_name)));
559 }
560
561
562 public void fireFileAddedToCollection(File file)
563 {
564 // Send the event off to all the CollectionContentsChangedListeners
565 for (int i = 0; i < collection_contents_changed_listeners.size(); i++) {
566 ((CollectionContentsChangedListener) collection_contents_changed_listeners.get(i)).fileAddedToCollection(file);
567 }
568 }
569
570
571 /** Retrieve the current collection.
572 * @return The <strong>Collection</strong> itself.
573 */
574 public Collection getCollection() {
575 return collection;
576 }
577
578
579 /** Returns the absolute filename of the specified collection's directory.
580 */
581 static public String getCollectionDirectoryPath(String collection_name)
582 {
583 return Gatherer.getCollectDirectoryPath() + collection_name + File.separator;
584 }
585
586
587 /** Returns the absolute filename of the loaded collection's archives directory.
588 */
589 static public String getLoadedCollectionArchivesDirectoryPath()
590 {
591 return getLoadedCollectionDirectoryPath() + "archives" + File.separator;
592 }
593
594
595 /** Returns the absolute filename of the loaded collection's building directory.
596 */
597 static public String getLoadedCollectionBuildingDirectoryPath()
598 {
599 return getLoadedCollectionDirectoryPath() + "building" + File.separator;
600 }
601
602
603 /** Returns the absolute filename of the loaded collection's collect.cfg file.
604 */
605 static public String getLoadedCollectionCfgFilePath()
606 {
607 String path = (Gatherer.GS3 == true)? Utility.COLLECTION_CONFIG_XML : Utility.COLLECT_CFG;
608 return getLoadedCollectionEtcDirectoryPath() + path;
609 }
610
611
612 /** Returns the absolute filename of the loaded collection's directory.
613 */
614 static public String getLoadedCollectionDirectoryPath()
615 {
616 return Gatherer.getCollectDirectoryPath() + collection.getName() + File.separator;
617 }
618
619
620 /** Returns the absolute filename of the loaded collection's etc directory.
621 */
622 static public String getLoadedCollectionEtcDirectoryPath()
623 {
624 return getLoadedCollectionDirectoryPath() + "etc" + File.separator;
625 }
626
627
628 /** Returns the absolute filename of the loaded collection's .col file.
629 */
630 static public String getLoadedCollectionColFilePath()
631 {
632 return getLoadedCollectionDirectoryPath() + collection.getName() + ".col";
633 }
634
635
636 /** Returns the absolute filename of the loaded collection's images directory.
637 */
638 static public String getLoadedCollectionImagesDirectoryPath()
639 {
640 return getLoadedCollectionDirectoryPath() + "images" + File.separator;
641 }
642
643
644 /** Returns the absolute filename of the loaded collection's import directory.
645 */
646 static public String getLoadedCollectionImportDirectoryPath()
647 {
648 return getLoadedCollectionDirectoryPath() + "import" + File.separator;
649 }
650
651
652 /** Returns the absolute filename of the loaded collection's index directory.
653 */
654 static public String getLoadedCollectionIndexDirectoryPath()
655 {
656 return getLoadedCollectionDirectoryPath() + "index" + File.separator;
657 }
658
659
660 /** Returns the absolute filename of the loaded collection's log directory.
661 */
662 static public String getLoadedCollectionLogDirectoryPath()
663 {
664 return getLoadedCollectionDirectoryPath() + "log" + File.separator;
665 }
666
667
668 /** Returns the absolute filename of the loaded collection's macros directory.
669 */
670 static public String getLoadedCollectionMacrosDirectoryPath()
671 {
672 return getLoadedCollectionDirectoryPath() + "macros" + File.separator;
673 }
674
675
676 /** Returns the absolute filename of the loaded collection's metadata directory.
677 */
678 static public String getLoadedCollectionMetadataDirectoryPath()
679 {
680 return getLoadedCollectionDirectoryPath() + "metadata" + File.separator;
681 }
682
683
684 /** Returns the name of the loaded collection.
685 */
686 static public String getLoadedCollectionName()
687 {
688 if (collection != null) {
689 return collection.getName();
690 }
691
692 return null;
693 }
694
695
696 public CollectionTree getCollectionTree()
697 {
698 if (collection_tree == null) {
699 collection_tree = new CollectionTree(collection_tree_model, true);
700 }
701
702 return collection_tree;
703 }
704
705
706 /** Retrieve the tree model associated with the current collection. */
707 public CollectionTreeModel getCollectionTreeModel()
708 {
709 if (collection_tree_model == null && collection != null) {
710 // Use the import directory to generate a new CollectionTreeModel
711 collection_tree_model = new CollectionTreeModel(new CollectionTreeNode(new File(getLoadedCollectionImportDirectoryPath())));
712 // Ensure that the manager is a change listener for the tree.
713 if (fm_tree_model_listener == null) {
714 fm_tree_model_listener = new FMTreeModelListener();
715 }
716 collection_tree_model.addTreeModelListener(fm_tree_model_listener);
717 }
718 return collection_tree_model;
719 }
720
721
722 /** This method when called, creates a new GShell in order to run the import.pl script.
723 * @see org.greenstone.gatherer.Configuration
724 * @see org.greenstone.gatherer.Gatherer
725 * @see org.greenstone.gatherer.gui.BuildOptions
726 * @see org.greenstone.gatherer.shell.GShell
727 * @see org.greenstone.gatherer.shell.GShellListener
728 * @see org.greenstone.gatherer.shell.GShellProgressMonitor
729 * @see org.greenstone.gatherer.util.Utility
730 */
731 public void importCollection() {
732 importing = true;
733
734 if (!saved()) {
735 DebugStream.println("CollectionManager.importCollection().forcesave");
736 import_monitor.saving();
737 saveCollection();
738 }
739
740 DebugStream.println("CollectionManager.importCollection()");
741 DebugStream.println("Is event dispatch thread: " + SwingUtilities.isEventDispatchThread());
742 //check that we can remove the old index before starting import
743 File index_dir = new File(getLoadedCollectionIndexDirectoryPath());
744 if (index_dir.exists()) {
745 DebugStream.println("Old Index = " + index_dir.getAbsolutePath()+", testing for deletability");
746 if (!canDelete(index_dir)) {
747 // tell the user
748 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Delete_Index"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
749 // tell the gui manager
750 // a message for the building log
751 GShellEvent event = new GShellEvent(this, 0, GShell.IMPORT, Dictionary.get("CollectionManager.Cannot_Delete_Index_Log"), GShell.ERROR);
752 Gatherer.g_man.create_pane.message(event);
753 event = new GShellEvent(this, 0, GShell.IMPORT, "", GShell.ERROR);
754 Gatherer.g_man.create_pane.processComplete(event);
755 importing = false;
756 return;
757 }
758 }
759
760 // Generate the import.pl command
761 ArrayList command_parts_list = new ArrayList();
762 if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) {
763 command_parts_list.add(Configuration.perl_path);
764 command_parts_list.add("-S");
765 }
766 command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "import.pl");
767 command_parts_list.add("-gli");
768 command_parts_list.add("-language");
769 command_parts_list.add(Configuration.getLanguage());
770 command_parts_list.add("-collectdir");
771 command_parts_list.add(getCollectDirectory());
772
773 String[] import_options = collection.import_options.getValues();
774 for (int i = 0; i < import_options.length; i++) {
775 command_parts_list.add(import_options[i]);
776 }
777
778 command_parts_list.add(collection.getName());
779
780 // Run the import.pl command
781 String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
782 GShell shell = new GShell(command_parts, GShell.IMPORT, BUILDING, this, import_monitor, GShell.GSHELL_IMPORT);
783 shell.addGShellListener(Gatherer.g_man.create_pane);
784 shell.addGShellListener(Gatherer.g_man.format_pane);
785 shell.start();
786 DebugStream.println("CollectionManager.importCollection().return");
787
788 importing = false;
789 }
790
791
792 public void importMetadataSet(MetadataSet external_metadata_set)
793 {
794 // Copy the .mds file into the collection's "metadata" folder...
795 File external_metadata_set_file = external_metadata_set.getMetadataSetFile();
796
797 // ...but not if it is the redundant "hidden.mds" file
798 if (external_metadata_set_file.getName().equals("hidden.mds")) {
799 return;
800 }
801
802 // ...and only if it doesn't already exist
803 File metadata_set_file = new File(getLoadedCollectionMetadataDirectoryPath(), external_metadata_set_file.getName());
804 if (!metadata_set_file.exists()) {
805 try {
806 Gatherer.f_man.getQueue().copyFile(external_metadata_set_file, metadata_set_file, false);
807
808 // If we're using a remote Greenstone server, upload the metadata file
809 if (Gatherer.isGsdlRemote) {
810 RemoteGreenstoneServer.uploadCollectionFile(collection.getName(), metadata_set_file);
811 }
812 }
813 catch (Exception exception) {
814 DebugStream.printStackTrace(exception);
815 }
816
817 // Load it into the MetadataSetManager
818 MetadataSetManager.loadMetadataSet(metadata_set_file);
819 }
820 }
821
822
823 /** Determine if we are currently in the middle of importing (and thus, in this case, we can't allow the log writer to exit). Boy was this a mission to track down. The cascade of crap rolls out something like this: Joe Schmo clicks 'Build Collection', which calls the importCollection() method above, which in turn saves the collection with a saveTask, which fires a collectionChanged message once its finished, which drives the list of logs shown on the create pane to update, which fires a itemChanged() event to the OptionsPane who dutifully tells the current log writer thread to finish up writing (all zero lines its been asked to write) and then die. Wereapon Joe Schmo gets a pretty log to look at, but it isn't actually being written to file so the next time he tries to view it faeces hits the air motion cooling device. Joy.
824 * @return true if the gli is currently importing
825 */
826 public boolean isImporting() {
827 return importing;
828 }
829
830
831 public void loadCollection(String collection_file_path)
832 {
833 // Display a modal progress popup to indicate that the collection is being loaded
834 ModalProgressPopup load_collection_progress_popup = new ModalProgressPopup(Dictionary.get("CollectionManager.Loading_Collection"), Dictionary.get("CollectionManager.Loading_Collection_Please_Wait"));
835 load_collection_progress_popup.display();
836
837 // Load the collection on a separate thread so the progress bar updates correctly
838 (new LoadCollectionTask(collection_file_path, load_collection_progress_popup)).start();
839 }
840
841
842 private class LoadCollectionTask
843 extends Thread
844 {
845 private String collection_file_path = null;
846 private ModalProgressPopup load_collection_progress_popup = null;
847
848 public LoadCollectionTask(String collection_file_path, ModalProgressPopup load_collection_progress_popup)
849 {
850 this.collection_file_path = collection_file_path;
851 this.load_collection_progress_popup = load_collection_progress_popup;
852 }
853
854 public void run()
855 {
856 loadCollectionInternal(collection_file_path);
857 load_collection_progress_popup.close();
858 }
859 }
860
861
862 /** Attempts to load the given collection. Currently uses simple serialization of the collection class.
863 * @param location The path to the collection as a <strong>String</strong>.
864 * @see org.greenstone.gatherer.Configuration
865 * @see org.greenstone.gatherer.Gatherer
866 * @see org.greenstone.gatherer.collection.Collection
867 * @see org.greenstone.gatherer.util.Utility
868 */
869 private void loadCollectionInternal(String location)
870 {
871 DebugStream.println("Loading collection " + location + "...");
872
873 if (Gatherer.isGsdlRemote) {
874 String collection_name = location.substring(location.lastIndexOf(File.separator) + 1, location.length() - ".col".length());
875 if (RemoteGreenstoneServer.downloadCollection(collection_name).equals("")) {
876 return;
877 }
878 }
879
880 // Check we have actually been given a .col file.
881 if (!location.endsWith(".col")) {
882 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Not_Col_File", location), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
883 DebugStream.println("CollectionManager.loadCollection: Haven't been given a .col file.");
884 return;
885 }
886
887 // Check that the collection configuration file is available
888 File collection_file = new File(location);
889
890 // Ensure that the directory exists
891 File collection_directory = collection_file.getParentFile();
892
893 if (collection_directory == null || !collection_directory.exists()) {
894 // We can't open this
895 System.err.println("CollectionManager.loadCollection: No collection directory.");
896 return;
897 }
898
899 String file_str = (Gatherer.GS3)? Utility.CONFIG_GS3_FILE : Utility.CONFIG_FILE;
900 File collection_config_file = new File(collection_directory, file_str);
901 if (!collection_config_file.exists()) {
902 System.err.println("CollectionManager.loadCollection: No config file.");
903 collection_directory = null;
904 collection_config_file = null;
905 return;
906 }
907
908 // Ensure that an import directory exists for this collection
909 File collection_import_directory = new File(collection_directory, "import");
910 if (!collection_import_directory.exists()) {
911 collection_import_directory.mkdir();
912 }
913
914 // Special case of a user trying to open an old greenstone collection.
915 boolean non_gli_collection = false;
916 File collection_metadata_directory = new File(collection_directory, "metadata");
917 if (!collection_metadata_directory.exists()) {
918 DebugStream.println("Loading non-gatherer collection...");
919 // Show a warning message in case user wants to quit now
920 non_gli_collection = true;
921 WarningDialog legacy_dialog = new WarningDialog("warning.LegacyCollection", Dictionary.get("LegacyCollection.Title"), Dictionary.get("LegacyCollection.Message"), null, true);
922 if (legacy_dialog.display()==JOptionPane.CANCEL_OPTION) {
923 legacy_dialog.dispose();
924 collection_directory = null;
925 collection_config_file = null;
926 return;
927 }
928 legacy_dialog.dispose();
929
930 }
931
932 // Now determine if a lock already exists on this collection.
933 String collection_name = collection_directory.getName();
934 File lock_file = new File(collection_file.getParentFile(), LOCK_FILE);
935 if (lock_file.exists()) {
936 LockFileDialog dialog = new LockFileDialog(Gatherer.g_man, collection_name, lock_file);
937 int choice = dialog.getChoice();
938 dialog.dispose();
939 dialog = null;
940
941 if (choice != LockFileDialog.YES_OPTION) {
942 // user has cancelled
943 lock_file = null;
944 collection_directory = null;
945 collection_config_file = null;
946 return;
947 }
948
949 lock_file.delete();
950 }
951
952 try {
953 // Create a lock file.
954 createLockFile(lock_file);
955 // This lock file may not have been created so check
956 if(!lock_file.canWrite()) {
957 // The lock file cannot be written to. Most likely cause incorrect file permissions.
958 System.err.println("Cannot write lock file!");
959 String args[] = new String[2];
960 args[0] = location;
961 args[1] = Dictionary.get("FileActions.Write_Not_Permitted_Title");
962 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open_With_Reason", args), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
963 args = null;
964 return;
965 }
966
967 // Open the collection file
968 this.collection = new Collection(collection_file);
969 if (collection.error) {
970 collection = null;
971 // Remove lock file
972 if (lock_file.exists()) {
973 lock_file.delete();
974 }
975 throw(new Exception(Dictionary.get("CollectionManager.Missing_Config"))); // this error message does not agree with the error
976 }
977
978 MetadataSetManager.clearMetadataSets();
979 MetadataSetManager.loadMetadataSets(collection_metadata_directory);
980
981 // Make sure we always have the extracted metadata set
982 addRequiredMetadataSets();
983
984 ProfileXMLFileManager.loadProfileXMLFile(collection_metadata_directory);
985
986 // If this is a non-GLI (legacy) collection, load the default metadata sets
987 if (non_gli_collection) {
988 addDefaultMetadataSets();
989
990 // Recurse the import folder tree, backing up the metadata.xml files before they are edited
991 LegacyCollectionImporter.backupMetadataXMLFiles(collection_directory);
992 }
993
994 // Read through the metadata.xml files in the import directory, building up the metadata value trees
995 MetadataXMLFileManager.clearMetadataXMLFiles();
996 MetadataXMLFileManager.loadMetadataXMLFiles(collection_import_directory,collection.toSkimFile());
997
998 // Read through the doc.xml files in the archives directory
999 File collection_archives_directory = new File(getLoadedCollectionArchivesDirectoryPath());
1000 DocXMLFileManager.clearDocXMLFiles();
1001 DocXMLFileManager.loadDocXMLFiles(collection_archives_directory);
1002
1003 // Get a list of the collection specific classifiers and plugins
1004 Classifiers.loadClassifiersList(collection_name);
1005 Plugins.loadPluginsList(collection_name);
1006
1007 collection.cdm = new CollectionDesignManager(collection_config_file);
1008 if (non_gli_collection) {
1009 // Change the classifiers to use the namespaced element names
1010 LegacyCollectionImporter.updateClassifiers(collection.cdm);
1011 }
1012
1013 // We're done. Let everyone know.
1014 DebugStream.println(Dictionary.get("CollectionManager.Loading_Successful", collection_name));
1015 Gatherer.refresh(Gatherer.COLLECTION_OPENED);
1016 }
1017 catch (Exception error) {
1018 // There is obviously no existing collection present.
1019 DebugStream.printStackTrace(error);
1020 if(error.getMessage() != null) {
1021 String[] args = new String[2];
1022 args[0] = location;
1023 args[1] = error.getMessage();
1024 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open_With_Reason", args), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1025 }
1026 else {
1027 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open", location), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1028 }
1029 }
1030
1031 lock_file = null;
1032 collection_directory = null;
1033 collection_config_file = null;
1034 }
1035
1036
1037 private void makeCollection(String name, String email)
1038 {
1039 // Generate the mkcol.pl command
1040 ArrayList command_parts_list = new ArrayList();
1041 if (Utility.isWindows() && (!Gatherer.isGsdlRemote)) {
1042 command_parts_list.add(Configuration.perl_path);
1043 command_parts_list.add("-S");
1044 }
1045 command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "mkcol.pl");
1046
1047 command_parts_list.add((Gatherer.GS3) ? Utility.GS3MODE_ARGUMENT : "");// add '-gs3mode'
1048
1049 command_parts_list.add("-collectdir");
1050 command_parts_list.add(getCollectDirectory());
1051
1052
1053 command_parts_list.add("-win31compat");
1054 command_parts_list.add((Gatherer.isGsdlRemote) ? "false" : "true");
1055
1056 if (email != null && !email.equals("")) {
1057 command_parts_list.add("-creator");
1058 command_parts_list.add(email);
1059 }
1060
1061 command_parts_list.add(name);
1062
1063 // Run the mkcol.pl command
1064 String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
1065
1066 GShell process = new GShell(command_parts, GShell.NEW, COLLECT, this, null, GShell.GSHELL_NEW);
1067 process.run(); // Don't bother threading this... yet
1068 }
1069
1070
1071 /** Any implementation of GShellListener must include this method to allow the GShell to send messages to listeners. However in this case the CollectionManager is in no way interested in what the messages are, just the import events which have a specific type and are handled elsewhere. Thus we can safely ignore this event.
1072 * @param event A <strong>GShellEvent</strong> which contains a the message.
1073 */
1074 public synchronized void message(GShellEvent event) {
1075 }
1076
1077
1078 public void metadataChanged(CollectionTreeNode[] file_nodes)
1079 {
1080 if (collection != null) {
1081 collection.setMetadataChanged(true);
1082 }
1083 }
1084
1085
1086 public void openCollectionFromLastTime()
1087 {
1088 // If there was an open collection last session, reopen it
1089 if (Gatherer.open_collection_file_path != null) {
1090 // Load the collection now
1091 loadCollection(Gatherer.open_collection_file_path);
1092 }
1093 }
1094
1095
1096 /** This call is fired whenever a process within a GShell created by this class begins.
1097 * @param event A <strong>GShellEvent</strong> containing information about the GShell process.
1098 * @see org.greenstone.gatherer.Gatherer
1099 * @see org.greenstone.gatherer.gui.GUIManager
1100 * @see org.greenstone.gatherer.shell.GShell
1101 */
1102 public synchronized void processBegun(GShellEvent event) {
1103 DebugStream.println("CollectionManager.processBegun(" + event.getType() + ")");
1104 ///ystem.err.println("ProcessBegun " + event.getType());
1105 // If this is one of the types where we wish to lock user control
1106 Gatherer.g_man.lockCollection((event.getType() == GShell.IMPORT), true);
1107 }
1108 /** This call is fired whenever a process within a GShell created by this class ends.
1109 * @param event A <strong>GShellEvent</strong> containing information about the GShell process.
1110 * @see org.greenstone.gatherer.Gatherer
1111 * @see org.greenstone.gatherer.gui.GUIManager
1112 * @see org.greenstone.gatherer.shell.GShell
1113 */
1114 public synchronized void processComplete(GShellEvent event) {
1115 //ystem.err.println("CollectionManager.processComplete(" + event.getType() + ")");
1116 Gatherer.g_man.lockCollection((event.getType() == GShell.IMPORT), false);
1117 ///ystem.err.println("Recieved process complete event - " + event);
1118 // If we were running an import, now run a build.
1119 if(event.getType() == GShell.IMPORT && event.getStatus() == GShell.OK) {
1120 // Finish import.
1121 collection.setImported(true);
1122 collection.setFilesChanged(false);
1123 collection.setMetadataChanged(false);
1124 buildCollection(false);
1125 }
1126 // If we were running a build, now is when we move files across.
1127 else if(event.getType() == GShell.BUILD && event.getStatus() == GShell.OK) {
1128
1129 if(installCollection()) {
1130 // If we have a local library running then ask it to add our newly create collection
1131 if (LocalLibraryServer.isRunning() == true) {
1132 LocalLibraryServer.addCollection(collection.getName());
1133 }
1134 else if (Gatherer.GS3) {
1135 //xiao comment out this: convertToGS3Collection();
1136 Gatherer.configGS3Server(Configuration.site_name, ServletConfiguration.ADD_COMMAND + collection.getName());
1137 }
1138
1139 // Fire a collection changed first to update the preview etc buttons
1140 Gatherer.refresh(Gatherer.COLLECTION_REBUILT);
1141
1142 // Now display a message dialog saying its all built
1143 WarningDialog collection_built_warning_dialog = new WarningDialog("warning.CollectionBuilt", Dictionary.get("CollectionBuilt.Title"), Dictionary.get("CollectionBuilt.Message"), null, false);
1144 collection_built_warning_dialog.setMessageOnly(true); // Not a warning
1145 collection_built_warning_dialog.display();
1146 collection_built_warning_dialog.dispose();
1147 collection_built_warning_dialog = null;
1148
1149 //Set nothing as needing rebuilding, as a build has just finished :-)
1150 CollectionDesignManager.resetRebuildTypeRequired();
1151 }
1152 else {
1153 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Preview_Ready_Failed"), Dictionary.get("CollectionManager.Preview_Ready_Title"), JOptionPane.ERROR_MESSAGE);
1154 Gatherer.refresh(Gatherer.COLLECTION_REBUILT);
1155 DebugStream.println("Status is ok but !installCollection()");
1156 }
1157 }
1158 else if (event.getStatus() == GShell.CANCELLED) {
1159 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Build_Cancelled"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1160 Gatherer.g_man.repaint();
1161 }
1162 else if (event.getStatus() == GShell.ERROR) {
1163 DebugStream.println("There was an error in the gshell:"+ event.getMessage());
1164 if (event.getType() == GShell.NEW) {
1165 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Create_Collection"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1166 } else {
1167 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Preview_Ready_Failed"), Dictionary.get("CollectionManager.Preview_Ready_Title"), JOptionPane.ERROR_MESSAGE);
1168 Gatherer.refresh(Gatherer.COLLECTION_REBUILT);
1169 }
1170
1171 Gatherer.g_man.repaint(); // It appears Java's own dialogs have the same not always painting correct area bug that I suffer from. Well I don't suffer from it personally, but my ModalDialog components do.
1172 }
1173 }
1174
1175
1176 /** Determine if the manager is ready for actions apon its collection.
1177 * @return A <i>boolean</i> which is <i>true</i> to indicate a collection has been loaded and thus the collection is ready for editing, <i>false</i> otherwise.
1178 */
1179 static public synchronized boolean ready() {
1180 if(collection != null) {
1181 return true;
1182 }
1183 else {
1184 return false;
1185 }
1186 }
1187
1188
1189 /** This method associates the collection build monitor with the build monitor created in CreatePane.
1190 * @param monitor A <strong>GShellProgressMonitor</strong> which we will use as the build monitor.
1191 */
1192 public void registerBuildMonitor(GShellProgressMonitor monitor) {
1193 build_monitor = monitor;
1194 }
1195 /** This method associates the collection import monitor with the import monitor created in CreatePane.
1196 * @param monitor A <strong>GShellProgressMonitor</strong> which we will use as the import monitor.
1197 */
1198 public void registerImportMonitor(GShellProgressMonitor monitor) {
1199 import_monitor = monitor;
1200 }
1201
1202
1203 static public void removeCollectionContentsChangedListener(CollectionContentsChangedListener listener)
1204 {
1205 collection_contents_changed_listeners.remove(listener);
1206 }
1207
1208
1209 public void removeMetadataSet(MetadataSet metadata_set)
1210 {
1211 DebugStream.println("Removing metadata set...");
1212
1213 // Delete the .mds file from the collection's "metadata" folder...
1214 File metadata_set_file = metadata_set.getMetadataSetFile();
1215
1216 // ...but not if it is the "ex.mds" file
1217 if (metadata_set_file.getName().equals("ex.mds")) {
1218 return;
1219 }
1220
1221 // ...and only if it exists
1222 if (metadata_set_file.exists()) {
1223 metadata_set_file.delete();
1224
1225 // Unload it from the MetadataSetManager
1226 MetadataSetManager.unloadMetadataSet(metadata_set);
1227
1228 // If we're using a remote Greenstone server, delete the metadata file on the server
1229 if (Gatherer.isGsdlRemote) {
1230 RemoteGreenstoneServer.deleteCollectionFile(collection.getName(), metadata_set_file);
1231 }
1232 }
1233 }
1234
1235
1236 /** Used to check whether all open collections have a 'saved' state.
1237 * @return A <i>boolean</i> which is <i>true</i> if the collection has been saved.
1238 * @see org.greenstone.gatherer.collection.Collection
1239 */
1240 public boolean saved() {
1241 boolean result = true;
1242 if(collection != null) {
1243 result = collection.getSaved();
1244 }
1245 return result;
1246 }
1247
1248
1249 /** Saves the currently loaded collection. */
1250 public void saveCollection()
1251 {
1252
1253 if (collection == null) return;
1254
1255 DebugStream.println("Saving collection " + collection.getName() + "...");
1256
1257 // Change cursor to hourglass
1258 Gatherer.g_man.wait(true);
1259
1260 // Create a backup of the collection file, just in case anything goes wrong
1261 File collection_file = new File(getLoadedCollectionColFilePath());
1262 if (collection_file.exists()) {
1263 File collection_file_backup = new File(collection_file.getAbsolutePath() + "~");
1264 if (!collection_file.renameTo(collection_file_backup)) {
1265 DebugStream.println("Error in CollectionManager.saveCollection(): could not create backup file.");
1266 }
1267 collection_file_backup.deleteOnExit();
1268 }
1269
1270 // Write out the collection file
1271 collection.save();
1272
1273 // Write out the collection configuration file
1274 collection.cdm.save();
1275
1276 // Change cursor back to normal
1277 Gatherer.g_man.wait(false);
1278 }
1279
1280
1281 /** I started giving the user the choice of using an existing meta set or creating a new one. The second option being so that they didn't have to add/merge/ignore each element, they could all be added automatically. However, I am not sure where the merge prompt gets called from, and it is not essential, so I am leaving it for now - it should be added back in and finished. [kjdon] */
1282 private void addDefaultMetadataSets()
1283 {
1284 // Add dublin core which is the default metadata set. The user
1285 // can change this later
1286 File dc_file = new File(Gatherer.getGLIMetadataDirectoryPath()+"dublin.mds");
1287 if (dc_file.exists()) {
1288 importMetadataSet(new MetadataSet(dc_file));
1289 }
1290 }
1291
1292
1293 private void addRequiredMetadataSets()
1294 {
1295 // Always import the extracted metadata set
1296 File extracted_metadata_set_file = new File(Gatherer.getGLIMetadataDirectoryPath() + MetadataSetManager.EXTRACTED_METADATA_NAMESPACE + StaticStrings.METADATA_SET_EXTENSION);
1297 importMetadataSet(new MetadataSet(extracted_metadata_set_file));
1298 }
1299
1300
1301 // used as arg in the perl scripts
1302 private String getCollectDirectory() {
1303 String collect_dir = Gatherer.getCollectDirectoryPath();
1304
1305 // Remove erroneous file windows file separator as it causes problems when running import.pl
1306 if(collect_dir.length() > 2 && collect_dir.endsWith("\\")) {
1307 collect_dir = collect_dir.substring(0, collect_dir.length() - 1);
1308 }
1309
1310 return collect_dir;
1311 }
1312
1313
1314 /** Install collection by moving its files from building to index after a successful build.
1315 * @see org.greenstone.gatherer.Gatherer
1316 * @see org.greenstone.gatherer.util.Utility
1317 */
1318 private boolean installCollection()
1319 {
1320 DebugStream.println("Build complete. Moving files.");
1321
1322 try {
1323 // Ensure that the local library has released this collection so we can delete the index directory
1324 if (LocalLibraryServer.isRunning() == true) {
1325 LocalLibraryServer.releaseCollection(collection.getName());
1326 }
1327 // deactivate it in tomcat so that windows will release the index files
1328 if (Gatherer.GS3) {
1329 Gatherer.configGS3Server(Configuration.site_name, ServletConfiguration.DEACTIVATE_COMMAND + collection.getName());
1330 }
1331 File index_dir = new File(getLoadedCollectionIndexDirectoryPath());
1332 DebugStream.println("Index = " + index_dir.getAbsolutePath());
1333
1334 File building_dir = new File(getLoadedCollectionBuildingDirectoryPath());
1335 DebugStream.println("Building = " + building_dir.getAbsolutePath());
1336
1337 // Get the build mode from the build options
1338 String build_mode = collection.build_options.getValue("mode");
1339
1340 // Special case for build mode "all": replace index dir with building dir
1341 if (build_mode == null || build_mode.equals(Dictionary.get("CreatePane.Mode_All"))) {
1342 // Remove the old index directory
1343 if (index_dir.exists()) {
1344 Utility.delete(index_dir);
1345
1346 // Wait for a couple of seconds, just for luck
1347 wait(2000);
1348
1349 // Check the delete worked
1350 if (index_dir.exists()) {
1351 throw new Exception(Dictionary.get("CollectionManager.Index_Not_Deleted"));
1352 }
1353 }
1354
1355 if (Gatherer.isGsdlRemote) {
1356 RemoteGreenstoneServer.deleteCollectionFile(collection.getName(), new File(getLoadedCollectionIndexDirectoryPath()));
1357 RemoteGreenstoneServer.moveCollectionFile(collection.getName(), new File(getLoadedCollectionBuildingDirectoryPath()), new File(getLoadedCollectionIndexDirectoryPath()));
1358 }
1359
1360 // Move the building directory to become the new index directory
1361 if (building_dir.renameTo(index_dir) == false) {
1362 throw new Exception(Dictionary.get("CollectionManager.Build_Not_Moved"));
1363 }
1364 }
1365
1366 // Otherwise copy everything in the building dir into the index dir
1367 else {
1368 moveContentsInto(building_dir, index_dir);
1369 }
1370 }
1371 catch (Exception exception) {
1372 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Install_Exception", exception.getMessage()), "Error", JOptionPane.ERROR_MESSAGE);
1373 return false;
1374 }
1375 return true;
1376 }
1377
1378
1379 /** Moves all the files in one directory into another, overwriting existing files */
1380 private void moveContentsInto(File source_directory, File target_directory)
1381 {
1382 File[] source_files = source_directory.listFiles();
1383 for (int i = 0; i < source_files.length; i++) {
1384 File source_file = source_files[i];
1385 File target_file = new File(target_directory, source_file.getName());
1386
1387 if (source_file.isDirectory()) {
1388 moveContentsInto(source_file, target_file);
1389 source_file.delete();
1390 }
1391 else {
1392 if (target_file.exists()) {
1393 target_file.delete();
1394 }
1395
1396 source_file.renameTo(target_file);
1397 }
1398 }
1399 }
1400
1401 private void updateCollectionConfigXML(File base_cfg, File new_cfg) {
1402 //In this method, the files base_cfg and new_cfg are all xml files.
1403
1404 Document base_cfg_doc = XMLTools.parseXMLFile(base_cfg);
1405 XMLTools.writeXMLFile(new_cfg, base_cfg_doc);
1406 Document new_cfg_doc = XMLTools.parseXMLFile(new_cfg);
1407 Element collection_config = new_cfg_doc.getDocumentElement();
1408
1409 Node browseNode = XMLTools.getChildByTagNameIndexed(collection_config, StaticStrings.BROWSE_STR, 0);
1410 NodeList classifier_children = ((Element)browseNode).getElementsByTagName(StaticStrings.CLASSIFIER_STR);
1411 int num_nodes = classifier_children.getLength();
1412
1413 if (num_nodes < 1) {
1414 return;
1415 }
1416
1417 // Read in the classifier command watching for hfile, metadata and sort arguments.
1418 String buttonname = null;
1419 String hfile = null;
1420 String metadata = null;
1421 String sort = null;
1422
1423 for (int i=0; i<num_nodes; i++) {
1424 Element classifier_element = (Element)classifier_children.item(i);
1425 NodeList option_children = classifier_element.getElementsByTagName(StaticStrings.OPTION_STR);
1426 for (int j=0; j<option_children.getLength(); j++) {
1427 Element option_element = (Element)option_children.item(j);
1428 String name_str = option_element.getAttribute(StaticStrings.NAME_ATTRIBUTE);
1429 String value_str = option_element.getAttribute(StaticStrings.VALUE_ATTRIBUTE);
1430
1431 if (name_str == null || name_str.equals("")) {
1432 continue;
1433 }
1434 if (name_str != null && value_str == null ) {
1435 value_str = "";
1436 }
1437 if (name_str.equals("hfile")) {
1438 hfile = value_str;
1439 }
1440 else if (name_str.equals("metadata") && value_str != null) {
1441 String replacement = ProfileXMLFileManager.getMetadataElementFor(value_str);
1442 if (replacement != null && !replacement.equals("")) {
1443 metadata = replacement;
1444 }
1445 }
1446 else if (name_str.equals("sort") && value_str != null) {
1447 String replacement = ProfileXMLFileManager.getMetadataElementFor(value_str);
1448 if (replacement != null && !replacement.equals("")) {
1449 sort = replacement;
1450 }
1451 }
1452 else if(name_str.equals("buttonname") && value_str != null) {
1453 buttonname = value_str;
1454 }
1455 }
1456 }
1457 for (int i=0; i<num_nodes; i++) {
1458 Element classifier_element = (Element)classifier_children.item(i);
1459 NodeList option_children = classifier_element.getElementsByTagName(StaticStrings.OPTION_STR);
1460 for (int j=0; j<option_children.getLength(); j++) {
1461 Element option_element = (Element)option_children.item(j);
1462 String name_str = option_element.getAttribute(StaticStrings.NAME_ATTRIBUTE);
1463
1464 if (name_str.equals("metadata") && metadata != null) {
1465 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, metadata);
1466 }
1467 else if (name_str.equals("hfile") && hfile != null) {
1468 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, metadata + ".txt");
1469 }
1470 else if (name_str.equals("sort") && sort != null) {
1471 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, sort);
1472 }
1473 else if(name_str.equals("buttonname") && buttonname == "") {
1474 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, metadata);
1475 }
1476 else if(buttonname == null) {
1477 // No buttonname has been specified. Lets create one using the metadata as its value
1478 Element option = new_cfg_doc.createElement(StaticStrings.OPTION_STR);
1479 option.setAttribute(StaticStrings.NAME_ATTRIBUTE, "buttonname");
1480 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, metadata);
1481 classifier_element.appendChild(option);
1482 }
1483 }
1484 }
1485
1486 }
1487
1488 private void updateCollectionCFG(File base_cfg, File new_cfg, String description, String email, String title)
1489 {
1490 boolean first_name = true;
1491 boolean first_extra = true;
1492
1493 // Now read in base_cfg line by line, parsing important onces and/or replacing them with information pertinent to our collection. Each line is then written back out to the new collect.cfg file.
1494 try {
1495 BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(base_cfg), "UTF-8"));
1496 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new_cfg), "UTF-8"));
1497 String command = null;
1498 while((command = in.readLine()) != null) {
1499 if (command.length()==0) {
1500 // output a new line
1501 out.newLine();
1502 continue;
1503 }
1504 // We have to test the end of command for the special character '\'. If found, remove it and append the next line, then repeat.
1505 while(command.trim().endsWith("\\")) {
1506 command = command.substring(0, command.lastIndexOf("\\"));
1507 String next_line = in.readLine();
1508 if(next_line != null) {
1509 command = command + next_line;
1510 }
1511 }
1512 // commands can extend over more than one line so use the CommandTokenizer which takes care of that
1513 CommandTokenizer tokenizer = new CommandTokenizer(command, in, false);
1514 String command_type_str = tokenizer.nextToken().toLowerCase();
1515
1516 if (command_type_str.equals(StaticStrings.COLLECTIONMETADATA_STR)) {
1517 // read the whole thing in, but for collectionname, collectionextra, iconcollection, iconcollectionsmall we will ignore them
1518 StringBuffer new_command = new StringBuffer(command_type_str);
1519 String meta_name = tokenizer.nextToken();
1520 new_command.append(' ');
1521 new_command.append(meta_name);
1522 while (tokenizer.hasMoreTokens()) {
1523 new_command.append(' ');
1524 new_command.append(tokenizer.nextToken());
1525 }
1526 if (meta_name.equals(StaticStrings.COLLECTIONMETADATA_COLLECTIONNAME_STR) || meta_name.equals(StaticStrings.COLLECTIONMETADATA_COLLECTIONEXTRA_STR) || meta_name.equals(StaticStrings.COLLECTIONMETADATA_ICONCOLLECTION_STR) || meta_name.equals(StaticStrings.COLLECTIONMETADATA_ICONCOLLECTIONSMALL_STR)) {
1527 // dont save
1528 } else {
1529 write(out, new_command.toString());
1530 }
1531 new_command = null;
1532 continue;
1533 } // if collectionmeta
1534
1535 if (command_type_str.equals("classify")) {
1536 StringBuffer text = new StringBuffer(command_type_str);
1537 // Read in the classifier command watching for hfile, metadata and sort arguments.
1538 String buttonname = null;
1539 String hfile = null;
1540 String new_metadata = null;
1541 String old_metadata = null;
1542
1543 while(tokenizer.hasMoreTokens()) {
1544 String token = tokenizer.nextToken();
1545 if (token.equals("-hfile")) {
1546 if(tokenizer.hasMoreTokens()) {
1547 text.append(" ");
1548 text.append(token);
1549 token = tokenizer.nextToken();
1550 hfile = token;
1551 }
1552 }
1553 else if (token.equals("-metadata")) {
1554 if(tokenizer.hasMoreTokens()) {
1555 text.append(" ");
1556 text.append(token);
1557 String temp_metadata = tokenizer.nextToken();
1558 String replacement = ProfileXMLFileManager.getMetadataElementFor(temp_metadata);
1559 if (replacement != null && !replacement.equals("")) {
1560 token = replacement;
1561 old_metadata = temp_metadata;
1562 new_metadata = replacement;
1563 }
1564 else {
1565 token = temp_metadata;
1566 }
1567 temp_metadata = null;
1568 replacement = null;
1569 }
1570 }
1571 else if (token.equals("-sort")) {
1572 if(tokenizer.hasMoreTokens()) {
1573 text.append(" ");
1574 text.append(token);
1575 String temp_metadata = tokenizer.nextToken();
1576 String replacement = ProfileXMLFileManager.getMetadataElementFor(temp_metadata);
1577 if (replacement != null && !replacement.equals("")) {
1578 token = replacement;
1579 }
1580 else {
1581 token = temp_metadata;
1582 }
1583 temp_metadata = null;
1584 replacement = null;
1585 }
1586 }
1587 else if(token.equals("-buttonname")) {
1588 buttonname = token;
1589 }
1590 text.append(' ');
1591 text.append(token);
1592 token = null;
1593 }
1594
1595 // If we replaced the metadata argument and didn't encounter a buttonname, then add one now pointing back to the old metadata name in order to accomodate macro files which required such names (buttonname is metadata name by default)!
1596 if(old_metadata != null && new_metadata != null && buttonname == null) {
1597 text.append(' ');
1598 text.append("-buttonname");
1599 text.append(' ');
1600 text.append(old_metadata);
1601 }
1602 command = text.toString();
1603 // Replace the hfile if we found it
1604 if(hfile != null && new_metadata != null) {
1605 command = command.replaceAll(hfile, new_metadata + ".txt");
1606 }
1607
1608 buttonname = null;
1609 hfile = null;
1610 new_metadata = null;
1611 old_metadata = null;
1612 write(out, command);
1613 } else {
1614 // the rest of the commands just want a string - we read in all the tokens from the tokeniser and get rid of it.
1615 StringBuffer new_command = new StringBuffer(command_type_str);
1616 while (tokenizer.hasMoreTokens()) {
1617 new_command.append(' ');
1618 new_command.append(tokenizer.nextToken());
1619 }
1620
1621 command = new_command.toString();
1622
1623 // There is still one special case, that of the format command. In such a command we have to search for [<target>] to ensure we don't change parts of the format which have nothing to do with the metadata elements.
1624 // we really want to build up the whole command here
1625 boolean format_command = command_type_str.equals("format");
1626 HashMap metadata_mapping = ProfileXMLFileManager.getMetadataMapping();
1627 if (metadata_mapping != null) {
1628 Iterator keys = metadata_mapping.keySet().iterator();
1629 while (keys.hasNext()) {
1630 String target = (String) keys.next();
1631 String replacement = (String) metadata_mapping.get(target);
1632 if (replacement != null && !replacement.equals("")) {
1633 if (format_command) {
1634 target = "\\[" + target + "\\]";
1635 replacement = "{Or}{[" + replacement + "]," + target + "}";
1636 }
1637 command = command.replaceAll(target, replacement);
1638 }
1639 }
1640 }
1641
1642 write(out, command);
1643 }
1644 tokenizer = null;
1645 }
1646 in.close();
1647 in = null;
1648 out.flush();
1649 out.close();
1650 out = null;
1651 }
1652 catch(Exception error) {
1653 DebugStream.printStackTrace(error);
1654 }
1655 // All done, I hope.
1656 }
1657
1658 private void write(BufferedWriter out, String message)
1659 throws Exception {
1660 out.write(message, 0, message.length());
1661 out.newLine();
1662 }
1663
1664
1665 /** The CollectionManager class is getting too confusing by half so I'll implement this TreeModelListener in a private class to make responsibility clear. */
1666 private class FMTreeModelListener
1667 implements TreeModelListener {
1668 /** Any action that changes one of the tree models within a collection, which are the only models we listen to, mean the collections contents have changed and so saved should be set to false.
1669 * @param event A <strong>TreeModelEvent</strong> encompassing all the information about the event which has changed the tree.
1670 */
1671 public void treeNodesChanged(TreeModelEvent event) {
1672 if(collection != null) {
1673 collection.setSaved(false);
1674 collection.setFilesChanged(true);
1675 }
1676 }
1677 /** Any action that changes one of the tree models within a collection, which are the only models we listen to, mean the collections contents have changed and so saved should be set to false.
1678 * @param event A <strong>TreeModelEvent</strong> encompassing all the information about the event which has changed the tree.
1679 */
1680 public void treeNodesInserted(TreeModelEvent event) {
1681 if(collection != null) {
1682 collection.setSaved(false);
1683 collection.setFilesChanged(true);
1684 }
1685 }
1686 /** Any action that changes one of the tree models within a collection, which are the only models we listen to, mean the collections contents have changed and so saved should be set to false.
1687 * @param event A <strong>TreeModelEvent</strong> encompassing all the information about the event which has changed the tree.
1688 */
1689 public void treeNodesRemoved(TreeModelEvent event) {
1690 if(collection != null) {
1691 collection.setSaved(false);
1692 collection.setFilesChanged(true);
1693
1694 }
1695 }
1696 /** Any action that changes one of the tree models within a collection, which are the only models we listen to, mean the collections contents have changed and so saved should be set to false.
1697 * @param event A <strong>TreeModelEvent</strong> encompassing all the information about the event which has changed the tree.
1698 */
1699 public void treeStructureChanged(TreeModelEvent event) {
1700 if(collection != null) {
1701 collection.setSaved(false);
1702 }
1703 }
1704 }
1705}
Note: See TracBrowser for help on using the repository browser.