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

Last change on this file since 13399 was 13399, checked in by mdewsnip, 17 years ago

Tidied up default metadata sets and added a "addRequiredMetadataSets" function so the extracted metadata set is always loaded when creating or loading a collection.

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