/** *######################################################################### * * A component of the Gatherer application, part of the Greenstone digital * library suite from the New Zealand Digital Library Project at the * University of Waikato, New Zealand. * *

* * Author: John Thompson, Greenstone Digital Library, University of Waikato * *

* * Copyright (C) 1999 New Zealand Digital Library Project * *

* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * *

* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * *

* * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *######################################################################## */ package org.greenstone.gatherer.collection; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.filechooser.FileSystemView; import javax.swing.tree.*; import org.greenstone.gatherer.Configuration; import org.greenstone.gatherer.DebugStream; import org.greenstone.gatherer.Dictionary; import org.greenstone.gatherer.Gatherer; import org.greenstone.gatherer.LocalLibraryServer; import org.greenstone.gatherer.ServletConfiguration; import org.greenstone.gatherer.cdm.CollectionDesignManager; import org.greenstone.gatherer.cdm.CollectionMeta; import org.greenstone.gatherer.cdm.CollectionMetaManager; import org.greenstone.gatherer.cdm.CommandTokenizer; import org.greenstone.gatherer.gui.LockFileDialog; import org.greenstone.gatherer.gui.NewCollectionMetadataPrompt; import org.greenstone.gatherer.gui.ExternalCollectionPrompt; import org.greenstone.gatherer.gui.WarningDialog; import org.greenstone.gatherer.metadata.DocXMLFileManager; import org.greenstone.gatherer.metadata.MetadataSet; import org.greenstone.gatherer.metadata.MetadataSetManager; import org.greenstone.gatherer.metadata.MetadataXMLFileManager; import org.greenstone.gatherer.metadata.ProfileXMLFileManager; import org.greenstone.gatherer.shell.GShell; import org.greenstone.gatherer.shell.GShellEvent; import org.greenstone.gatherer.shell.GShellListener; import org.greenstone.gatherer.shell.GShellProgressMonitor; import org.greenstone.gatherer.util.ArrayTools; import org.greenstone.gatherer.util.Codec; import org.greenstone.gatherer.util.StaticStrings; import org.greenstone.gatherer.util.Utility; import org.greenstone.gatherer.util.XMLTools; import org.w3c.dom.*; /** This class manages many aspects of the collection, from its creation via scripts, data access via methods and its importing and building into the final collection. It is also resposible for firing appropriate event when significant changes have occured within the collection, and for creating a new metadata set manager as necessary. * @author John Thompson * @version 2.3 */ public class CollectionManager implements GShellListener { /** Are we currently in the process of building? */ private boolean building = false; /** Are we currently in the process of importing? */ private boolean importing = false; /** The objects listening for CollectionContentsChanged events. */ private ArrayList collection_contents_changed_listeners = new ArrayList(); /** The collection this manager is managing! */ static private Collection collection = null; /** The collection_model. */ private CollectionTreeModel collection_model = null; /** An inner class listener responsible for noting tree changes and resetting saved when they occur. */ private FMTreeModelListener fm_tree_model_listener = null; /** The monitor resposible for parsing the build process. */ private GShellProgressMonitor build_monitor = null; /** The monitor resposible for parsing the import process. */ private GShellProgressMonitor import_monitor = null; /** The name of the standard lock file. */ static final public String LOCK_FILE = "gli.lck"; /** Used to indicate the source of the message is the file collection methods. */ static final public int COLLECT = 3; /** Used to indicate the source of the message is the building methods. */ static final public int BUILDING = 5; /** Constructor. */ public CollectionManager() { // Initialisation. this.building = false; this.importing = false; this.collection = null; } public void addCollectionContentsChangedListener(CollectionContentsChangedListener listener) { collection_contents_changed_listeners.add(listener); } /** This method calls the builcol.pl scripts via a GShell so as to not lock up the processor. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.gui.BuildOptions * @see org.greenstone.gatherer.shell.GShell * @see org.greenstone.gatherer.shell.GShellListener * @see org.greenstone.gatherer.shell.GShellProgressMonitor * @see org.greenstone.gatherer.util.Utility */ private void buildCollection() { DebugStream.println("CollectionManager.buildCollection()"); building = true; String lang = Configuration.getLanguage(); String collect_dir = getCollectDirectory(); String args[]; if((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) { args = new String[8]; args[0] = Configuration.perl_path; args[1] = "-S"; args[2] = Configuration.getScriptPath() + "buildcol.pl"; args[3] = "-gli"; args[4] = "-language"; args[5] = lang; args[6] = "-collectdir"; args[7] = collect_dir; } else { args = new String[6]; args[0] = Configuration.getScriptPath() + "buildcol.pl"; args[1] = "-gli"; args[2] = "-language"; args[3] = lang; args[4] = "-collectdir"; args[5] = collect_dir; } args = ArrayTools.add(args, collection.build_options.getBuildValues()); args = ArrayTools.add(args, collection.getName()); GShell shell = new GShell(args, GShell.BUILD, BUILDING, this, build_monitor, GShell.GSHELL_BUILD); shell.addGShellListener(Gatherer.g_man.create_pane); shell.start(); DebugStream.println("CollectionManager.buildCollection().return"); } /** Used to determine whether the currently active collection has been built. * @return A boolean indicating the built status of the collection. */ public boolean built() { if(collection != null) { // Determine if the collection has been built by looking for the build.cfg file File build_cfg_file = new File(getCollectionIndex() + Utility.BUILD_CFG_FILENAME); return build_cfg_file.exists(); } return false; } /** 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 */ public boolean canDelete(File file) { if (!file.isDirectory()) { return file.canWrite(); } File [] file_list = file.listFiles(); for (int i=0; iCollection itself. */ public Collection getCollection() { return collection; } /** Constructs the absolute filename of the collection archive directory, which should resemble "$GSDLHOME/collect/<col_name>/archive/" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionArchives() { if (Gatherer.GS3) { return Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName()) + "archives" + File.separator; } else { return Utility.getCollectionDir(Configuration.gsdl_path, collection.getName()) + "archives" + File.separator; } } /** Constructs the absolute filename of the collection building directory, which should resemble "$GSDLHOME/collect/<col_name>/building/" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionBuild() { if (Gatherer.GS3) { return Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName()) + "building" + File.separator; } else { return Utility.getCollectionDir(Configuration.gsdl_path, collection.getName()) + "building" + File.separator; } } /** Constructs the absolute filename of the collection config file, which should resemble "$GSDLHOME/collect/<col_name>/etc/collect.cfg" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionConfig() { if (Gatherer.GS3) { return Utility.getConfigFile(Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName())); } else { return Utility.getConfigFile(Utility.getCollectionDir(Configuration.gsdl_path, collection.getName())); } } /** Constructs the absolute filename of the collection directory, which should resemble "$GSDLHOME/collect/<col_name>" * @return A String containing the directory name. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionDirectory() { if (Gatherer.GS3) { return Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName()); } else { return Utility.getCollectionDir(Configuration.gsdl_path, collection.getName()); } } /** Constructs the absolute filename of the collection etc directory, which should resemble "$GSDLHOME/collect/<col_name>/etc/" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionEtc() { if (Gatherer.GS3) { return Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName()) + "etc" + File.separator; } else { return Utility.getCollectionDir(Configuration.gsdl_path, collection.getName()) + "etc" + File.separator; } } /** Constructs the absolute filename of the collection file, which should resemble "$GSDLHOME/collect/<col_name>/<col_name>.col" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionFilename() { if (Gatherer.GS3) { return Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName()) + collection.getName() + ".col"; } else { return Utility.getCollectionDir(Configuration.gsdl_path, collection.getName()) + collection.getName() + ".col"; } } /** Constructs the absolute filename of the collection images directory, which should resemble "$GSDLHOME/collect/<col_name>/images/" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionImages() { if (Gatherer.GS3) { return Utility.getImagesDir(Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName())); } else { return Utility.getImagesDir(Utility.getCollectionDir(Configuration.gsdl_path, collection.getName())); } } /** Constructs the absolute filename of the collection import directory, which should resemble "$GSDLHOME/collect/<col_name>/import/" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionImport() { if (Gatherer.GS3) { return Utility.getImportDir(Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName())); } else { return Utility.getImportDir(Utility.getCollectionDir(Configuration.gsdl_path, collection.getName())); } } /** Constructs the absolute filename of the collection index directory, which should resemble "$GSDLHOME/collect/<col_name>/index/" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionIndex() { if (Gatherer.GS3) { return Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName()) + "index" + File.separator; } else { return Utility.getCollectionDir(Configuration.gsdl_path, collection.getName()) + "index" + File.separator; } } /** Constructs the absolute filename of the collection log directory, which should resemble "$GSDLHOME/collect/<col_name>/log/" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionLog() { if (Gatherer.GS3) { return Utility.getLogDir(Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName())); } else { return Utility.getLogDir(Utility.getCollectionDir(Configuration.gsdl_path, collection.getName())); } } /** Constructs the absolute filename of the collection metadata directory, which should resemble "$GSDLHOME/collect/<col_name>/metadata/" * @return A String containing the filename. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public String getCollectionMetadata() { if (Gatherer.GS3) { return Utility.getCollectionDir(Configuration.gsdl3_path, Configuration.site_name, collection.getName()) + "metadata" + File.separator; } else { return Utility.getCollectionDir(Configuration.gsdl_path, collection.getName()) + "metadata" + File.separator; } } /** Retrieve the tree model associated with the current collection. */ public CollectionTreeModel getCollectionTreeModel() { if (collection_model == null && collection != null) { // Use the import directory to generate a new CollectionTreeModel collection_model = new CollectionTreeModel(new CollectionTreeNode(new File(getCollectionImport()))); // Ensure that the manager is a change listener for the tree. if (fm_tree_model_listener == null) { fm_tree_model_listener = new FMTreeModelListener(); } collection_model.addTreeModelListener(fm_tree_model_listener); } return collection_model; } /** This method when called, creates a new GShell in order to run the import.pl script. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.gui.BuildOptions * @see org.greenstone.gatherer.shell.GShell * @see org.greenstone.gatherer.shell.GShellListener * @see org.greenstone.gatherer.shell.GShellProgressMonitor * @see org.greenstone.gatherer.util.Utility */ public void importCollection() { importing = true; if (!saved()) { DebugStream.println("CollectionManager.importCollection().forcesave"); import_monitor.saving(); saveCollection(); } DebugStream.println("CollectionManager.importCollection()"); //check that we can remove the old index before starting import File index_dir = new File(getCollectionIndex(), "temp.txt"); index_dir = index_dir.getParentFile(); if(index_dir.exists()) { DebugStream.println("Old Index = " + index_dir.getAbsolutePath()+", testing for deletability"); if (!canDelete(index_dir)) { // tell the user JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Delete_Index"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); // tell the gui manager // a message for the building log GShellEvent event = new GShellEvent(this, 0, GShell.IMPORT, Dictionary.get("CollectionManager.Cannot_Delete_Index_Log"), GShell.ERROR); Gatherer.g_man.create_pane.message(event); event = new GShellEvent(this, 0, GShell.IMPORT, "", GShell.ERROR); Gatherer.g_man.create_pane.processComplete(event); importing = false; return; } } String collect_dir = getCollectDirectory(); String args[]; String lang = Configuration.getLanguage(); if((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) { args = new String[8]; args[0] = Configuration.perl_path; args[1] = "-S"; args[2] = Configuration.getScriptPath() + "import.pl"; args[3] = "-gli"; args[4] = "-language"; args[5] = lang; args[6] = "-collectdir"; args[7] = collect_dir; } else { args = new String[6]; args[0] = Configuration.getScriptPath() + "import.pl"; args[1] = "-gli"; args[2] = "-language"; args[3] = lang; args[4] = "-collectdir"; args[5] = collect_dir; } collect_dir = null; args = ArrayTools.add(args, collection.build_options.getImportValues()); args = ArrayTools.add(args, collection.getName()); GShell shell = new GShell(args, GShell.IMPORT, BUILDING, this, import_monitor, GShell.GSHELL_IMPORT); shell.addGShellListener(Gatherer.g_man.create_pane); shell.start(); DebugStream.println("CollectionManager.importCollection().return"); importing = false; } public void importMetadataSet(MetadataSet external_metadata_set) { // Copy the .mds file into the collection's "metadata" folder... File external_metadata_set_file = external_metadata_set.getMetadataSetFile(); // ...but not if it is the redundant "hidden.mds" file if (external_metadata_set_file.getName().equals("hidden.mds")) { return; } // ...and only if it doesn't already exist File metadata_set_file = new File(getCollectionMetadata(), external_metadata_set_file.getName()); if (!metadata_set_file.exists()) { try { Gatherer.f_man.getQueue().copyFile(external_metadata_set_file, metadata_set_file, null); } catch (Exception ex) { ex.printStackTrace(); } // Load it into the MetadataSetManager MetadataSetManager.loadMetadataSet(metadata_set_file); } } /** 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. * @return true if the gli is currently importing */ public boolean isImporting() { return importing; } /** Attempts to load the given collection. Currently uses simple serialization of the collection class. * @param location The path to the collection as a String. * @see org.greenstone.gatherer.Configuration * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.collection.Collection * @see org.greenstone.gatherer.util.Utility */ public boolean loadCollection(String location) { DebugStream.println("Loading collection " + location + "..."); boolean non_gatherer_collection = false; // Check we have actually been given a .col file. if (!location.endsWith(".col")) { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Not_Col_File", location), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); DebugStream.println("CollectionManager.loadCollection: Haven't been given a .col file."); return false; } // Check that there is the collection configuration file available File collection_file = new File(location); // Ensure that the directory exists. File collection_directory = collection_file.getParentFile(); if (!collection_directory.exists()) { // we cant open this collection_directory = null; return false; } File collection_config_file = new File(collection_directory, Utility.CONFIG_FILE); if (!collection_config_file.exists()) { DebugStream.println("CollectionManager.loadCollection: No config file"); collection_directory = null; collection_config_file = null; return false; } // Special case of a user trying to open an old greenstone collection. File collection_metadata_directory = new File(collection_directory, Utility.META_DIR); if (!collection_metadata_directory.exists()) { DebugStream.println("Loading non-gatherer collection..."); non_gatherer_collection = true; } // Now determine if a lock already exists on this collection. String name = collection_directory.getName(); File lock_file = new File(collection_file.getParentFile(), LOCK_FILE); if (lock_file.exists()) { LockFileDialog dialog = new LockFileDialog(Gatherer.g_man, name, lock_file); int choice = dialog.getChoice(); dialog.dispose(); dialog = null; if (choice != LockFileDialog.YES_OPTION) { // user has cancelled lock_file = null; collection_directory = null; collection_config_file = null; return false; } lock_file.delete(); } boolean result = false; try { // Create a lock file. createLockFile(lock_file); // This lock file may not have been created so check if(!lock_file.canWrite()) { // The lock file cannot be written to. Most likely cause incorrect file permissions. System.err.println("Cannot write lock file!"); String args[] = new String[2]; args[0] = location; args[1] = Dictionary.get("FileActions.Write_Not_Permitted_Title"); JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open_With_Reason", args), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); args = null; return false; } // Open the collection file this.collection = new Collection(collection_file); if (collection.error) { collection = null; // Remove lock file if (lock_file.exists()) { lock_file.delete(); } throw(new Exception(Dictionary.get("CollectionManager.Missing_Config"))); // this error message does not agree with the error } MetadataSetManager.clearMetadataSets(); MetadataSetManager.loadMetadataSets(collection_metadata_directory); ProfileXMLFileManager.loadProfileXMLFile(collection_metadata_directory); // If this is a non-GLI (legacy) collection, ask the user to choose some metadata sets if (non_gatherer_collection) { if (!addSomeMetadataSets(collection_directory)) { lock_file = null; collection_directory = null; closeCollection(); return false; } // Recurse the import folder tree, backing up the metadata.xml files before they are edited LegacyCollectionImporter.backupMetadataXMLFiles(collection_directory); } // Read through the metadata.xml files in the import directory, building up the metadata value trees File collection_import_directory = new File(collection_directory, Utility.IMPORT_DIR); MetadataXMLFileManager.clearMetadataXMLFiles(); MetadataXMLFileManager.loadMetadataXMLFiles(collection_import_directory); // Read through the doc.xml files in the archives directory File collection_archives_directory = new File(getCollectionArchives()); DocXMLFileManager.clearDocXMLFiles(); DocXMLFileManager.loadDocXMLFiles(collection_archives_directory); collection.cdm = new CollectionDesignManager(collection_config_file); if (non_gatherer_collection) { // Change the classifiers to use the namespaced element names LegacyCollectionImporter.updateClassifiers(collection.cdm); } // Tell everyone that it worked. DebugStream.println(Dictionary.get("CollectionManager.Loading_Successful", name)); // We're done. Let everyone know. Gatherer.refresh(Gatherer.COLLECTION_OPENED); result = true; } catch (Exception error) { // There is obviously no existing collection present. DebugStream.printStackTrace(error); if(error.getMessage() != null) { String[] args = new String[2]; args[0] = location; args[1] = error.getMessage(); JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open_With_Reason", args), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open", location), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); } } lock_file = null; collection_directory = null; collection_config_file = null; return result; } public void makeCollection(String description, String email, String name, String title) { // Encode the description so it is safe to write to shell if(Utility.isWindows()) { description = Codec.transform(description, Codec.TEXT_TO_SHELL_WINDOWS); } else { description = Codec.transform(description, Codec.TEXT_TO_SHELL_UNIX); } String collect_dir = getCollectDirectory(); // Run the mkcol command. String command[]; if((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) { if(description == null || title == null) { command = new String[8]; command[0] = Configuration.perl_path; command[1] = "-S"; command[2] = Configuration.getScriptPath() + "mkcol.pl"; command[3] = "-collectdir"; command[4] = collect_dir; command[5] = "-win31compat"; command[6] = (Gatherer.isGsdlRemote) ? "false" : "true"; command[7] = name; } // Users are no longer required to supply an email else if(email == null) { command = new String[12]; command[0] = Configuration.perl_path; command[1] = "-S"; command[2] = Configuration.getScriptPath() + "mkcol.pl"; command[3] = "-collectdir"; command[4] = collect_dir; command[5] = "-win31compat"; command[6] = (Gatherer.isGsdlRemote) ? "false" : "true"; command[7] = "-title"; command[8] = title; command[9] = "-about"; command[10] = description; command[11] = name; } else { command = new String[14]; command[0] = Configuration.perl_path; command[1] = "-S"; command[2] = Configuration.getScriptPath() + "mkcol.pl"; command[3] = "-collectdir"; command[4] = collect_dir; command[5] = "-win31compat"; command[6] = (Gatherer.isGsdlRemote) ? "false" : "true"; command[7] = "-title"; command[8] = title; command[9] = "-creator"; command[10] = email; command[11] = "-about"; command[12] = description; command[13] = name; } } else { if(description == null || title == null) { command = new String[6]; command[0] = "mkcol.pl"; command[1] = "-collectdir"; command[2] = collect_dir; command[3] = "-win31compat"; command[4] = (Gatherer.isGsdlRemote) ? "false" : "true"; command[5] = name; } else if(email == null) { command = new String[10]; command[0] = "mkcol.pl"; command[1] = "-collectdir"; command[2] = collect_dir; command[3] = "-win31compat"; command[4] = (Gatherer.isGsdlRemote) ? "false" : "true"; command[5] = "-title"; command[6] = title; command[7] = "-about"; command[8] = description; command[9] = name; } else { command = new String[12]; command[0] = "mkcol.pl"; command[1] = "-collectdir"; command[2] = collect_dir; command[3] = "-win31compat"; command[4] = (Gatherer.isGsdlRemote) ? "false" : "true"; command[5] = "-title"; command[6] = title; command[7] = "-creator"; command[8] = email; command[9] = "-about"; command[10] = description; command[11] = name; } } GShell process = new GShell(command, GShell.NEW, COLLECT, this, null, GShell.GSHELL_NEW); process.run(); // Don't bother threading this... yet } /** 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. * @param event A GShellEvent which contains a the message. */ public synchronized void message(GShellEvent event) { } /** This call is fired whenever a process within a GShell created by this class begins. * @param event A GShellEvent containing information about the GShell process. * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.gui.GUIManager * @see org.greenstone.gatherer.shell.GShell */ public synchronized void processBegun(GShellEvent event) { DebugStream.println("CollectionManager.processBegun(" + event.getType() + ")"); ///ystem.err.println("ProcessBegun " + event.getType()); // If this is one of the types where we wish to lock user control Gatherer.g_man.lockCollection((event.getType() == GShell.IMPORT), true); } /** This call is fired whenever a process within a GShell created by this class ends. * @param event A GShellEvent containing information about the GShell process. * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.gui.GUIManager * @see org.greenstone.gatherer.shell.GShell */ public synchronized void processComplete(GShellEvent event) { DebugStream.println("CollectionManager.processComplete(" + event.getType() + ")"); Gatherer.g_man.lockCollection((event.getType() == GShell.IMPORT), false); ///ystem.err.println("Recieved process complete event - " + event); // If we were running an import, now run a build. if(event.getType() == GShell.IMPORT && event.getStatus() == GShell.OK) { // Finish import. collection.setImported(true); buildCollection(); } // If we were running a build, now is when we move files across. else if(event.getType() == GShell.BUILD && event.getStatus() == GShell.OK) { if(installCollection()) { // If we have a local library running then ask it to add our newly create collection if (LocalLibraryServer.isRunning() == true) { LocalLibraryServer.addCollection(collection.getName()); } else if (Gatherer.GS3) { convertToGS3Collection(); Gatherer.configGS3Server(Configuration.site_name, ServletConfiguration.ADD_COMMAND + collection.getName()); } // Fire a collection changed first to update the preview etc buttons Gatherer.refresh(Gatherer.COLLECTION_REBUILT); // Now display a message dialog saying its all built WarningDialog collection_built_warning_dialog = new WarningDialog("warning.CollectionBuilt", null, false); collection_built_warning_dialog.setMessageOnly(true); // Not a warning collection_built_warning_dialog.display(); collection_built_warning_dialog.dispose(); collection_built_warning_dialog = null; } else { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Preview_Ready_Failed"), Dictionary.get("CollectionManager.Preview_Ready_Title"), JOptionPane.ERROR_MESSAGE); Gatherer.refresh(Gatherer.COLLECTION_REBUILT); } } else if(event.getStatus() == GShell.ERROR || event.getStatus() == GShell.CANCELLED) { DebugStream.println("There was an error in the gshell:"+ event.getMessage()); if (event.getType() == GShell.NEW) { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Create_Collection"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Preview_Ready_Failed"), Dictionary.get("CollectionManager.Preview_Ready_Title"), JOptionPane.ERROR_MESSAGE); Gatherer.refresh(Gatherer.COLLECTION_REBUILT); } 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. } } /** Determine if the manager is ready for actions apon its collection. * @return A boolean which is true to indicate a collection has been loaded and thus the collection is ready for editing, false otherwise. */ static public synchronized boolean ready() { if(collection != null) { return true; } else { return false; } } /** This method associates the collection build monitor with the build monitor created in CreatePane. * @param monitor A GShellProgressMonitor which we will use as the build monitor. */ public void registerBuildMonitor(GShellProgressMonitor monitor) { build_monitor = monitor; } /** This method associates the collection import monitor with the import monitor created in CreatePane. * @param monitor A GShellProgressMonitor which we will use as the import monitor. */ public void registerImportMonitor(GShellProgressMonitor monitor) { import_monitor = monitor; } public void removeMetadataSet(MetadataSet metadata_set) { System.err.println("Removing metadata set..."); // Delete the .mds file from the collection's "metadata" folder... File metadata_set_file = metadata_set.getMetadataSetFile(); // ...but not if it is the "ex.mds" file if (metadata_set_file.getName().equals("ex.mds")) { return; } // ...and only if it exists if (metadata_set_file.exists()) { metadata_set_file.delete(); // Unload it from the MetadataSetManager MetadataSetManager.unloadMetadataSet(metadata_set); } } /** Used to check whether all open collections have a 'saved' state. * @return A boolean which is true if the collection has been saved. * @see org.greenstone.gatherer.collection.Collection */ public boolean saved() { boolean result = true; if(collection != null) { result = collection.getSaved(); } return result; } /** Saves the currently loaded collection. */ public void saveCollection() { DebugStream.println("Saving collection " + collection.getName() + "..."); // Change cursor to hourglass Gatherer.g_man.wait(true); // Create a backup of the collection file, just in case anything goes wrong File collection_file = new File(Gatherer.c_man.getCollectionFilename()); if (collection_file.exists()) { File collection_file_backup = new File(collection_file.getAbsolutePath() + "~"); if (!collection_file.renameTo(collection_file_backup)) { DebugStream.println("Error in CollectionManager.saveCollection(): could not create backup file."); } collection_file_backup.deleteOnExit(); } // Write out the collection file collection.save(); // Write out the collection configuration file Gatherer.g_man.design_pane.saveConfiguration(); // Write hfiles for the loaded metadata elements into the collection "etc" directory MetadataSetManager.writeHierarchyFiles(new File(Gatherer.c_man.getCollectionEtc())); // Change cursor back to normal Gatherer.g_man.wait(false); } /** 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] */ private boolean addSomeMetadataSets(File collection_dir) { ExternalCollectionPrompt external_prompt = new ExternalCollectionPrompt(); int meta_choice = external_prompt.getMetadataChoice(); boolean cancelled = external_prompt.isCancelled(); if (cancelled) { return false; } // now we reuse the newcoll metadata prompt for the user to select metadata sets NewCollectionMetadataPrompt ncm_prompt = new NewCollectionMetadataPrompt(true); if (ncm_prompt.isCancelled()) { return false; } ArrayList metadata_sets = ncm_prompt.getSets(); // Import default metadata sets if any. for(int i = 0; metadata_sets != null && i < metadata_sets.size(); i++) { importMetadataSet((MetadataSet) metadata_sets.get(i)); } // Always import the extracted metadata set File extracted_metadata_set_file = new File(Utility.METADATA_DIR + Utility.EXTRACTED_METADATA_NAMESPACE + StaticStrings.METADATA_SET_EXTENSION); importMetadataSet(new MetadataSet(extracted_metadata_set_file)); return true; } // used as arg in the perl scripts private String getCollectDirectory() { String collect_dir; if (Gatherer.GS3) { collect_dir = Utility.getCollectDir(Configuration.gsdl3_path, Configuration.site_name); } else { collect_dir = Utility.getCollectDir(Configuration.gsdl_path); } // Remove erroneous file windows file separator as it causes problems when running import.pl if(collect_dir.length() > 2 && collect_dir.endsWith("\\")) { collect_dir = collect_dir.substring(0, collect_dir.length() - 1); } return collect_dir; } /** Install collection by moving its files from building to index after a successful build. * @see org.greenstone.gatherer.Gatherer * @see org.greenstone.gatherer.util.Utility */ private boolean installCollection() { DebugStream.println("Build complete. Moving files."); try { // Ensure that the local library has released this collection so we can delete the index directory if (LocalLibraryServer.isRunning() == true) { LocalLibraryServer.releaseCollection(collection.getName()); } File index_dir = new File(getCollectionIndex()); DebugStream.println("Index = " + index_dir.getAbsolutePath()); File building_dir = new File(getCollectionBuild()); DebugStream.println("Building = " + building_dir.getAbsolutePath()); // Get the build mode from the build options String build_mode = collection.build_options.getBuildValue("mode"); // Special case for build mode "all": replace index dir with building dir if (build_mode == null || build_mode.equals(Dictionary.get("CreatePane.Mode_All"))) { // Remove the old index directory if (index_dir.exists()) { Utility.delete(index_dir); // Wait for a couple of seconds, just for luck wait(2000); // Check the delete worked if (index_dir.exists()) { throw new Exception("Index directory could not be removed."); } } // Move the building directory to become the new index directory if (building_dir.renameTo(index_dir) == false) { throw new Exception("Build directory could not be moved."); } } // Otherwise copy everything in the building dir into the index dir else { moveContentsInto(building_dir, index_dir); } } catch (Exception exception) { JOptionPane.showMessageDialog(Gatherer.g_man, "Exception detected during collection install.\nMost likely caused by Windows or Local Library holding locks on files:\n" + exception.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); return false; } return true; } /** Moves all the files in one directory into another, overwriting existing files */ private void moveContentsInto(File source_directory, File target_directory) { File[] source_files = source_directory.listFiles(); for (int i = 0; i < source_files.length; i++) { File source_file = source_files[i]; File target_file = new File(target_directory, source_file.getName()); if (source_file.isDirectory()) { moveContentsInto(source_file, target_file); source_file.delete(); } else { if (target_file.exists()) { target_file.delete(); } source_file.renameTo(target_file); } } } private void updateCollectionCFG(File base_cfg, File new_cfg, String description, String email, String title) { boolean first_name = true; boolean first_extra = true; String collection_path = (base_cfg.getParentFile().getParentFile()).getAbsolutePath(); // 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. try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(base_cfg), "UTF-8")); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new_cfg), "UTF-8")); String command = null; while((command = in.readLine()) != null) { if (command.length()==0) { // output a new line out.newLine(); continue; } // We have to test the end of command for the special character '\'. If found, remove it and append the next line, then repeat. while(command.trim().endsWith("\\")) { command = command.substring(0, command.lastIndexOf("\\")); String next_line = in.readLine(); if(next_line != null) { command = command + next_line; } } // commands can extend over more than one line so use the CommandTokenizer which takes care of that CommandTokenizer tokenizer = new CommandTokenizer(command, in, false); String command_type_str = tokenizer.nextToken().toLowerCase(); if (command_type_str.equals(StaticStrings.COLLECTIONMETADATA_STR)) { // read the whole thing in, but for collectionname, collectionextra, iconcollection, iconcollectionsmall we will ignore them StringBuffer new_command = new StringBuffer(command_type_str); String meta_name = tokenizer.nextToken(); new_command.append(' '); new_command.append(meta_name); while (tokenizer.hasMoreTokens()) { new_command.append(' '); new_command.append(tokenizer.nextToken()); } 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)) { // dont save } else { write(out, new_command.toString()); } new_command = null; continue; } // if collectionmeta if(command_type_str.equals(Utility.CFG_CLASSIFY)) { StringBuffer text = new StringBuffer(command_type_str); // Read in the classifier command watching for hfile, metadata and sort arguments. String buttonname = null; String hfile = null; String new_metadata = null; String old_metadata = null; while(tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if(token.equals(Utility.CFG_CLASSIFY_HFILE)) { if(tokenizer.hasMoreTokens()) { text.append(" "); text.append(token); token = tokenizer.nextToken(); hfile = token; } } else if(token.equals(Utility.CFG_CLASSIFY_METADATA)) { if(tokenizer.hasMoreTokens()) { text.append(" "); text.append(token); String temp_metadata = tokenizer.nextToken(); String replacement = ProfileXMLFileManager.getMetadataElementFor(temp_metadata); if (replacement != null && !replacement.equals("")) { token = replacement; old_metadata = temp_metadata; new_metadata = replacement; } else { token = temp_metadata; } temp_metadata = null; replacement = null; } } else if(token.equals(Utility.CFG_CLASSIFY_SORT)) { if(tokenizer.hasMoreTokens()) { text.append(" "); text.append(token); String temp_metadata = tokenizer.nextToken(); String replacement = ProfileXMLFileManager.getMetadataElementFor(temp_metadata); if (replacement != null && !replacement.equals("")) { token = replacement; } else { token = temp_metadata; } temp_metadata = null; replacement = null; } } else if(token.equals(Utility.CFG_CLASSIFY_BUTTONNAME)) { buttonname = token; } text.append(' '); text.append(token); token = null; } // 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)! if(old_metadata != null && new_metadata != null && buttonname == null) { text.append(' '); text.append(Utility.CFG_CLASSIFY_BUTTONNAME); text.append(' '); text.append(old_metadata); } command = text.toString(); // Replace the hfile if we found it if(hfile != null && new_metadata != null) { command = command.replaceAll(hfile, new_metadata + ".txt"); } buttonname = null; hfile = null; new_metadata = null; old_metadata = null; write(out, command); } else { // the rest of the commands just want a string - we read in all the tokens from the tokeniser and get rid of it. StringBuffer new_command = new StringBuffer(command_type_str); while (tokenizer.hasMoreTokens()) { new_command.append(' '); new_command.append(tokenizer.nextToken()); } command = new_command.toString(); // There is still one special case, that of the format command. In such a command we have to search for [] to ensure we don't change parts of the format which have nothing to do with the metadata elements. // we really want to build up the whole command here boolean format_command = command_type_str.equals(Utility.CFG_FORMAT); HashMap metadata_mapping = ProfileXMLFileManager.getMetadataMapping(); if (metadata_mapping != null) { Iterator keys = metadata_mapping.keySet().iterator(); while (keys.hasNext()) { String target = (String) keys.next(); String replacement = (String) metadata_mapping.get(target); if (replacement != null && !replacement.equals("")) { if (format_command) { target = "\\[" + target + "\\]"; replacement = "{Or}{[" + replacement + "]," + target + "}"; } command = command.replaceAll(target, replacement); } } } write(out, command); } tokenizer = null; } in.close(); in = null; out.flush(); out.close(); out = null; } catch(Exception error) { DebugStream.printStackTrace(error); } // All done, I hope. } private void write(BufferedWriter out, String message) throws Exception { out.write(message, 0, message.length()); out.newLine(); } /** The CollectionManager class is getting too confusing by half so I'll implement this TreeModelListener in a private class to make responsibility clear. */ private class FMTreeModelListener implements TreeModelListener { /** 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. * @param event A TreeModelEvent encompassing all the information about the event which has changed the tree. */ public void treeNodesChanged(TreeModelEvent event) { if(collection != null) { collection.setSaved(false); } } /** 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. * @param event A TreeModelEvent encompassing all the information about the event which has changed the tree. */ public void treeNodesInserted(TreeModelEvent event) { if(collection != null) { collection.setSaved(false); } } /** 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. * @param event A TreeModelEvent encompassing all the information about the event which has changed the tree. */ public void treeNodesRemoved(TreeModelEvent event) { if(collection != null) { collection.setSaved(false); } } /** 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. * @param event A TreeModelEvent encompassing all the information about the event which has changed the tree. */ public void treeStructureChanged(TreeModelEvent event) { if(collection != null) { collection.setSaved(false); } } } }