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

Last change on this file since 22772 was 22772, checked in by ak19, 14 years ago

Corrected error in previous accidental commit: To tell the local library server to release a collection, need to pass a URL style slash

  • Property svn:keywords set to Author Date Id Revision
File size: 87.5 KB
Line 
1/**
2 *#########################################################################
3 *
4 * A component of the Gatherer application, part of the Greenstone digital
5 * library suite from the New Zealand Digital Library Project at the
6 * University of Waikato, New Zealand.
7 *
8 * <BR><BR>
9 *
10 * Author: John Thompson, Greenstone Digital Library, University of Waikato
11 *
12 * <BR><BR>
13 *
14 * Copyright (C) 1999 New Zealand Digital Library Project
15 *
16 * <BR><BR>
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
22 *
23 * <BR><BR>
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * <BR><BR>
31 *
32 * You should have received a copy of the GNU General Public License
33 * along with this program; if not, write to the Free Software
34 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
35 *########################################################################
36 */
37package org.greenstone.gatherer.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.cdm.BuildTypeManager;
54import org.greenstone.gatherer.cdm.CollectionConfiguration;
55import org.greenstone.gatherer.greenstone.Classifiers;
56import org.greenstone.gatherer.greenstone.LocalGreenstone;
57import org.greenstone.gatherer.greenstone.LocalLibraryServer;
58import org.greenstone.gatherer.greenstone.Plugins;
59import org.greenstone.gatherer.greenstone3.ServletConfiguration;
60import org.greenstone.gatherer.gui.LockFileDialog;
61import org.greenstone.gatherer.gui.ModalProgressPopup;
62import org.greenstone.gatherer.gui.WarningDialog;
63import org.greenstone.gatherer.metadata.DocXMLFileManager;
64import org.greenstone.gatherer.metadata.MetadataChangedListener;
65import org.greenstone.gatherer.metadata.MetadataSet;
66import org.greenstone.gatherer.metadata.MetadataSetManager;
67import org.greenstone.gatherer.metadata.MetadataXMLFileManager;
68import org.greenstone.gatherer.metadata.ProfileXMLFileManager;
69import org.greenstone.gatherer.remote.RemoteGreenstoneServer;
70import org.greenstone.gatherer.shell.GShell;
71import org.greenstone.gatherer.shell.GShellEvent;
72import org.greenstone.gatherer.shell.GShellListener;
73import org.greenstone.gatherer.shell.GShellProgressMonitor;
74import org.greenstone.gatherer.util.Codec;
75import org.greenstone.gatherer.util.StaticStrings;
76import org.greenstone.gatherer.util.Utility;
77import org.greenstone.gatherer.util.XMLTools;
78import org.w3c.dom.*;
79
80/** 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 responsible for firing appropriate event when significant changes have occured within the collection, and for creating a new metadata set manager as necessary.
81 * @author John Thompson
82 * @version 2.3
83 */
84public class CollectionManager
85 implements GShellListener, MetadataChangedListener
86{
87 /** Are we currently in the process of building? */
88 static private boolean building = false;
89 /** Are we currently in the process of importing? */
90 static private boolean importing = false;
91 /** Are we currently in the process of scheduling? */
92 static private boolean scheduling = false;
93 /** The objects listening for CollectionContentsChanged events. */
94 static private ArrayList collection_contents_changed_listeners = new ArrayList();
95 /** The collection this manager is managing! */
96 static private Collection collection = null;
97 /** The collection tree (used in both Gather and Enrich panes). */
98 static private CollectionTree collection_tree = null;
99 /** The collection tree model. */
100 static private CollectionTreeModel collection_tree_model = null;
101 /** An inner class listener responsible for noting tree changes and resetting saved when they occur. */
102 static private FMTreeModelListener fm_tree_model_listener = null;
103 /** The monitor responsible for parsing the build process. */
104 static private GShellProgressMonitor build_monitor = null;
105 /** The monitor responsible for parsing the import process. */
106 static private GShellProgressMonitor import_monitor = null;
107 /** The monitor responsible for parsing the scheduler process. */
108 static private GShellProgressMonitor schedule_monitor = null;
109
110 /** The name of the standard lock file. */
111 static final public String LOCK_FILE = "gli.lck";
112
113 /** Used to indicate the source of the message is the file collection methods. */
114 static final public int COLLECT = 3;
115 /** Used to indicate the source of the message is the building methods. */
116 static final public int BUILDING = 5;
117 /** Used to indicate the source of the message is in the scheduling methods...? */
118 static final public int SCHEDULING = 7;
119
120 /** To store the path to the perl scripts. In the case of local Greenstone servers,
121 * this will be the local bin/script folder. */
122 static private String scriptPath = "";
123
124 /** Constructor. */
125 public CollectionManager() {
126 // Initialisation.
127 this.building = false;
128 this.importing = false;
129 this.scheduling = false;
130 this.collection = null;
131
132 MetadataXMLFileManager.addMetadataChangedListener(this);
133
134 // If using a remote Greenstone server, delete the local collect directory because it will be out of date
135 if (Gatherer.isGsdlRemote) {
136 System.err.println("Deleting user's local collect directory...");
137 Utility.delete(new File(Gatherer.getCollectDirectoryPath()));
138 System.err.println("Done.");
139 new File(Gatherer.getCollectDirectoryPath()).mkdirs();
140
141 scriptPath = ""; // remote greenstone: scriptPath will be determined on remote server side
142 }
143 else { // local greenstone case: scripts are inside bin/script
144 scriptPath = LocalGreenstone.getBinScriptDirectoryPath();
145 }
146 }
147
148
149 static public void addCollectionContentsChangedListener(CollectionContentsChangedListener listener)
150 {
151 collection_contents_changed_listeners.add(listener);
152 }
153
154
155 /** This method calls the builcol.pl scripts via a GShell so as to not lock up the processor.
156 * @see org.greenstone.gatherer.Configuration
157 * @see org.greenstone.gatherer.Gatherer
158 * @see org.greenstone.gatherer.collection.Collection
159 * @see org.greenstone.gatherer.gui.BuildOptions
160 * @see org.greenstone.gatherer.shell.GShell
161 * @see org.greenstone.gatherer.shell.GShellListener
162 * @see org.greenstone.gatherer.shell.GShellProgressMonitor
163 * @see org.greenstone.gatherer.util.Utility
164 */
165 public void buildCollection()
166 {
167
168 DebugStream.println("In CollectionManager.buildCollection(), CollectionDesignManager.isCompleteBuild(): " + CollectionDesignManager.isCompleteBuild());
169 DebugStream.println("Is event dispatch thread: " + SwingUtilities.isEventDispatchThread());
170 building = true;
171
172 // Generate the buildcol.pl command
173 ArrayList command_parts_list = new ArrayList();
174 if (!Gatherer.isGsdlRemote) {
175 command_parts_list.add(Configuration.perl_path);
176 command_parts_list.add("-S");
177 }
178
179 if (Configuration.fedora_info.isActive()) {
180 command_parts_list.add(scriptPath + "g2f-buildcol.pl");
181
182 command_parts_list.add("-hostname");
183 command_parts_list.add(Configuration.fedora_info.getHostname());
184
185 command_parts_list.add("-port");
186 command_parts_list.add(Configuration.fedora_info.getPort());
187
188 command_parts_list.add("-username");
189 command_parts_list.add(Configuration.fedora_info.getUsername());
190
191 command_parts_list.add("-password");
192 command_parts_list.add(Configuration.fedora_info.getPassword());
193
194 command_parts_list.add("-protocol");
195 command_parts_list.add(Configuration.fedora_info.getProtocol());
196
197 }
198 else {
199
200 if ( !CollectionDesignManager.isCompleteBuild() && CollectionDesignManager.index_manager.isLucene() ) {
201 command_parts_list.add(scriptPath + "incremental-buildcol.pl");
202 CollectionDesignManager.setBuildcolWasFull(false);
203 } else {
204 command_parts_list.add(scriptPath + "full-buildcol.pl");
205 CollectionDesignManager.setBuildcolWasFull(true);
206 }
207 }
208
209 command_parts_list.add("-gli");
210 command_parts_list.add("-language");
211 command_parts_list.add(Configuration.getLanguage());
212 if(!Gatherer.isGsdlRemote) {
213 command_parts_list.add("-collectdir");
214 command_parts_list.add(getCollectDirectory()); // <../collect/>
215 }
216
217 String[] build_options = collection.build_options.getValues();
218 for (int i = 0; i < build_options.length; i++) {
219 command_parts_list.add(build_options[i]);
220 }
221
222 command_parts_list.add(collection.getGroupQualifiedName(false)); // (colgroup/)colname
223
224 // Run the buildcol.pl and
225 String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
226 GShell shell = new GShell(command_parts, GShell.BUILD, BUILDING, this, build_monitor, GShell.GSHELL_BUILD);
227 shell.addGShellListener(Gatherer.g_man.create_pane);
228 shell.addGShellListener(Gatherer.g_man.format_pane);
229 shell.start();
230
231 }
232
233 /*probably repeating alot of work, but I want to keep this separate... wendy*/
234 public void scheduleBuild()
235 {
236 DebugStream.println("In CollectionManager.scheduleBuild(), CollectionDesignManager.isCompleteBuild(): " + CollectionDesignManager.isCompleteBuild());
237 DebugStream.println("Is event dispatch threa: " + SwingUtilities.isEventDispatchThread());
238
239 ArrayList sched_list = new ArrayList();
240 if (!Gatherer.isGsdlRemote) {
241 sched_list.add(Configuration.perl_path);
242 sched_list.add("-S");
243 }
244 sched_list.add(scriptPath + "schedule.pl");
245 sched_list.add("-colname");
246 sched_list.add(collection.getName());
247 sched_list.add("-gli");
248
249 // First, generate the import.pl command, also converting to a string
250 // Generate the import.pl command
251 ArrayList import_list = new ArrayList();
252 if (!Gatherer.isGsdlRemote) {
253 import_list.add(Configuration.perl_path);
254 import_list.add("-S");
255 }
256
257 String cmdPrefix = CollectionDesignManager.isCompleteBuild() ? "full-" : "incremental-";
258 import_list.add(scriptPath + cmdPrefix + "import.pl");
259 import_list.add("-language");
260 import_list.add(Configuration.getLanguage());
261 if(!Gatherer.isGsdlRemote) {
262 import_list.add("-collectdir");
263 import_list.add(getCollectDirectory());
264 }
265
266 String[] import_options = collection.import_options.getValues();
267 int i = 0;
268 for (i = 0; i < import_options.length; i++) {
269 import_list.add(import_options[i]);
270 }
271
272 import_list.add(collection.getGroupQualifiedName(false)); // (colgroup/)colname
273
274 String[] import_parts = (String[]) import_list.toArray(new String[0]);
275 String command = "";
276 i = 0;
277 for (i = 0; i < import_parts.length-1; i++) {
278 command = command + import_parts[i] + " ";
279 }
280 command = command + import_parts[i];
281
282 sched_list.add("-import");
283 sched_list.add("\"" + command + "\"");
284
285 // Generate the buildcol.pl command, also converting to a string
286 ArrayList build_list = new ArrayList();
287
288 // i'm not doing this in schedule.pl right now - should i be?
289 if (!Gatherer.isGsdlRemote) {
290 build_list.add(Configuration.perl_path);
291 build_list.add("-S");
292 }
293
294 String buildType = (new CollectionMeta( CollectionDesignManager.collect_config.getBuildType() )).getValue(CollectionMeta.TEXT);
295 if ( !CollectionDesignManager.isCompleteBuild() && buildType.equals( BuildTypeManager.BUILD_TYPE_LUCENE ) ) {
296 build_list.add(scriptPath + "incremental-buildcol.pl");
297 } else {
298 build_list.add(scriptPath + "full-buildcol.pl");
299 }
300
301 build_list.add("-language");
302 build_list.add(Configuration.getLanguage());
303 if(!Gatherer.isGsdlRemote) {
304 build_list.add("-collectdir");
305 build_list.add(getCollectDirectory());
306 }
307
308 String[] build_options = collection.build_options.getValues();
309 for (i = 0; i < build_options.length; i++) {
310 build_list.add(build_options[i]);
311 }
312
313 build_list.add(collection.getGroupQualifiedName(false)); // (colgroup/)colname
314
315 //build actual string
316 String[] build_parts = (String[]) build_list.toArray(new String[0]);
317 String command2 = "";
318 for(i = 0; i < build_parts.length-1; i++) {
319 command2 = command2 + build_parts[i] + " ";
320 }
321 command2 = command2 + build_parts[i];
322
323 sched_list.add("-build");
324 sched_list.add("\"" + command2 + "\"");
325
326 //next, the scheduling frequency goes here
327 String[] schedule_options = collection.schedule_options.getValues();
328 for(i = 0; i < schedule_options.length; i++) {
329 sched_list.add(schedule_options[i]);
330 }
331
332 //now, hope it will run. ;)
333 String[] sched_parts = (String[]) sched_list.toArray(new String[0]);
334
335 GShell shell = new GShell(sched_parts, GShell.SCHEDULE, SCHEDULING, this, schedule_monitor, GShell.GSHELL_SCHEDULE);
336 shell.addGShellListener(Gatherer.g_man.create_pane);
337 shell.addGShellListener(Gatherer.g_man.format_pane);
338 shell.start();
339 }
340
341 /** Used to determine whether the currently active collection has been built.
342 * @return A boolean indicating the built status of the collection.
343 */
344 public boolean built() {
345 if(collection != null) {
346 // Determine if the collection has been built by looking for the build.cfg (gs2)
347 // buildConfig.xml (gs3) or export.inf (fedora) file
348 String file_name = "";
349
350 if (Configuration.fedora_info != null && Configuration.fedora_info.isActive()) { // FLI case
351 // Fedora build
352 //file_name = getLoadedCollectionArchivesDirectoryPath() + "import.inf";
353 //file_name = getLoadedCollectionExportDirectoryPath() + "export.inf"; // export.pl no longer generates this
354 file_name = getLoadedCollectionExportDirectoryPath() + "archiveinf-doc.gdb";
355 } else {
356 // GLI is running, check if it's greenstone 3 or greenstone 2
357 if (Gatherer.GS3) { // GS3 GLI
358 file_name = getLoadedCollectionIndexDirectoryPath() + Utility.BUILD_CONFIG_XML;
359 }
360 else { // greenstone 2 GLI
361 file_name = getLoadedCollectionIndexDirectoryPath() + Utility.BUILD_CFG;
362 }
363 }
364 File test_file = new File(file_name);
365 return test_file.exists();
366 }
367 return false;
368 }
369
370 /** Used to determine whether the currently active collection has been imported.
371 * @return A boolean indicating the imported status of the collection.
372 */
373 public boolean imported() {
374 if ( collection != null ) {
375 String file_name = getLoadedCollectionDirectoryPath() + "archives";
376 File test_file = new File(file_name);
377 return test_file.exists();
378 }
379 return false;
380 }
381
382 /** 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 */
383 static private boolean canDelete(File file)
384 {
385 if (!file.isDirectory()) {
386 return file.canWrite();
387 }
388 File [] file_list = file.listFiles();
389 for (int i=0; i<file_list.length; i++) {
390 if (!canDelete(file_list[i])) {
391 return false;
392 }
393 }
394 return true;
395 }
396
397
398 /** Called to close the current collection and remove its lock file.
399 * @see org.greenstone.gatherer.Gatherer
400 * @see org.greenstone.gatherer.collection.Collection
401 * @see org.greenstone.gatherer.util.Utility
402 */
403 public void closeCollection() {
404 if (collection == null) {
405 return;
406 }
407 DebugStream.println("Close collection: " + collection.getName());
408
409 // Remove the lock on this file, then remove the collection.
410 File lock_file = new File(getLoadedCollectionDirectoryPath() + LOCK_FILE);
411 lock_file.delete();
412 if (lock_file.exists()) {
413 System.err.println("Warning: Lockfile was not successfully deleted.");
414 }
415
416 // Remove the lock file on the server
417 if (Gatherer.isGsdlRemote) {
418 Gatherer.remoteGreenstoneServer.deleteCollectionFile(collection.getGroupQualifiedName(false), lock_file);
419 }
420
421 MetadataSetManager.clearMetadataSets();
422 MetadataXMLFileManager.clearMetadataXMLFiles();
423 DocXMLFileManager.clearDocXMLFiles();
424 ProfileXMLFileManager.clearProfileXMLFile();
425
426 // If we're using the Local Library we must release the collection before writing to the collect.cfg file
427 if(Gatherer.isLocalLibrary) {
428 LocalLibraryServer.releaseCollection(getLoadedCollectionName(true)); // URL style slash //collection.getName());
429 }
430
431 collection.destroy();
432 collection = null;
433 collection_tree_model = null;
434 //Configuration.setCollectionConfiguration(null);
435 Gatherer.refresh(Gatherer.COLLECTION_CLOSED);
436 if (Gatherer.g_man != null) {
437 Gatherer.g_man.updateUI(); // !!! Necessary?
438 }
439 }
440
441//This method is no longer used in gs3 since the modification of CollectionConfiguration.java
442// public void convertToGS3Collection() {
443// // Generate the convert_coll_from_gs2.pl command
444// ArrayList command_parts_list = new ArrayList();
445// if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) {
446// command_parts_list.add(Configuration.perl_path);
447// command_parts_list.add("-S");
448// }
449// command_parts_list.add(Configuration.getGS3ScriptPath() + "convert_coll_from_gs2.pl");
450// command_parts_list.add("-collectdir");
451// command_parts_list.add(getCollectDirectory());
452// command_parts_list.add(collection.getGroupQualifiedName(false)); // (colgroup/)colname
453//
454// // Run the convert_coll_from_gs2.pl command
455// String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
456// GShell process = new GShell(command_parts, GShell.CONVERT, COLLECT, this, null, GShell.GSHELL_CONVERT);
457// process.addGShellListener(this);
458// process.run(); // Don't bother threading this... yet
459//
460// }
461
462 /** When basing a new collection on an existing one, we need to copy
463 * over some extra directories: all except import, archives, building, index
464 * really we just want images, macros, perllib, but there may also be eg style, or other dirs.
465 */
466 private boolean copyExtraBaseCollStuff(File new_coll_dir, File base_coll_dir) {
467 if (!new_coll_dir.isDirectory() || !base_coll_dir.isDirectory()) {
468 return false;
469 }
470 DebugStream.println("Copying extra dirs from the base collection");
471
472
473 File subdirs[] = base_coll_dir.listFiles();
474 for (int i = 0; subdirs != null && i < subdirs.length; i++) {
475 File subdir = subdirs[i];
476 if (subdir.isDirectory()) {
477 String dir_name = subdir.getName();
478 // ignore those we don't need, (archives, buildng, index) and
479 // those we are handling in another place (import, etc, metadata)
480 if (dir_name.startsWith ("import") || dir_name.startsWith("archives") || dir_name.startsWith("building") || dir_name.startsWith("index") || dir_name.startsWith("etc") || dir_name.startsWith("metadata") || dir_name.startsWith("log") || dir_name.startsWith("tmp")) {
481 continue;
482 }
483 try {
484 // copy the directory
485 File new_coll_subdir = new File(new_coll_dir, dir_name);
486 new_coll_subdir.mkdirs();
487 Gatherer.f_man.getQueue().copyDirectoryContents(subdir, new_coll_subdir);
488 }
489 catch (Exception e) {
490 DebugStream.println("Couldn't copy over the" + subdir+" dir from the base collection: "+e.toString());
491 }
492 }
493 }
494
495 return true;
496 }
497
498 /** 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.
499 * @param description a description of the collection as a String
500 * @param email the email address of the author/maintainer as a String
501 * @param name the short name of the collection, which will subsequently be used to refer to this particular collection, as a String
502 * @param title the longer title of the collection as a String
503 * @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
504 * @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
505 */
506 public void createCollection(String description, String email, String name, String title, File base_collection_directory, ArrayList metadata_sets)
507 {
508 // Display a modal progress popup to indicate that the collection is being loaded
509 ModalProgressPopup create_collection_progress_popup = new ModalProgressPopup(Dictionary.get("CollectionManager.Creating_Collection"), Dictionary.get("CollectionManager.Creating_Collection_Please_Wait"));
510 create_collection_progress_popup.display();
511
512 // Create the collection on a separate thread so the progress bar updates correctly
513 (new CreateCollectionTask(description, email, name, title, base_collection_directory, metadata_sets, create_collection_progress_popup)).start();
514 }
515
516
517 private class CreateCollectionTask
518 extends Thread
519 {
520 private String description = null;
521 private String email = null;
522 private String name = null;
523 private String title = null;
524 private File base_collection_directory = null;
525 private ArrayList metadata_sets = null;
526 private ModalProgressPopup create_collection_progress_popup = null;
527
528 public CreateCollectionTask(String description, String email, String name, String title, File base_collection_directory, ArrayList metadata_sets, ModalProgressPopup create_collection_progress_popup)
529 {
530 this.description = description;
531 this.email = email;
532 this.name = name;
533 this.title = title;
534 this.base_collection_directory = base_collection_directory;
535 this.metadata_sets = metadata_sets;
536 this.create_collection_progress_popup = create_collection_progress_popup;
537 }
538
539 public void run()
540 {
541 createCollectionInternal(description, email, name, title, base_collection_directory, metadata_sets);
542 create_collection_progress_popup.close();
543 }
544 }
545
546
547 private void createCollectionInternal(String description, String email, String name, String title, File base_collection_directory, ArrayList metadata_sets)
548 {
549 try {
550 // first make sure that the collect directory exists
551 File collect_dir = new File(getDefaultCollectDirectory());
552 if (!collect_dir.exists()) {
553 collect_dir.mkdirs();
554 }
555
556 // Create the new collection
557 makeCollection(name, email);
558
559 // Check that the collection has been created successfully
560 String collection_directory_path = getCollectionDirectoryPath(name);
561 if (!new File(collection_directory_path).exists()) {
562 // If there is no collection directory then the creation was unsuccessful, or cancelled
563
564 return;
565 }
566
567 // Check for the existence of the collection configuration file
568 String file_name = ((Gatherer.GS3 == true)? Utility.COLLECTION_CONFIG_XML : Utility.COLLECT_CFG);
569 File collect_cfg_file = new File(collection_directory_path + "etc" + File.separator + file_name);
570
571 if (!collect_cfg_file.exists()) {
572 System.err.println("Error: no " + file_name + " file has been created!");
573 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);
574 return;
575 }
576
577 // ACTIVE_DIR/log/
578 File log_dir = new File(collection_directory_path + "log");
579 log_dir.mkdirs();
580
581 // Make sure an import folder exists
582 File collection_import_directory = new File(collection_directory_path + "import");
583 if (!collection_import_directory.exists()) {
584 collection_import_directory.mkdirs();
585 if (Gatherer.isGsdlRemote) {
586 Gatherer.remoteGreenstoneServer.newCollectionDirectory(name, collection_import_directory);
587 }
588 }
589
590 // Now create the collection object around the directory.
591 collection = new Collection(new File(collection_directory_path, "gli.col"));
592
593 // for remote case, scheduling causes an Exception on creating a new collection that
594 // can't be recovered from. For GS3, it doesn't work since it it trying to access etc/main.cfg
595 if (canDoScheduling()) {
596 scheduling();
597 }
598
599 MetadataSetManager.clearMetadataSets();
600 MetadataXMLFileManager.clearMetadataXMLFiles();
601 DocXMLFileManager.clearDocXMLFiles();
602
603 // Import default metadata sets, if any
604 // for (int i = 0; metadata_sets != null && i < metadata_sets.size(); i++) {
605 // importMetadataSet((MetadataSet) metadata_sets.get(i));
606 // }
607
608 ProfileXMLFileManager.loadProfileXMLFile(new File(collection_directory_path + "metadata"));
609
610 // Before creating the CollectionDesignManager check if we are basing it upon some other collection
611 if (base_collection_directory != null) {
612 DebugStream.println("Basing new collection on existing one: " + base_collection_directory);
613
614 // If we're using a remote Greenstone server, download the collection shell to get the files needed
615 if (Gatherer.isGsdlRemote) {
616 String base_collection_name = base_collection_directory.getName();
617 Gatherer.remoteGreenstoneServer.downloadCollection(base_collection_name);
618 }
619
620 collection.setBaseCollection(base_collection_directory.getAbsolutePath());
621 // copy over other needed directories
622 copyExtraBaseCollStuff(new File(collection_directory_path), base_collection_directory);
623
624 // Try to import any existing metadata sets for this collection
625 // Look in base_collection_directory/metadata and import any metadata sets found.
626 File base_metadata_directory = new File(base_collection_directory, "metadata");
627 ArrayList base_metadata_sets = MetadataSetManager.listMetadataSets(base_metadata_directory);
628 if (base_metadata_sets != null) {
629 for (int i = 0; i < base_metadata_sets.size(); i++) {
630 importMetadataSet((MetadataSet) base_metadata_sets.get(i));
631 }
632 }
633 else {
634 DebugStream.println("This base collection has no metadata directory.");
635 }
636
637 // Now we update our collect.cfg
638 DebugStream.println("Copy and update " + file_name + " from base collection.");
639
640 if (Gatherer.GS3 == true) {
641 updateCollectionConfigXML(new File(base_collection_directory, Utility.CONFIG_GS3_FILE),
642 new File(collection_directory_path, Utility.CONFIG_GS3_FILE));
643 } else {
644 updateCollectionCFG(new File(base_collection_directory, Utility.CONFIG_FILE),
645 new File(collection_directory_path, Utility.CONFIG_FILE),
646 description, email, title);
647 }
648 }
649 else {
650 // only load metadata sets here if we have not based the collection on any other.
651 // Load the default metadata sets
652 addDefaultMetadataSets();
653
654 // Make sure we always have the extracted metadata set
655 addRequiredMetadataSets();
656 }
657
658 collection.cdm = new CollectionDesignManager(new File(getLoadedCollectionCfgFilePath()));
659
660 // We always set title and description here rather than calling mkcol.pl with Unicode arguments
661 CollectionMeta collection_name_collectionmeta = collection.cdm.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_COLLECTIONNAME_STR);
662 collection_name_collectionmeta.setValue(title);
663 CollectionMeta collection_extra_collectionmeta = collection.cdm.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_COLLECTIONEXTRA_STR);
664 collection_extra_collectionmeta.setValue(description);
665
666 // 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.
667 if (base_collection_directory != null) {
668 // Update the creator and maintainer
669 CollectionMeta creator_collectionmeta = new CollectionMeta(collection.cdm.collect_config.getCreator());
670 creator_collectionmeta.setValue(email);
671 creator_collectionmeta = null;
672 CollectionMeta maintainer_collectionmeta = new CollectionMeta(collection.cdm.collect_config.getMaintainer());
673 maintainer_collectionmeta.setValue(email);
674 maintainer_collectionmeta = null;
675
676 // All collections based on others are automatically public
677 CollectionMeta public_collectionmeta = new CollectionMeta(collection.cdm.collect_config.getPublic());
678 public_collectionmeta.setValue(StaticStrings.TRUE_STR);
679 public_collectionmeta = null;
680
681 // Finally reset the icons
682 CollectionMeta icon_collection_collectionmeta = collection.cdm.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_ICONCOLLECTION_STR);
683 icon_collection_collectionmeta.setValue(StaticStrings.EMPTY_STR);
684 icon_collection_collectionmeta = null;
685 CollectionMeta icon_collection_small_collectionmeta = collection.cdm.collectionmeta_manager.getMetadatum(StaticStrings.COLLECTIONMETADATA_ICONCOLLECTIONSMALL_STR);
686 icon_collection_small_collectionmeta.setValue(StaticStrings.EMPTY_STR);
687 icon_collection_small_collectionmeta = null;
688 }
689
690 saveCollection();
691
692 // Create a lock file
693 createLockFile(new File(collection_directory_path, LOCK_FILE));
694
695 // We're done. Let everyone know.
696 Gatherer.refresh(Gatherer.COLLECTION_OPENED);
697 }
698 catch (Exception error) {
699 DebugStream.printStackTrace(error);
700 }
701 }
702
703 private void scheduling()
704 throws Exception
705 {
706 //try to obtain email address of collection owner if it exists...
707 String stmp = Configuration.getEmail();
708 if(stmp != null) {
709 collection.schedule_options.setValue("toaddr", false, Configuration.getEmail());
710 }
711
712 //The next few items deal with updating the SMTP server, and the to: and from: addresses
713 //from main.cfg and the collection configuration. if no changes are made, or the
714 //values are result to NULL, any existing values are kept.
715
716 //try to obtain email address of Greenstone installation webmaster for - used to indicate "sender".
717 File mcfg = new File(LocalGreenstone.getDirectoryPath() + File.separator + "etc" + File.separator + "main.cfg");
718 BufferedReader maincfg = new BufferedReader(new FileReader(mcfg));
719 stmp = "";
720 String fromaddr = "";
721 while((stmp = maincfg.readLine()) != null) {
722 if(stmp.startsWith("maintainer")) {
723 fromaddr = stmp.substring(10); //length of MailServer
724 fromaddr = fromaddr.trim();
725 break;
726 }
727 }
728 maincfg.close();
729 if(!fromaddr.equals("NULL") && !fromaddr.equals("null")) {
730 collection.schedule_options.setValue("fromaddr", false, fromaddr);
731 }
732
733 //try to obtain an smtp server address from main.cfg. If that fails,
734 //try mail.server if an email address exists. If that fails,
735 //maybe a message to set attribute in main.cfg?
736 //i'm pretty sure there exists functionality to do this, but
737 //i'll finish this faster if I just wrote it
738
739
740 maincfg = new BufferedReader(new FileReader(mcfg));
741 String smtptmp = "NULL";
742 while((stmp = maincfg.readLine()) != null) {
743 if(stmp.startsWith("MailServer")) {
744 smtptmp = stmp.substring(10); //length of MailServer
745 smtptmp = smtptmp.trim();
746 break;
747 }
748 }
749 maincfg.close();
750
751 //try if lookup fails
752 if(smtptmp.equals("NULL") || smtptmp.equals("null")) {
753 String email2=fromaddr;
754 if(!email2.equals("NULL") && !email2.equals("null")) {
755 int loc = email2.indexOf('@');
756 email2 = email2.substring(loc+1);
757 smtptmp = "mail."+email2;
758 }
759 }
760 if(!smtptmp.equals("NULL") && !smtptmp.equals("null")) {
761 collection.schedule_options.setValue("smtp", false, smtptmp);
762 }
763
764 }
765
766
767 private void createLockFile(File lock_file)
768 {
769 try {
770 Document default_lockfile = XMLTools.parseXMLFile("xml/" + LOCK_FILE, true);
771 String user_name = System.getProperty("user.name");
772 Element person_element = (Element) XMLTools.getNodeFromNamed(default_lockfile.getDocumentElement(), "User");
773 person_element.appendChild(default_lockfile.createTextNode(user_name));
774 person_element = null;
775 user_name = null;
776 String machine_name = Utility.getMachineName();
777 Element machine_element = (Element) XMLTools.getNodeFromNamed(default_lockfile.getDocumentElement(), "Machine");
778 machine_element.appendChild(default_lockfile.createTextNode(machine_name));
779 machine_element = null;
780 machine_name = null;
781 String date_time = Utility.getDateString();
782 Element date_element = (Element) XMLTools.getNodeFromNamed(default_lockfile.getDocumentElement(), "Date");
783 date_element.appendChild(default_lockfile.createTextNode(date_time));
784 date_element = null;
785 date_time = null;
786 XMLTools.writeXMLFile(lock_file, default_lockfile);
787 }
788 catch (Exception exception) {
789 DebugStream.printStackTrace(exception);
790 }
791 }
792
793
794 public boolean deleteCollection(String collection_name)
795 {
796 // First we must release the collection from the local library, if it's running
797 if (LocalLibraryServer.isRunning() == true) {
798 LocalLibraryServer.releaseCollection(collection_name);
799 }
800
801 // Delete the collection on the server if we're using a remote Greenstone
802 if (Gatherer.isGsdlRemote) {
803 Gatherer.remoteGreenstoneServer.deleteCollection(collection_name);
804 }
805
806 // if Greenstone3, need to deactivate the collection on the server
807 if (Gatherer.GS3) {
808 Gatherer.configGS3Server(Configuration.site_name, ServletConfiguration.DEACTIVATE_COMMAND + collection_name);
809 }
810
811 // Now delete the collection directory
812 return Utility.delete(new File(getCollectionDirectoryPath(collection_name)));
813 }
814
815
816 public void fireFileAddedToCollection(File file)
817 {
818 // Send the event off to all the CollectionContentsChangedListeners
819 for (int i = 0; i < collection_contents_changed_listeners.size(); i++) {
820 ((CollectionContentsChangedListener) collection_contents_changed_listeners.get(i)).fileAddedToCollection(file);
821 }
822 }
823
824
825 /** Retrieve the current collection.
826 * @return The <strong>Collection</strong> itself.
827 */
828 public Collection getCollection() {
829 return collection;
830 }
831
832
833 /** Returns the absolute filename of the specified collection's directory.
834 */
835 static public String getCollectionDirectoryPath(String collection_name)
836 {
837 return Gatherer.getCollectDirectoryPath() + collection_name + File.separator;
838 }
839
840
841 /** Returns the absolute filename of the loaded collection's archives directory.
842 */
843 static public String getLoadedCollectionArchivesDirectoryPath()
844 {
845 return getLoadedCollectionDirectoryPath() + "archives" + File.separator;
846 }
847
848 /** Returns the absolute filename of the loaded collection's export directory.
849 */
850 static public String getLoadedCollectionExportDirectoryPath()
851 {
852 return getLoadedCollectionDirectoryPath() + "export" + File.separator;
853 }
854
855
856
857 /** Returns the absolute filename of the loaded collection's building directory.
858 */
859 static public String getLoadedCollectionBuildingDirectoryPath()
860 {
861 return getLoadedCollectionDirectoryPath() + "building" + File.separator;
862 }
863
864
865 /** Returns the absolute filename of the loaded collection's collect.cfg file.
866 */
867 static public String getLoadedCollectionCfgFilePath()
868 {
869 String path = (Gatherer.GS3 == true)? Utility.COLLECTION_CONFIG_XML : Utility.COLLECT_CFG;
870 return getLoadedCollectionEtcDirectoryPath() + path;
871 }
872
873
874 /** Returns the absolute filename of the loaded collection's directory.
875 */
876 static public String getLoadedCollectionDirectoryPath()
877 {
878 return collection.getCollectionDirectory().getPath() + File.separator;
879 }
880
881
882 /** Returns the absolute filename of the loaded collection's etc directory.
883 */
884 static public String getLoadedCollectionEtcDirectoryPath()
885 {
886 return getLoadedCollectionDirectoryPath() + "etc" + File.separator;
887 }
888
889
890 /** Returns the absolute filename of the loaded collection's .col file.
891 */
892 static public String getLoadedCollectionColFilePath()
893 {
894 return getLoadedCollectionDirectoryPath() + "gli.col";
895 }
896
897
898 /** Returns the absolute filename of the loaded collection's images directory.
899 */
900 static public String getLoadedCollectionImagesDirectoryPath()
901 {
902 return getLoadedCollectionDirectoryPath() + "images" + File.separator;
903 }
904
905
906 /** Returns the absolute filename of the loaded collection's import directory.
907 */
908 static public String getLoadedCollectionImportDirectoryPath()
909 {
910 return getLoadedCollectionDirectoryPath() + "import" + File.separator;
911 }
912
913
914 /** Returns the absolute filename of the loaded collection's index directory.
915 */
916 static public String getLoadedCollectionIndexDirectoryPath()
917 {
918 return getLoadedCollectionDirectoryPath() + "index" + File.separator;
919 }
920
921
922 /** Returns the absolute filename of the loaded collection's log directory.
923 */
924 static public String getLoadedCollectionLogDirectoryPath()
925 {
926 return getLoadedCollectionDirectoryPath() + "log" + File.separator;
927 }
928
929
930 /** Returns the absolute filename of the loaded collection's macros directory.
931 */
932 static public String getLoadedCollectionMacrosDirectoryPath()
933 {
934 return getLoadedCollectionDirectoryPath() + "macros" + File.separator;
935 }
936
937
938 /** Returns the absolute filename of the loaded collection's metadata directory.
939 */
940 static public String getLoadedCollectionMetadataDirectoryPath()
941 {
942 return getLoadedCollectionDirectoryPath() + "metadata" + File.separator;
943 }
944
945
946 /** Returns the (group-qualified) name of the loaded collection with
947 * OS-dependent file separator.
948 */
949 static public String getLoadedCollectionName()
950 {
951 return CollectionManager.getLoadedCollectionName(false);
952 }
953
954 /** Returns the (group-qualified) name of the loaded collection with
955 * OS-dependent space separator.
956 * @url true if url-type forward slashes, false if OS-dependent filesystem slashes.
957 */
958 static public String getLoadedCollectionName(boolean url)
959 {
960 if (collection != null) {
961 //return collection.getName();
962 return collection.getGroupQualifiedName(url);
963 }
964
965 return null;
966 }
967
968 /** @return the subname of any collection (stripped of any collection-group). */
969 static public String getLoadedCollectionTailName()
970 {
971 if (collection != null) {
972 return collection.getCollectionTailName();
973 }
974
975 return null;
976 }
977
978 /** Returns the "collectionGroupName/collectionName" or just the collectionName
979 * depending on whether the collection is part of a collection group or not.
980 * If url = true, then returns the sub-path as a URL (containing / only),
981 * and if url = false, then the sub-path is returned in filepath form
982 * (\ or /, depending on the OS).
983 */
984 static public String getLoadedGroupQualifiedCollectionName(boolean url)
985 {
986 if (collection != null) {
987 return collection.getGroupQualifiedName(url);
988 }
989
990 return null;
991 }
992
993 public CollectionTree getCollectionTree()
994 {
995 if (collection_tree == null) {
996 collection_tree = new CollectionTree(collection_tree_model, true);
997 }
998
999 return collection_tree;
1000 }
1001
1002
1003 /** Retrieve the tree model associated with the current collection. */
1004 public CollectionTreeModel getCollectionTreeModel()
1005 {
1006 if (collection_tree_model == null && collection != null) {
1007 // Use the import directory to generate a new CollectionTreeModel
1008 collection_tree_model = new CollectionTreeModel(new CollectionTreeNode(new File(getLoadedCollectionImportDirectoryPath())));
1009 // Ensure that the manager is a change listener for the tree.
1010 if (fm_tree_model_listener == null) {
1011 fm_tree_model_listener = new FMTreeModelListener();
1012 }
1013 collection_tree_model.addTreeModelListener(fm_tree_model_listener);
1014 }
1015 return collection_tree_model;
1016 }
1017
1018
1019 /** This method when called, creates a new GShell in order to run the import.pl script.
1020 * @see org.greenstone.gatherer.Configuration
1021 * @see org.greenstone.gatherer.Gatherer
1022 * @see org.greenstone.gatherer.gui.BuildOptions
1023 * @see org.greenstone.gatherer.shell.GShell
1024 * @see org.greenstone.gatherer.shell.GShellListener
1025 * @see org.greenstone.gatherer.shell.GShellProgressMonitor
1026 * @see org.greenstone.gatherer.util.Utility
1027 */
1028 public void importCollection() {
1029 importing = true;
1030
1031 if (!saved()) {
1032 DebugStream.println("CollectionManager.importCollection().forcesave");
1033 import_monitor.saving();
1034 saveCollection();
1035 }
1036
1037 DebugStream.println("CollectionManager.importCollection()");
1038 DebugStream.println("Is event dispatch thread: " + SwingUtilities.isEventDispatchThread());
1039 //check that we can remove the old index before starting import
1040 File index_dir = new File(getLoadedCollectionIndexDirectoryPath());
1041 if (index_dir.exists()) {
1042 DebugStream.println("Old Index = " + index_dir.getAbsolutePath()+", testing for deletability");
1043 if (!canDelete(index_dir)) {
1044 // tell the user
1045 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Delete_Index"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1046 // tell the gui manager
1047 // a message for the building log
1048 GShellEvent event = new GShellEvent(this, 0, GShell.IMPORT, Dictionary.get("CollectionManager.Cannot_Delete_Index_Log"), GShell.ERROR);
1049 Gatherer.g_man.create_pane.message(event);
1050 event = new GShellEvent(this, 0, GShell.IMPORT, "", GShell.ERROR);
1051 Gatherer.g_man.create_pane.processComplete(event);
1052 importing = false;
1053 return;
1054 }
1055 }
1056
1057 // Generate the import.pl command
1058 ArrayList command_parts_list = new ArrayList();
1059 if (!Gatherer.isGsdlRemote) {
1060 command_parts_list.add(Configuration.perl_path);
1061 command_parts_list.add("-S");
1062 }
1063
1064 if (Configuration.fedora_info.isActive()) {
1065 command_parts_list.add(scriptPath + "g2f-import.pl");
1066
1067 command_parts_list.add("-hostname");
1068 command_parts_list.add(Configuration.fedora_info.getHostname());
1069
1070 command_parts_list.add("-port");
1071 command_parts_list.add(Configuration.fedora_info.getPort());
1072
1073 command_parts_list.add("-username");
1074 command_parts_list.add(Configuration.fedora_info.getUsername());
1075
1076 command_parts_list.add("-password");
1077 command_parts_list.add(Configuration.fedora_info.getPassword());
1078
1079 command_parts_list.add("-protocol");
1080 command_parts_list.add(Configuration.fedora_info.getProtocol());
1081 }
1082 else {
1083 String cmdPrefix = null;
1084 if ( CollectionDesignManager.isCompleteBuild() ) {
1085 cmdPrefix = "full-";
1086 CollectionDesignManager.setImportWasFull( true );
1087 } else {
1088 cmdPrefix = "incremental-";
1089 CollectionDesignManager.setImportWasFull( false );
1090 }
1091 command_parts_list.add(scriptPath + cmdPrefix + "import.pl"); // scriptPath already set according to local or remote case
1092 }
1093
1094 command_parts_list.add("-gli");
1095 command_parts_list.add("-language");
1096 command_parts_list.add(Configuration.getLanguage());
1097 if(!Gatherer.isGsdlRemote) {
1098 command_parts_list.add("-collectdir");
1099 command_parts_list.add(getCollectDirectory());
1100 }
1101
1102 String[] import_options = collection.import_options.getValues();
1103 for (int i = 0; i < import_options.length; i++) {
1104 System.err.println( "Tacking on option: " + import_options[i] );
1105 command_parts_list.add(import_options[i]);
1106 }
1107
1108 command_parts_list.add(collection.getGroupQualifiedName(false)); // (colgroup/)colname
1109
1110 // Run the import.pl command
1111 String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
1112 GShell shell = new GShell(command_parts, GShell.IMPORT, BUILDING, this, import_monitor, GShell.GSHELL_IMPORT);
1113 //shell.setEventProperty("is_incremental", Boolean.toString(is_incremental));
1114 shell.addGShellListener(Gatherer.g_man.create_pane);
1115 shell.addGShellListener(Gatherer.g_man.format_pane);
1116 shell.start();
1117 DebugStream.println("CollectionManager.importCollection().return");
1118
1119 importing = false;
1120 }
1121
1122
1123 public void importMetadataSet(MetadataSet external_metadata_set)
1124 {
1125 // Copy the .mds file into the collection's "metadata" folder...
1126 File external_metadata_set_file = external_metadata_set.getMetadataSetFile();
1127
1128 // ...but not if it is the redundant "hidden.mds" file
1129 if (external_metadata_set_file.getName().equals("hidden.mds")) {
1130 return;
1131 }
1132
1133 // ...and only if it doesn't already exist
1134 File metadata_set_file = new File(getLoadedCollectionMetadataDirectoryPath(), external_metadata_set_file.getName());
1135 if (!metadata_set_file.exists()) {
1136 try {
1137 Gatherer.f_man.getQueue().copyFile(external_metadata_set_file, metadata_set_file, false);
1138
1139 // If we're using a remote Greenstone server, upload the metadata file
1140 if (Gatherer.isGsdlRemote) {
1141 Gatherer.remoteGreenstoneServer.uploadCollectionFile(collection.getGroupQualifiedName(false), metadata_set_file);
1142 }
1143 }
1144 catch (Exception exception) {
1145 DebugStream.printStackTrace(exception);
1146 }
1147
1148 // Load it into the MetadataSetManager
1149 MetadataSetManager.loadMetadataSet(metadata_set_file);
1150 }
1151 }
1152
1153
1154 /** 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.
1155 * @return true if the gli is currently importing
1156 */
1157 public boolean isImporting() {
1158 return importing;
1159 }
1160
1161
1162 public void loadCollection(String collection_file_path)
1163 {
1164 if(new File(collection_file_path).isDirectory()) { // collect folder instead of previously-opened collection
1165 Gatherer.setMenuBarEnabled(true);
1166 return; // nothing else to be done, no collection to open
1167 }
1168
1169 // Display a modal progress popup to indicate that the collection is being loaded
1170 ModalProgressPopup load_collection_progress_popup = new ModalProgressPopup(Dictionary.get("CollectionManager.Loading_Collection"), Dictionary.get("CollectionManager.Loading_Collection_Please_Wait"));
1171 load_collection_progress_popup.display();
1172
1173 // Load the collection on a separate thread so the progress bar updates correctly
1174 (new LoadCollectionTask(collection_file_path, load_collection_progress_popup)).start();
1175 }
1176
1177
1178 private class LoadCollectionTask
1179 extends Thread
1180 {
1181 private String collection_file_path = null;
1182 private ModalProgressPopup load_collection_progress_popup = null;
1183
1184 public LoadCollectionTask(String collection_file_path, ModalProgressPopup load_collection_progress_popup)
1185 {
1186 this.collection_file_path = collection_file_path;
1187 this.load_collection_progress_popup = load_collection_progress_popup;
1188 }
1189
1190 public void run()
1191 {
1192 loadCollectionInternal(collection_file_path);
1193 load_collection_progress_popup.close();
1194 Gatherer.setMenuBarEnabled(true);
1195 }
1196 }
1197
1198
1199 /** Attempts to load the given collection. Currently uses simple serialization of the collection class.
1200 * @param location The path to the collection as a <strong>String</strong>.
1201 * @see org.greenstone.gatherer.Configuration
1202 * @see org.greenstone.gatherer.Gatherer
1203 * @see org.greenstone.gatherer.collection.Collection
1204 * @see org.greenstone.gatherer.util.Utility
1205 */
1206 private void loadCollectionInternal(String location)
1207 {
1208 DebugStream.println("Loading collection " + location + "...");
1209
1210
1211 // Check we have actually been given a .col file.
1212 if (!location.endsWith(".col")) {
1213 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Not_Col_File", location), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1214 DebugStream.println("CollectionManager.loadCollection: Haven't been given a .col file.");
1215 return;
1216 }
1217
1218 // Check that the collection configuration file is available
1219 File collection_file = new File(location);
1220
1221 //String collection_name = collection_directory.getName();
1222 String collection_name = "";
1223 File collection_directory = collection_file.getParentFile();
1224
1225 // To get colname = (colgroup/)coltailname, subtract Gatherer.getCollectDirectoryPath() from collection_directory:
1226 int index = collection_directory.getAbsolutePath().indexOf(Gatherer.getCollectDirectoryPath());
1227 if(index == -1) {
1228 System.err.println("*** ERROR: collection directory " + collection_directory + " is not located in collect folder: " + Gatherer.getCollectDirectoryPath());
1229 } else {
1230 index += Gatherer.getCollectDirectoryPath().length();
1231 collection_name = collection_directory.getAbsolutePath().substring(index);
1232 }
1233
1234 if (Gatherer.isGsdlRemote) {
1235 if (Gatherer.remoteGreenstoneServer.downloadCollection(collection_name).equals("")) {
1236 return;
1237 }
1238 }
1239
1240 // Ensure that the collection directory exists
1241 if (collection_directory == null || !collection_directory.exists()) {
1242 // We can't open this
1243 System.err.println("CollectionManager.loadCollection: No collection directory.");
1244 return;
1245 }
1246
1247 String file_str = (Gatherer.GS3)? Utility.CONFIG_GS3_FILE : Utility.CONFIG_FILE;
1248 File collection_config_file = new File(collection_directory, file_str);
1249 if (!collection_config_file.exists()) {
1250 System.err.println("CollectionManager.loadCollection: No config file.");
1251 collection_directory = null;
1252 collection_config_file = null;
1253 return;
1254 }
1255
1256 // Ensure that an import directory exists for this collection
1257 File collection_import_directory = new File(collection_directory, "import");
1258 if (!collection_import_directory.exists()) {
1259 collection_import_directory.mkdir();
1260 }
1261
1262 // Special case of a user trying to open an old greenstone collection.
1263 boolean non_gli_collection = false;
1264 File collection_metadata_directory = new File(collection_directory, "metadata");
1265 if (!collection_metadata_directory.exists()) {
1266 DebugStream.println("Loading non-gatherer collection...");
1267 // Show a warning message in case user wants to quit now
1268 non_gli_collection = true;
1269 WarningDialog legacy_dialog = new WarningDialog("warning.LegacyCollection", Dictionary.get("LegacyCollection.Title"), Dictionary.get("LegacyCollection.Message"), null, true);
1270 if (legacy_dialog.display()==JOptionPane.CANCEL_OPTION) {
1271 legacy_dialog.dispose();
1272 collection_directory = null;
1273 collection_config_file = null;
1274 return;
1275 }
1276 legacy_dialog.dispose();
1277
1278 }
1279
1280 // Now determine if a lock already exists on this collection.
1281 File lock_file = new File(collection_file.getParentFile(), LOCK_FILE);
1282 if (lock_file.exists()) {
1283 LockFileDialog dialog = new LockFileDialog(Gatherer.g_man, collection_name, lock_file);
1284 int choice = dialog.getChoice();
1285 dialog.dispose();
1286 dialog = null;
1287
1288 if (choice != LockFileDialog.YES_OPTION) {
1289 // user has cancelled
1290 lock_file = null;
1291 collection_directory = null;
1292 collection_config_file = null;
1293 return;
1294 }
1295
1296 lock_file.delete();
1297 }
1298
1299 // now we are using gli.col - old colls may have used the collection name
1300 if (!collection_file.exists()) {
1301 File old_coll_file = new File(collection_directory, collection_name+".col");
1302 if (old_coll_file.exists()) {
1303 try {
1304 old_coll_file.renameTo(collection_file);
1305 } catch (Exception e) {
1306 DebugStream.println("Couldn't rename "+old_coll_file.getName()+" to gli.col. Will just carry on with default gli.col");
1307 // but just carry on.
1308 }
1309 }
1310 }
1311
1312 try {
1313 // Create a lock file.
1314 createLockFile(lock_file);
1315 // This lock file may not have been created so check
1316 if(!lock_file.canWrite()) {
1317 // The lock file cannot be written to. Most likely cause incorrect file permissions.
1318 System.err.println("Cannot write lock file!");
1319 String args[] = new String[2];
1320 args[0] = location;
1321 args[1] = Dictionary.get("FileActions.Write_Not_Permitted_Message", new String[]{lock_file.getAbsolutePath()});
1322 if(Gatherer.client_operating_system.toUpperCase().indexOf("WINDOWS")!=-1){
1323 //if(Gatherer.client_operating_system.toUpperCase().indexOf("VISTA")!=-1){
1324 args[1] += Dictionary.get("FileActions.File_Permission_Detail", new String[]{Configuration.gsdl_path, System.getProperty("user.name")});
1325 //}
1326 }
1327 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open_With_Reason", args), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1328 args = null;
1329 return;
1330 }
1331
1332 // need to fix this up as currently it craps out if the .col file is not there, which is may not always be.
1333 if (canDoScheduling() && collection_file.exists()) {
1334 //THIS LOOKS LIKE THE BEST PLACE TO TRY AND UPDATE .col FILES FOR EXISTING COLLECTIONS...Wendy
1335 // Don't need to update anything if collection_file doesn't exist yet.
1336 //First, see if "Schedule" exists in the XMl File...
1337 BufferedReader bir = new BufferedReader(new FileReader(collection_file));
1338 boolean flag = false;
1339 try {
1340 String stmp = new String();
1341
1342 while((stmp = bir.readLine()) != null) {
1343 stmp = stmp.trim();
1344 if(stmp.equals("<Schedule>") || stmp.equals("<Schedule/>")) {
1345 flag = true;
1346 break;
1347 }
1348 }
1349 bir.close();
1350
1351 } catch (IOException ioe) {
1352 DebugStream.printStackTrace(ioe);
1353 }
1354
1355 //modify if old .col (i.e. no Schedule exists in XML file)
1356 if(!flag) {
1357 File new_collection_file = new File(collection_directory.getAbsolutePath() + "/tmp.col");
1358
1359
1360 BufferedWriter bor = new BufferedWriter(new FileWriter(new_collection_file));
1361 bir = new BufferedReader(new FileReader(collection_file));
1362
1363 try {
1364 String stmp = new String();
1365 while((stmp = bir.readLine()) != null) {
1366 String stmp2 = stmp.trim();
1367 if(stmp2.startsWith("<!ELEMENT Argument")) {
1368 bor.write(" <!ELEMENT Schedule (Arguments*)>\n");
1369 }
1370 else if(stmp2.equals("</BuildConfig>")) {
1371 bor.write(" <Schedule/>\n");
1372 }
1373
1374 bor.write(stmp + "\n");
1375
1376 }
1377 bir.close();
1378 bor.close();
1379 } catch (IOException ioe) {
1380 DebugStream.printStackTrace(ioe);
1381 }
1382
1383 //copy over tmp.col to replace
1384 try {
1385 collection_file.delete();
1386 new_collection_file.renameTo(collection_file);
1387 } catch (Exception e) {
1388 DebugStream.printStackTrace(e);
1389 }
1390 }
1391 }
1392
1393 // Open the collection file
1394 this.collection = new Collection(collection_file);
1395 if (collection.error) {
1396 collection = null;
1397 // Remove lock file
1398 if (lock_file.exists()) {
1399 lock_file.delete();
1400 }
1401 throw(new Exception(Dictionary.get("CollectionManager.Missing_Config"))); // this error message does not agree with the error
1402 }
1403
1404 if (canDoScheduling()) {
1405 scheduling();
1406 }
1407
1408 // These may have been set in the past, but are no longer used
1409 // by GLI
1410 collection.import_options.removeValue("removeold");
1411 collection.import_options.removeValue("keepold");
1412
1413 MetadataSetManager.clearMetadataSets();
1414 MetadataSetManager.loadMetadataSets(collection_metadata_directory);
1415
1416 // Make sure we always have the extracted metadata set
1417 addRequiredMetadataSets();
1418
1419 ProfileXMLFileManager.loadProfileXMLFile(collection_metadata_directory);
1420
1421 // If this is a non-GLI (legacy) collection, load the default metadata sets
1422 if (non_gli_collection) {
1423 addDefaultMetadataSets();
1424
1425 // Recurse the import folder tree, backing up the metadata.xml files before they are edited
1426 LegacyCollectionImporter.backupMetadataXMLFiles(collection_directory);
1427 }
1428
1429 // Read through the metadata.xml files in the import directory, building up the metadata value trees
1430 MetadataXMLFileManager.clearMetadataXMLFiles();
1431 MetadataXMLFileManager.loadMetadataXMLFiles(collection_import_directory,collection.toSkimFile());
1432
1433
1434 // get rid of the previous scan through docxml files
1435 DocXMLFileManager.clearDocXMLFiles();
1436
1437 if (Configuration.fedora_info.isActive()) { // FLI case
1438 // Read through the docmets.xml files in the export directory
1439 File collection_export_directory = new File(getLoadedCollectionExportDirectoryPath());
1440 DocXMLFileManager.loadDocXMLFiles(collection_export_directory,"docmets.xml");
1441 }
1442 else {
1443 // Read through the doc.xml files in the archives directory
1444 File collection_archives_directory = new File(getLoadedCollectionArchivesDirectoryPath());
1445 DocXMLFileManager.loadDocXMLFiles(collection_archives_directory,"doc.xml");
1446 }
1447
1448
1449 // Get a list of the collection specific classifiers and plugins
1450 Classifiers.loadClassifiersList(collection_name);
1451 Plugins.loadPluginsList(collection_name);
1452
1453 collection.cdm = new CollectionDesignManager(collection_config_file);
1454 if (non_gli_collection) {
1455 // Change the classifiers to use the namespaced element names
1456 LegacyCollectionImporter.updateClassifiers(collection.cdm);
1457 }
1458
1459 // We're done. Let everyone know.
1460 DebugStream.println(Dictionary.get("CollectionManager.Loading_Successful", collection_name));
1461 Gatherer.refresh(Gatherer.COLLECTION_OPENED);
1462 }
1463 catch (Exception error) {
1464 // There is obviously no existing collection present.
1465 DebugStream.printStackTrace(error);
1466 error.printStackTrace();
1467 if(error.getMessage() != null) {
1468 String[] args = new String[2];
1469 args[0] = location;
1470 args[1] = error.getMessage();
1471 //args[1] = "The Librarian Interface does not have permission to write to... Please check file permissions.";
1472 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open_With_Reason", args), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1473 }
1474 else {
1475 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open", location), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1476 }
1477 }
1478
1479 lock_file = null;
1480 collection_directory = null;
1481 collection_config_file = null;
1482 }
1483
1484 /** At present, scheduling only works for GS2, only when GS2 is local and only when GLI runs from
1485 * within a GS2 installation. This method can be adjusted as scheduling becomes available for more
1486 * more situations. */
1487 public static boolean canDoScheduling() {
1488 // Would be nice to support more of these, rather than returning false
1489 if(Gatherer.isGsdlRemote) {
1490 return false;
1491 }
1492 if(Gatherer.GS3) {
1493 return false;
1494 }
1495 if (Configuration.fedora_info.isActive()) {
1496 return false;
1497 }
1498
1499 // GS2's etc/main.cfg is necessary for scheduling, but scheduling looks for it locally:
1500 // it assumes GLI is inside a GS2 installation
1501 File mcfg = new File(LocalGreenstone.getDirectoryPath() + File.separator + "etc" + File.separator + "main.cfg");
1502 if(!mcfg.exists()) {
1503 System.out.println("Cannot do scheduling, since there is no file: " + mcfg.getAbsolutePath()
1504 + ".\nScheduling presently depends on GLI running from inside a GS2.");
1505 return false;
1506 }
1507
1508 return true;
1509 }
1510
1511 private void makeCollection(String name, String email)
1512 {
1513 // Generate the mkcol.pl command
1514 ArrayList command_parts_list = new ArrayList();
1515 if (!Gatherer.isGsdlRemote) {
1516 command_parts_list.add(Configuration.perl_path);
1517 command_parts_list.add("-S");
1518 }
1519 command_parts_list.add(scriptPath + "mkcol.pl");
1520 if(Gatherer.GS3) {
1521 command_parts_list.add(Utility.GS3MODE_ARGUMENT); // add '-gs3mode'
1522 }
1523 if(!Gatherer.isGsdlRemote) {
1524 command_parts_list.add("-collectdir");
1525 command_parts_list.add(getDefaultCollectDirectory());
1526 }
1527 command_parts_list.add("-win31compat");
1528 command_parts_list.add((Gatherer.isGsdlRemote) ? "false" : "true");
1529
1530 if (email != null && !email.equals("")) {
1531 command_parts_list.add("-creator");
1532 command_parts_list.add(email);
1533 }
1534
1535 command_parts_list.add(name);
1536
1537 // Run the mkcol.pl command
1538 String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);
1539 //for(int i = 0; i < command_parts.length; i++) {
1540 ///ystem.err.println("\""+command_parts[i]+"\"");
1541 //}
1542
1543 GShell process = new GShell(command_parts, GShell.NEW, COLLECT, this, null, GShell.GSHELL_NEW);
1544 process.run(); // Don't bother threading this... yet
1545 }
1546
1547
1548 /** 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.
1549 * @param event A <strong>GShellEvent</strong> which contains a the message.
1550 */
1551 public synchronized void message(GShellEvent event) {
1552
1553 }
1554
1555
1556 public void metadataChanged(CollectionTreeNode[] file_nodes)
1557 {
1558 if (collection != null) {
1559 collection.setMetadataChanged(true);
1560 }
1561 }
1562
1563
1564 public void openCollectionFromLastTime() {
1565 // If there was an open collection last session, reopen it
1566 if (Gatherer.open_collection_file_path != null) {
1567 // Load the collection now
1568 loadCollection(Gatherer.open_collection_file_path);
1569 }
1570
1571 }
1572
1573
1574 /** This call is fired whenever a process within a GShell created by this class begins.
1575 * @param event A <strong>GShellEvent</strong> containing information about the GShell process.
1576 * @see org.greenstone.gatherer.Gatherer
1577 * @see org.greenstone.gatherer.gui.GUIManager
1578 * @see org.greenstone.gatherer.shell.GShell
1579 */
1580 public synchronized void processBegun(GShellEvent event) {
1581 DebugStream.println("CollectionManager.processBegun(" + event.getType() + ")");
1582 ///ystem.err.println("ProcessBegun " + event.getType());
1583 // If this is one of the types where we wish to lock user control
1584 Gatherer.g_man.lockCollection((event.getType() == GShell.IMPORT), true);
1585 }
1586 /** This call is fired whenever a process within a GShell created by this class ends.
1587 * @param event A <strong>GShellEvent</strong> containing information about the GShell process.
1588 * @see org.greenstone.gatherer.Gatherer
1589 * @see org.greenstone.gatherer.gui.GUIManager
1590 * @see org.greenstone.gatherer.shell.GShell
1591 */
1592 public synchronized void processComplete(GShellEvent event) {
1593 //ystem.err.println("CollectionManager.processComplete(" + event.getType() + ")");
1594 Gatherer.g_man.lockCollection((event.getType() == GShell.IMPORT), false);
1595 ///ystem.err.println("Received process complete event - " + event);
1596 // If we were running an import, now run a build.
1597 if(event.getType() == GShell.IMPORT && event.getStatus() == GShell.OK) {
1598 // Finish import.
1599 collection.setImported(true);
1600 collection.setFilesChanged(false);
1601 collection.setMetadataChanged(false);
1602 buildCollection();
1603 }
1604 else if(event.getType() == GShell.SCHEDULE && event.getStatus() == GShell.OK ) {
1605
1606 WarningDialog collection_built_warning_dialog = new WarningDialog("warning.ScheduleBuilt", Dictionary.get("ScheduleBuilt.Title"), Dictionary.get("ScheduleBuilt.Message"), null, false);
1607 collection_built_warning_dialog.setMessageOnly(true); // Not a warning
1608 collection_built_warning_dialog.display();
1609 collection_built_warning_dialog.dispose();
1610 collection_built_warning_dialog = null;
1611 }
1612 // If we were running a build, now is when we move files across.
1613 else if(event.getType() == GShell.BUILD && event.getStatus() == GShell.OK) {
1614
1615 if ( CollectionDesignManager.buildcolWasFull() ) {
1616 if(installCollection()) {
1617 // If we have a local library running then ask it to add our newly create collection
1618 if (LocalLibraryServer.isRunning() == true) {
1619 LocalLibraryServer.addCollection(collection.getName());
1620 }
1621 else if (Gatherer.GS3) {
1622 //xiao comment out this: convertToGS3Collection();
1623 Gatherer.configGS3Server(Configuration.site_name, ServletConfiguration.ADD_COMMAND + collection.getName());
1624 }
1625
1626 // Fire a collection changed first to update the preview etc buttons
1627 Gatherer.refresh(Gatherer.COLLECTION_REBUILT);
1628
1629 // Now display a message dialog saying its all built
1630 WarningDialog collection_built_warning_dialog = new WarningDialog("warning.CollectionBuilt", Dictionary.get("CollectionBuilt.Title"), Dictionary.get("CollectionBuilt.Message"), null, false);
1631 collection_built_warning_dialog.setMessageOnly(true); // Not a warning
1632 collection_built_warning_dialog.display();
1633 collection_built_warning_dialog.dispose();
1634 collection_built_warning_dialog = null;
1635
1636 //Set nothing as needing rebuilding, as a build has just finished :-)
1637 CollectionDesignManager.resetRebuildTypeRequired();
1638 }
1639 else {
1640 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Preview_Ready_Failed"), Dictionary.get("CollectionManager.Preview_Ready_Title"), JOptionPane.ERROR_MESSAGE);
1641 Gatherer.refresh(Gatherer.COLLECTION_REBUILT);
1642 DebugStream.println("Status is ok but !installCollection()");
1643 }
1644 }
1645 }
1646 else if (event.getStatus() == GShell.CANCELLED) {
1647 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Build_Cancelled"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1648 Gatherer.g_man.repaint();
1649 }
1650 else if (event.getStatus() == GShell.ERROR) {
1651 if (event.getType() == GShell.NEW) {
1652 String name = event.getMessage();
1653 String collectDir = getCollectionDirectoryPath(name);
1654 String errMsg = "";
1655 if (!new File(getCollectionDirectoryPath(name)).exists() || !new File(getCollectionDirectoryPath(name)).canWrite()) {
1656 String reason = Dictionary.get("FileActions.Write_Not_Permitted_Message", new String[]{collectDir});
1657 errMsg = Dictionary.get("CollectionManager.Cannot_Create_Collection_With_Reason", new String[]{reason});
1658 if(Gatherer.client_operating_system.toUpperCase().indexOf("WINDOWS") != -1){
1659 //if(Gatherer.client_operating_system.toUpperCase().indexOf("VISTA")!=-1){
1660 errMsg += Dictionary.get("FileActions.File_Permission_Detail", new String[]{Configuration.gsdl_path, System.getProperty("user.name")});
1661 //}
1662 }
1663 } else {
1664 errMsg = Dictionary.get("CollectionManager.Cannot_Create_Collection");
1665 }
1666 JOptionPane.showMessageDialog(Gatherer.g_man, errMsg, Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
1667 }
1668 else if(event.getType() == GShell.SCHEDULE) {
1669 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Schedule_Failed"), Dictionary.get("CollectionManager.Schedule_Ready_Title"), JOptionPane.ERROR_MESSAGE);
1670 }
1671 else {
1672 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Preview_Ready_Failed"), Dictionary.get("CollectionManager.Preview_Ready_Title"), JOptionPane.ERROR_MESSAGE);
1673 Gatherer.refresh(Gatherer.COLLECTION_REBUILT);
1674 }
1675
1676 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.
1677 }
1678 }
1679
1680
1681 /** Determine if the manager is ready for actions apon its collection.
1682 * @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.
1683 */
1684 static public synchronized boolean ready() {
1685 if(collection != null) {
1686 return true;
1687 }
1688 else {
1689 return false;
1690 }
1691 }
1692
1693
1694 /** This method associates the collection build monitor with the build monitor created in CreatePane.
1695 * @param monitor A <strong>GShellProgressMonitor</strong> which we will use as the build monitor.
1696 */
1697 public void registerBuildMonitor(GShellProgressMonitor monitor) {
1698 build_monitor = monitor;
1699 }
1700 /** This method associates the collection import monitor with the import monitor created in CreatePane.
1701 * @param monitor A <strong>GShellProgressMonitor</strong> which we will use as the import monitor.
1702 */
1703 public void registerImportMonitor(GShellProgressMonitor monitor) {
1704 import_monitor = monitor;
1705 }
1706
1707 public void registerScheduleMonitor(GShellProgressMonitor monitor) {
1708 schedule_monitor = monitor;
1709 }
1710
1711
1712 static public void removeCollectionContentsChangedListener(CollectionContentsChangedListener listener)
1713 {
1714 collection_contents_changed_listeners.remove(listener);
1715 }
1716
1717
1718 public void removeMetadataSet(MetadataSet metadata_set)
1719 {
1720 DebugStream.println("Removing metadata set...");
1721
1722 // Delete the .mds file from the collection's "metadata" folder...
1723 File metadata_set_file = metadata_set.getMetadataSetFile();
1724
1725 // ...but not if it is the "ex.mds" file
1726 if (metadata_set_file.getName().equals("ex.mds")) {
1727 return;
1728 }
1729
1730 // ...and only if it exists
1731 if (metadata_set_file.exists()) {
1732 metadata_set_file.delete();
1733
1734 // Unload it from the MetadataSetManager
1735 MetadataSetManager.unloadMetadataSet(metadata_set);
1736
1737 // If we're using a remote Greenstone server, delete the metadata file on the server
1738 if (Gatherer.isGsdlRemote) {
1739 Gatherer.remoteGreenstoneServer.deleteCollectionFile(collection.getGroupQualifiedName(false), metadata_set_file);
1740 }
1741 }
1742 }
1743
1744
1745 /** Used to check whether all open collections have a 'saved' state.
1746 * @return A <i>boolean</i> which is <i>true</i> if the collection has been saved.
1747 * @see org.greenstone.gatherer.collection.Collection
1748 */
1749 public boolean saved() {
1750 boolean result = true;
1751 if(collection != null) {
1752 result = collection.getSaved();
1753 }
1754 return result;
1755 }
1756
1757
1758 /** Saves the currently loaded collection. */
1759 public void saveCollection()
1760 {
1761
1762 if (collection == null) return;
1763
1764 DebugStream.println("Saving collection " + collection.getName() + "...");
1765
1766 // Change cursor to hourglass
1767 Gatherer.g_man.wait(true);
1768
1769 // Create a backup of the collection file, just in case anything goes wrong
1770 File collection_file = new File(getLoadedCollectionColFilePath());
1771 if (collection_file.exists()) {
1772 File collection_file_backup = new File(collection_file.getAbsolutePath() + "~");
1773 if (!collection_file.renameTo(collection_file_backup)) {
1774 DebugStream.println("Error in CollectionManager.saveCollection(): could not create backup file.");
1775 }
1776 collection_file_backup.deleteOnExit();
1777 }
1778
1779 // Write out the collection file
1780 collection.save();
1781
1782 // Write out the collection configuration file
1783 collection.cdm.save();
1784
1785 // Change cursor back to normal
1786 Gatherer.g_man.wait(false);
1787 }
1788
1789
1790 /** 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] */
1791 // now add in greenstone metadata set too.
1792 private void addDefaultMetadataSets()
1793 {
1794 // Add dublin core which is the default metadata set. The user
1795 // can change this later
1796 File dc_file = new File(Gatherer.getGLIMetadataDirectoryPath()+"dublin.mds");
1797 if (dc_file.exists()) {
1798 importMetadataSet(new MetadataSet(dc_file));
1799 }
1800 File gs_file = new File(Gatherer.getGLIMetadataDirectoryPath()+"greenstone.mds");
1801 if (gs_file.exists()) {
1802 importMetadataSet(new MetadataSet(gs_file));
1803 }
1804 }
1805
1806
1807 private void addRequiredMetadataSets()
1808 {
1809 // Always import the extracted metadata set
1810 File extracted_metadata_set_file = new File(Gatherer.getGLIMetadataDirectoryPath() + MetadataSetManager.EXTRACTED_METADATA_NAMESPACE + StaticStrings.METADATA_SET_EXTENSION);
1811 importMetadataSet(new MetadataSet(extracted_metadata_set_file));
1812 }
1813
1814 private String getDefaultCollectDirectory() {
1815 String collect_dir = Gatherer.getCollectDirectoryPath();
1816 // Remove erroneous file windows file separator as it causes problems when running import.pl
1817 if(collect_dir.length() > 2 && collect_dir.endsWith("\\")) {
1818 collect_dir = collect_dir.substring(0, collect_dir.length() - 1);
1819 }
1820 return collect_dir;
1821 }
1822
1823 // used as arg in the perl scripts
1824 private String getCollectDirectory() {
1825 String collect_dir = Gatherer.getCollectDirectoryPath();
1826 return collect_dir.substring(0, collect_dir.length()-1); // remove trailing slash
1827
1828 // the following will stick any colgroup at the end of the collect directory, making it no longer
1829 // possible to get the real collect dir in a general manner if this were located outside greenstone
1830 //String collect_dir = collection.getCollectionDirectory().getParentFile().getPath();
1831 //return collect_dir;
1832 }
1833
1834
1835 /** Install collection by moving its files from building to index after a successful build.
1836 * @see org.greenstone.gatherer.Gatherer
1837 * @see org.greenstone.gatherer.util.Utility
1838 */
1839 private boolean installCollection()
1840 {
1841 if (Configuration.fedora_info.isActive()) {
1842 DebugStream.println("Fedora build complete. No need to move files.");
1843 return true;
1844 }
1845
1846
1847 DebugStream.println("Build complete. Moving files.");
1848
1849 try {
1850 // Ensure that the local library has released this collection so we can delete the index directory
1851 if (LocalLibraryServer.isRunning() == true) {
1852 LocalLibraryServer.releaseCollection(getLoadedCollectionName(true)); // URL style slash //collection.getName());
1853 }
1854 // deactivate it in tomcat so that windows will release the index files
1855 if (Gatherer.GS3 && !Gatherer.isGsdlRemote) {
1856 Gatherer.configGS3Server(Configuration.site_name, ServletConfiguration.DEACTIVATE_COMMAND + collection.getName());
1857 }
1858 File index_dir = new File(getLoadedCollectionIndexDirectoryPath());
1859 DebugStream.println("Index = " + index_dir.getAbsolutePath());
1860
1861 File building_dir = new File(getLoadedCollectionBuildingDirectoryPath());
1862 DebugStream.println("Building = " + building_dir.getAbsolutePath());
1863
1864 // Get the build mode from the build options
1865 String build_mode = collection.build_options.getValue("mode");
1866
1867 // Special case for build mode "all": replace index dir with building dir
1868 if (build_mode == null || build_mode.equals(Dictionary.get("CreatePane.Mode_All"))) {
1869 // Remove the old index directory
1870 if (index_dir.exists()) {
1871 Utility.delete(index_dir);
1872
1873 // Wait for a couple of seconds, just for luck
1874 wait(2000);
1875
1876 // Check the delete worked
1877 if (index_dir.exists()) {
1878 throw new Exception(Dictionary.get("CollectionManager.Index_Not_Deleted"));
1879 }
1880 }
1881
1882 if (Gatherer.isGsdlRemote) {
1883 Gatherer.remoteGreenstoneServer.deleteCollectionFile(
1884 collection.getGroupQualifiedName(false), new File(getLoadedCollectionIndexDirectoryPath()));
1885 Gatherer.remoteGreenstoneServer.moveCollectionFile(collection.getGroupQualifiedName(false),
1886 new File(getLoadedCollectionBuildingDirectoryPath()), new File(getLoadedCollectionIndexDirectoryPath()));
1887 }
1888
1889 // Move the building directory to become the new index directory
1890 if (building_dir.renameTo(index_dir) == false) {
1891 throw new Exception(Dictionary.get("CollectionManager.Build_Not_Moved"));
1892 }
1893 }
1894
1895 // Otherwise copy everything in the building dir into the index dir
1896 else {
1897 moveContentsInto(building_dir, index_dir);
1898 }
1899 }
1900 catch (Exception exception) {
1901 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Install_Exception", exception.getMessage()), "Error", JOptionPane.ERROR_MESSAGE);
1902 return false;
1903 }
1904 return true;
1905 }
1906
1907
1908 /** Moves all the files in one directory into another, overwriting existing files */
1909 private void moveContentsInto(File source_directory, File target_directory)
1910 {
1911 File[] source_files = source_directory.listFiles();
1912 for (int i = 0; i < source_files.length; i++) {
1913 File source_file = source_files[i];
1914 File target_file = new File(target_directory, source_file.getName());
1915
1916 if (source_file.isDirectory()) {
1917 moveContentsInto(source_file, target_file);
1918 source_file.delete();
1919 }
1920 else {
1921 if (target_file.exists()) {
1922 target_file.delete();
1923 }
1924
1925 source_file.renameTo(target_file);
1926 }
1927 }
1928 }
1929
1930 private void updateCollectionConfigXML(File base_cfg, File new_cfg) {
1931 //In this method, the files base_cfg and new_cfg are all xml files.
1932
1933 Document base_cfg_doc = XMLTools.parseXMLFile(base_cfg);
1934 XMLTools.writeXMLFile(new_cfg, base_cfg_doc);
1935 Document new_cfg_doc = XMLTools.parseXMLFile(new_cfg);
1936 Element collection_config = new_cfg_doc.getDocumentElement();
1937
1938 Node browseNode = XMLTools.getChildByTagNameIndexed(collection_config, StaticStrings.BROWSE_STR, 0);
1939 NodeList classifier_children = ((Element)browseNode).getElementsByTagName(StaticStrings.CLASSIFIER_STR);
1940 int num_nodes = classifier_children.getLength();
1941
1942 if (num_nodes < 1) {
1943 return;
1944 }
1945
1946 // Read in the classifier command watching for hfile, metadata and sort arguments.
1947 String buttonname = null;
1948 String hfile = null;
1949 String metadata = null;
1950 String sort = null;
1951
1952 for (int i=0; i<num_nodes; i++) {
1953 Element classifier_element = (Element)classifier_children.item(i);
1954 NodeList option_children = classifier_element.getElementsByTagName(StaticStrings.OPTION_STR);
1955 for (int j=0; j<option_children.getLength(); j++) {
1956 Element option_element = (Element)option_children.item(j);
1957 String name_str = option_element.getAttribute(StaticStrings.NAME_ATTRIBUTE);
1958 String value_str = option_element.getAttribute(StaticStrings.VALUE_ATTRIBUTE);
1959
1960 if (name_str == null || name_str.equals("")) {
1961 continue;
1962 }
1963 if (name_str != null && value_str == null ) {
1964 value_str = "";
1965 }
1966 if (name_str.equals("hfile")) {
1967 hfile = value_str;
1968 }
1969 else if (name_str.equals("metadata") && value_str != null) {
1970 String replacement = ProfileXMLFileManager.getMetadataElementFor(value_str);
1971 if (replacement != null && !replacement.equals("")) {
1972 metadata = replacement;
1973 }
1974 }
1975 else if (name_str.equals("sort") && value_str != null) {
1976 String replacement = ProfileXMLFileManager.getMetadataElementFor(value_str);
1977 if (replacement != null && !replacement.equals("")) {
1978 sort = replacement;
1979 }
1980 }
1981 else if(name_str.equals("buttonname") && value_str != null) {
1982 buttonname = value_str;
1983 }
1984 }
1985 }
1986 for (int i=0; i<num_nodes; i++) {
1987 Element classifier_element = (Element)classifier_children.item(i);
1988 NodeList option_children = classifier_element.getElementsByTagName(StaticStrings.OPTION_STR);
1989 for (int j=0; j<option_children.getLength(); j++) {
1990 Element option_element = (Element)option_children.item(j);
1991 String name_str = option_element.getAttribute(StaticStrings.NAME_ATTRIBUTE);
1992
1993 if (name_str.equals("metadata") && metadata != null) {
1994 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, metadata);
1995 }
1996 else if (name_str.equals("hfile") && hfile != null) {
1997 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, metadata + ".txt");
1998 }
1999 else if (name_str.equals("sort") && sort != null) {
2000 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, sort);
2001 }
2002 else if(name_str.equals("buttonname") && (buttonname == "" || buttonname == null)) {
2003 // No buttonname has been specified. Lets create one using the metadata as its value
2004 Element option = new_cfg_doc.createElement(StaticStrings.OPTION_STR);
2005 option.setAttribute(StaticStrings.NAME_ATTRIBUTE, "buttonname");
2006 option_element.setAttribute(StaticStrings.VALUE_ATTRIBUTE, metadata);
2007 classifier_element.appendChild(option);
2008 }
2009 }
2010 }
2011 }
2012
2013 private void updateCollectionCFG(File base_cfg, File new_cfg, String description, String email, String title)
2014 {
2015 boolean first_name = true;
2016 boolean first_extra = true;
2017
2018 // 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.
2019 try {
2020 BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(base_cfg), "UTF-8"));
2021 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new_cfg), "UTF-8"));
2022 String command = null;
2023 while((command = in.readLine()) != null) {
2024 if (command.length()==0) {
2025 // output a new line
2026 out.newLine();
2027 continue;
2028 }
2029 // We have to test the end of command for the special character '\'. If found, remove it and append the next line, then repeat.
2030 while(command.trim().endsWith("\\")) {
2031 command = command.substring(0, command.lastIndexOf("\\"));
2032 String next_line = in.readLine();
2033 if(next_line != null) {
2034 command = command + next_line;
2035 }
2036 }
2037 // commands can extend over more than one line so use the CommandTokenizer which takes care of that
2038 CommandTokenizer tokenizer = new CommandTokenizer(command, in, false);
2039 String command_type_str = tokenizer.nextToken().toLowerCase();
2040
2041 if (command_type_str.equals(StaticStrings.COLLECTIONMETADATA_STR)) {
2042 // read the whole thing in, but for collectionname, collectionextra, iconcollection, iconcollectionsmall we will ignore them
2043 StringBuffer new_command = new StringBuffer(command_type_str);
2044 String meta_name = tokenizer.nextToken();
2045 new_command.append(' ');
2046 new_command.append(meta_name);
2047 while (tokenizer.hasMoreTokens()) {
2048 new_command.append(' ');
2049 new_command.append(tokenizer.nextToken());
2050 }
2051 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)) {
2052 // dont save
2053 } else {
2054 write(out, new_command.toString());
2055 }
2056 new_command = null;
2057 continue;
2058 } // if collectionmeta
2059
2060 if (command_type_str.equals("classify")) {
2061 StringBuffer text = new StringBuffer(command_type_str);
2062 // Read in the classifier command watching for hfile, metadata and sort arguments.
2063 String buttonname = null;
2064 String hfile = null;
2065 String new_metadata = null;
2066 String old_metadata = null;
2067
2068 while(tokenizer.hasMoreTokens()) {
2069 String token = tokenizer.nextToken();
2070 if (token.equals("-hfile")) {
2071 if(tokenizer.hasMoreTokens()) {
2072 text.append(" ");
2073 text.append(token);
2074 token = tokenizer.nextToken();
2075 hfile = token;
2076 }
2077 }
2078 else if (token.equals("-metadata")) {
2079 if(tokenizer.hasMoreTokens()) {
2080 text.append(" ");
2081 text.append(token);
2082 String temp_metadata = tokenizer.nextToken();
2083 String replacement = ProfileXMLFileManager.getMetadataElementFor(temp_metadata);
2084 if (replacement != null && !replacement.equals("")) {
2085 token = replacement;
2086 old_metadata = temp_metadata;
2087 new_metadata = replacement;
2088 }
2089 else {
2090 token = temp_metadata;
2091 }
2092 temp_metadata = null;
2093 replacement = null;
2094 }
2095 }
2096 else if (token.equals("-sort")) {
2097 if(tokenizer.hasMoreTokens()) {
2098 text.append(" ");
2099 text.append(token);
2100 String temp_metadata = tokenizer.nextToken();
2101 String replacement = ProfileXMLFileManager.getMetadataElementFor(temp_metadata);
2102 if (replacement != null && !replacement.equals("")) {
2103 token = replacement;
2104 }
2105 else {
2106 token = temp_metadata;
2107 }
2108 temp_metadata = null;
2109 replacement = null;
2110 }
2111 }
2112 else if(token.equals("-buttonname")) {
2113 buttonname = token;
2114 }
2115 text.append(' ');
2116 text.append(token);
2117 token = null;
2118 }
2119
2120 // 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)!
2121 if(old_metadata != null && new_metadata != null && buttonname == null) {
2122 text.append(' ');
2123 text.append("-buttonname");
2124 text.append(' ');
2125 text.append(old_metadata);
2126 }
2127 command = text.toString();
2128 // Replace the hfile if we found it
2129 if(hfile != null && new_metadata != null) {
2130 command = command.replaceAll(hfile, new_metadata + ".txt");
2131 }
2132
2133 buttonname = null;
2134 hfile = null;
2135 new_metadata = null;
2136 old_metadata = null;
2137 write(out, command);
2138 } else {
2139 // the rest of the commands just want a string - we read in all the tokens from the tokeniser and get rid of it.
2140 StringBuffer new_command = new StringBuffer(command_type_str);
2141 while (tokenizer.hasMoreTokens()) {
2142 new_command.append(' ');
2143 new_command.append(tokenizer.nextToken());
2144 }
2145
2146 command = new_command.toString();
2147
2148 // 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.
2149 // we really want to build up the whole command here
2150 boolean format_command = command_type_str.equals("format");
2151 HashMap metadata_mapping = ProfileXMLFileManager.getMetadataMapping();
2152 if (metadata_mapping != null) {
2153 Iterator keys = metadata_mapping.keySet().iterator();
2154 while (keys.hasNext()) {
2155 String target = (String) keys.next();
2156 String replacement = (String) metadata_mapping.get(target);
2157 if (replacement != null && !replacement.equals("")) {
2158 if (format_command) {
2159 target = "\\[" + target + "\\]";
2160 replacement = "{Or}{[" + replacement + "]," + target + "}";
2161 }
2162 command = command.replaceAll(target, replacement);
2163 }
2164 }
2165 }
2166
2167 write(out, command);
2168 }
2169 tokenizer = null;
2170 }
2171 in.close();
2172 in = null;
2173 out.flush();
2174 out.close();
2175 out = null;
2176 }
2177 catch(Exception error) {
2178 DebugStream.printStackTrace(error);
2179 }
2180 // All done, I hope.
2181 }
2182
2183 private void write(BufferedWriter out, String message)
2184 throws Exception {
2185 out.write(message, 0, message.length());
2186 out.newLine();
2187 }
2188
2189
2190 /** The CollectionManager class is getting too confusing by half so I'll implement this TreeModelListener in a private class to make responsibility clear. */
2191 private class FMTreeModelListener
2192 implements TreeModelListener {
2193 /** 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.
2194 * @param event A <strong>TreeModelEvent</strong> encompassing all the information about the event which has changed the tree.
2195 */
2196 public void treeNodesChanged(TreeModelEvent event) {
2197 if(collection != null) {
2198 collection.setSaved(false);
2199 collection.setFilesChanged(true);
2200 }
2201 }
2202 /** 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.
2203 * @param event A <strong>TreeModelEvent</strong> encompassing all the information about the event which has changed the tree.
2204 */
2205 public void treeNodesInserted(TreeModelEvent event) {
2206 if(collection != null) {
2207 collection.setSaved(false);
2208 collection.setFilesChanged(true);
2209 }
2210 }
2211 /** 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.
2212 * @param event A <strong>TreeModelEvent</strong> encompassing all the information about the event which has changed the tree.
2213 */
2214 public void treeNodesRemoved(TreeModelEvent event) {
2215 if(collection != null) {
2216 collection.setSaved(false);
2217 collection.setFilesChanged(true);
2218
2219 }
2220 }
2221 /** 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.
2222 * @param event A <strong>TreeModelEvent</strong> encompassing all the information about the event which has changed the tree.
2223 */
2224 public void treeStructureChanged(TreeModelEvent event) {
2225 if(collection != null) {
2226 collection.setSaved(false);
2227 }
2228 }
2229 }
2230}
Note: See TracBrowser for help on using the repository browser.