/** *######################################################################### * * 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.LocalGreenstone; 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.greenstone.Classifiers; import org.greenstone.gatherer.greenstone.Plugins; import org.greenstone.gatherer.gui.LockFileDialog; import org.greenstone.gatherer.gui.ModalProgressPopup; import org.greenstone.gatherer.gui.WarningDialog; import org.greenstone.gatherer.metadata.DocXMLFileManager; import org.greenstone.gatherer.metadata.MetadataChangedListener; 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.remote.RemoteGreenstoneServer; 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.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, MetadataChangedListener { /** 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 tree (used in both Gather and Enrich panes). */ static private CollectionTree collection_tree = null; /** The collection tree model. */ private CollectionTreeModel collection_tree_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; /** Whether we have downloaded the collection configurations in this session, when using a remote Greenstone. */ static public boolean downloaded_collection_configurations = false; /** 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; MetadataXMLFileManager.addMetadataChangedListener(this); // If using a remote Greenstone server, delete the local collect directory because it will be out of date if (Gatherer.isGsdlRemote) { System.err.println("Deleting user's local collect directory..."); Utility.delete(new File(Gatherer.getCollectDirectoryPath())); System.err.println("Done."); new File(Gatherer.getCollectDirectoryPath()).mkdirs(); } } 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 */ public void buildCollection(boolean incremental_build) { DebugStream.println("In CollectionManager.buildCollection(), incremental_build: " + incremental_build); DebugStream.println("Is event dispatch thread: " + SwingUtilities.isEventDispatchThread()); building = true; // Generate the buildcol.pl command ArrayList command_parts_list = new ArrayList(); if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) { command_parts_list.add(Configuration.perl_path); command_parts_list.add("-S"); } command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "buildcol.pl"); command_parts_list.add("-gli"); command_parts_list.add("-language"); command_parts_list.add(Configuration.getLanguage()); command_parts_list.add("-collectdir"); command_parts_list.add(getCollectDirectory()); // If the user hasn't manually specified "-keepold" or "-removeold" then pick one based on incremental_build if (!collection.build_options.getValueEnabled("keepold") && !collection.build_options.getValueEnabled("removeold")) { command_parts_list.add(incremental_build ? "-keepold" : "-removeold"); } String[] build_options = collection.build_options.getValues(); for (int i = 0; i < build_options.length; i++) { command_parts_list.add(build_options[i]); } command_parts_list.add(collection.getName()); // Run the buildcol.pl command String[] command_parts = (String[]) command_parts_list.toArray(new String[0]); GShell shell = new GShell(command_parts, GShell.BUILD, BUILDING, this, build_monitor, GShell.GSHELL_BUILD); shell.addGShellListener(Gatherer.g_man.create_pane); shell.addGShellListener(Gatherer.g_man.format_pane); shell.start(); } /** 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(getCollectionIndexDirectoryPath() + "build.cfg"); 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; } static public String getCollectionDirectoryPath() { return Gatherer.getCollectDirectoryPath() + collection.getName() + File.separator; } /** Constructs the absolute filename of the collection's directory, which should resemble "$GSDLHOME/collect/<col_name>" * @return A String containing the directory name. */ static public String getCollectionDirectoryPath(String collection_name) { return Gatherer.getCollectDirectoryPath() + collection_name + File.separator; } /** Constructs the absolute filename of the collection's .col file, which should resemble "$GSDLHOME/collect/<col_name>/<col_name>.col" * @return A String containing the filename. */ public String getCollectionFilePath() { return getCollectionDirectoryPath() + collection.getName() + ".col"; } /** Constructs the absolute filename of the collection's archives directory, which should resemble "$GSDLHOME/collect/<col_name>/archives/" * @return A String containing the filename. */ public String getCollectionArchivesDirectoryPath() { return getCollectionDirectoryPath() + "archives" + File.separator; } /** Constructs the absolute filename of the collection's building directory, which should resemble "$GSDLHOME/collect/<col_name>/building/" * @return A String containing the filename. */ public String getCollectionBuildingDirectoryPath() { return getCollectionDirectoryPath() + "building" + File.separator; } /** Constructs the absolute filename of the collection's collect.cfg file, which should resemble "$GSDLHOME/collect/<col_name>/etc/collect.cfg" * @return A String containing the filename. */ public String getCollectionConfigFilePath() { return getCollectionEtcDirectoryPath() + "collect.cfg"; } /** Constructs the absolute filename of the collection's etc directory, which should resemble "$GSDLHOME/collect/<col_name>/etc/" * @return A String containing the filename. */ public String getCollectionEtcDirectoryPath() { return getCollectionDirectoryPath() + "etc" + File.separator; } /** Constructs the absolute filename of the collection's images directory, which should resemble "$GSDLHOME/collect/<col_name>/images/" * @return A String containing the filename. */ public String getCollectionImagesDirectoryPath() { return getCollectionDirectoryPath() + "images" + File.separator; } /** Constructs the absolute filename of the collection's import directory, which should resemble "$GSDLHOME/collect/<col_name>/import/" * @return A String containing the filename. */ public String getCollectionImportDirectoryPath() { return getCollectionDirectoryPath() + "import" + File.separator; } /** Constructs the absolute filename of the collection's index directory, which should resemble "$GSDLHOME/collect/<col_name>/index/" * @return A String containing the filename. */ public String getCollectionIndexDirectoryPath() { return getCollectionDirectoryPath() + "index" + File.separator; } /** Constructs the absolute filename of the collection's log directory, which should resemble "$GSDLHOME/collect/<col_name>/log/" * @return A String containing the filename. */ public String getCollectionLogDirectoryPath() { return getCollectionDirectoryPath() + "log" + File.separator; } /** Constructs the absolute filename of the collection's metadata directory, which should resemble "$GSDLHOME/collect/<col_name>/metadata/" * @return A String containing the filename. */ public String getCollectionMetadataDirectoryPath() { return getCollectionDirectoryPath() + "metadata" + File.separator; } /** Constructs the absolute filename of the collection's metadata directory, which should resemble "$GSDLHOME/collect/<col_name>/metadata/" * @return A String containing the filename. */ public String getCollectionPluginsDirectoryPath() { return getCollectionDirectoryPath() + "perllib" + File.separator + "plugins" + File.separator; } /** Constructs the absolute filename of the collection's metadata directory, which should resemble "$GSDLHOME/collect/<col_name>/metadata/" * @return A String containing the filename. */ public String getCollectionClassifiersDirectoryPath() { return getCollectionDirectoryPath() + "perllib" + File.separator + "classify" + File.separator; } public CollectionTree getCollectionTree() { if (collection_tree == null) { collection_tree = new CollectionTree(collection_tree_model, true); } return collection_tree; } /** Retrieve the tree model associated with the current collection. */ public CollectionTreeModel getCollectionTreeModel() { if (collection_tree_model == null && collection != null) { // Use the import directory to generate a new CollectionTreeModel collection_tree_model = new CollectionTreeModel(new CollectionTreeNode(new File(getCollectionImportDirectoryPath()))); // Ensure that the manager is a change listener for the tree. if (fm_tree_model_listener == null) { fm_tree_model_listener = new FMTreeModelListener(); } collection_tree_model.addTreeModelListener(fm_tree_model_listener); } return collection_tree_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()"); DebugStream.println("Is event dispatch thread: " + SwingUtilities.isEventDispatchThread()); //check that we can remove the old index before starting import File index_dir = new File(getCollectionIndexDirectoryPath()); 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; } } // Generate the import.pl command ArrayList command_parts_list = new ArrayList(); if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) { command_parts_list.add(Configuration.perl_path); command_parts_list.add("-S"); } command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "import.pl"); command_parts_list.add("-gli"); command_parts_list.add("-language"); command_parts_list.add(Configuration.getLanguage()); command_parts_list.add("-collectdir"); command_parts_list.add(getCollectDirectory()); String[] import_options = collection.import_options.getValues(); for (int i = 0; i < import_options.length; i++) { command_parts_list.add(import_options[i]); } command_parts_list.add(collection.getName()); // Run the import.pl command String[] command_parts = (String[]) command_parts_list.toArray(new String[0]); GShell shell = new GShell(command_parts, GShell.IMPORT, BUILDING, this, import_monitor, GShell.GSHELL_IMPORT); shell.addGShellListener(Gatherer.g_man.create_pane); shell.addGShellListener(Gatherer.g_man.format_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(getCollectionMetadataDirectoryPath(), external_metadata_set_file.getName()); if (!metadata_set_file.exists()) { try { Gatherer.f_man.getQueue().copyFile(external_metadata_set_file, metadata_set_file, false); // If we're using a remote Greenstone server, upload the metadata file if (Gatherer.isGsdlRemote) { RemoteGreenstoneServer.uploadCollectionFile(collection.getName(), metadata_set_file); } } catch (Exception exception) { DebugStream.printStackTrace(exception); } // 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; } public void loadCollection(String collection_file_path) { // Display a modal progress popup to indicate that the collection is being loaded ModalProgressPopup load_collection_progress_popup = new ModalProgressPopup(Dictionary.get("CollectionManager.Loading_Collection"), Dictionary.get("CollectionManager.Loading_Collection_Please_Wait")); load_collection_progress_popup.display(); // Load the collection on a separate thread so the progress bar updates correctly (new LoadCollectionTask(collection_file_path, load_collection_progress_popup)).start(); } private class LoadCollectionTask extends Thread { private String collection_file_path = null; private ModalProgressPopup load_collection_progress_popup = null; public LoadCollectionTask(String collection_file_path, ModalProgressPopup load_collection_progress_popup) { this.collection_file_path = collection_file_path; this.load_collection_progress_popup = load_collection_progress_popup; } public void run() { loadCollectionInternal(collection_file_path); load_collection_progress_popup.close(); } } /** 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 */ private void loadCollectionInternal(String location) { DebugStream.println("Loading collection " + location + "..."); if (Gatherer.isGsdlRemote) { String collection_name = location.substring(location.lastIndexOf(File.separator) + 1, location.length() - ".col".length()); if (RemoteGreenstoneServer.downloadCollection(collection_name).equals("")) { return; } } // 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; } // Check that the collection configuration file is available File collection_file = new File(location); // Ensure that the directory exists File collection_directory = collection_file.getParentFile(); if (collection_directory == null || !collection_directory.exists()) { // We can't open this System.err.println("CollectionManager.loadCollection: No collection directory."); return; } File collection_config_file = new File(collection_directory, Utility.CONFIG_FILE); if (!collection_config_file.exists()) { System.err.println("CollectionManager.loadCollection: No config file."); collection_directory = null; collection_config_file = null; return; } // Ensure that an import directory exists for this collection File collection_import_directory = new File(collection_directory, "import"); if (!collection_import_directory.exists()) { collection_import_directory.mkdir(); } // Special case of a user trying to open an old greenstone collection. boolean non_gli_collection = false; File collection_metadata_directory = new File(collection_directory, "metadata"); if (!collection_metadata_directory.exists()) { DebugStream.println("Loading non-gatherer collection..."); // Show a warning message in case user wants to quit now non_gli_collection = true; WarningDialog legacy_dialog = new WarningDialog("warning.LegacyCollection", Dictionary.get("LegacyCollection.Title"), Dictionary.get("LegacyCollection.Message"), null, true); if (legacy_dialog.display()==JOptionPane.CANCEL_OPTION) { legacy_dialog.dispose(); collection_directory = null; collection_config_file = null; return; } legacy_dialog.dispose(); } // Now determine if a lock already exists on this collection. String collection_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, collection_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; } lock_file.delete(); } 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; } // 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); // Make sure we always have the extracted metadata set addRequiredMetadataSets(); ProfileXMLFileManager.loadProfileXMLFile(collection_metadata_directory); // If this is a non-GLI (legacy) collection, load the default metadata sets if (non_gli_collection) { addDefaultMetadataSets(); // 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 MetadataXMLFileManager.clearMetadataXMLFiles(); MetadataXMLFileManager.loadMetadataXMLFiles(collection_import_directory); // Read through the doc.xml files in the archives directory File collection_archives_directory = new File(getCollectionArchivesDirectoryPath()); DocXMLFileManager.clearDocXMLFiles(); DocXMLFileManager.loadDocXMLFiles(collection_archives_directory); // Get a list of the collection specific classifiers and plugins Classifiers.loadClassifiersList(collection_name); Plugins.loadPluginsList(collection_name); collection.cdm = new CollectionDesignManager(collection_config_file); if (non_gli_collection) { // Change the classifiers to use the namespaced element names LegacyCollectionImporter.updateClassifiers(collection.cdm); } // We're done. Let everyone know. DebugStream.println(Dictionary.get("CollectionManager.Loading_Successful", collection_name)); Gatherer.refresh(Gatherer.COLLECTION_OPENED); } 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; } private void makeCollection(String name, String email) { // Generate the mkcol.pl command ArrayList command_parts_list = new ArrayList(); if (Utility.isWindows() && (!Gatherer.isGsdlRemote)) { command_parts_list.add(Configuration.perl_path); command_parts_list.add("-S"); } command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "mkcol.pl"); command_parts_list.add("-collectdir"); command_parts_list.add(getCollectDirectory()); command_parts_list.add("-win31compat"); command_parts_list.add((Gatherer.isGsdlRemote) ? "false" : "true"); if (email != null && !email.equals("")) { command_parts_list.add("-creator"); command_parts_list.add(email); } command_parts_list.add(name); // Run the mkcol.pl command String[] command_parts = (String[]) command_parts_list.toArray(new String[0]); GShell process = new GShell(command_parts, 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) { } public void metadataChanged(CollectionTreeNode[] file_nodes) { if (collection != null) { collection.setMetadataChanged(true); } } public void openCollectionFromLastTime() { // If there was an open collection last session, reopen it if (Gatherer.open_collection_file_path != null && !Gatherer.isGsdlRemote) { // If we're using a remote Greenstone server we must download the collection configurations first // if (Gatherer.isGsdlRemote && !CollectionManager.downloaded_collection_configurations) { // if (RemoteGreenstoneServer.downloadCollectionConfigurations().equals("")) { // Something went wrong downloading the collection configurations // return; // } // CollectionManager.downloaded_collection_configurations = true; // } // Load the collection now loadCollection(Gatherer.open_collection_file_path); } } /** 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) { //ystem.err.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); collection.setFilesChanged(false); collection.setMetadataChanged(false); buildCollection(false); } // 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", Dictionary.get("CollectionBuilt.Title"), Dictionary.get("CollectionBuilt.Message"), 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; //Set nothing as needing rebuilding, as a build has just finished :-) CollectionDesignManager.resetRebuildTypeRequired(); } 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); DebugStream.println("Status is ok but !installCollection()"); } } else if (event.getStatus() == GShell.CANCELLED) { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Build_Cancelled"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); Gatherer.g_man.repaint(); } else if (event.getStatus() == GShell.ERROR) { 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 removeCollectionContentsChangedListener(CollectionContentsChangedListener listener) { collection_contents_changed_listeners.remove(listener); } public void removeMetadataSet(MetadataSet metadata_set) { DebugStream.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); // If we're using a remote Greenstone server, delete the metadata file on the server if (Gatherer.isGsdlRemote) { RemoteGreenstoneServer.deleteCollectionFile(collection.getName(), metadata_set_file); } } } /** 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() { if (collection == null) return; 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(getCollectionFilePath()); 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 collection.cdm.save(); // 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 void addDefaultMetadataSets() { // Add dublin core which is the default metadata set. The user // can change this later File dc_file = new File(Gatherer.getGLIMetadataDirectoryPath()+"dublin.mds"); if (dc_file.exists()) { importMetadataSet(new MetadataSet(dc_file)); } } private void addRequiredMetadataSets() { // Always import the extracted metadata set File extracted_metadata_set_file = new File(Gatherer.getGLIMetadataDirectoryPath() + MetadataSetManager.EXTRACTED_METADATA_NAMESPACE + StaticStrings.METADATA_SET_EXTENSION); importMetadataSet(new MetadataSet(extracted_metadata_set_file)); } // used as arg in the perl scripts private String getCollectDirectory() { String collect_dir = Gatherer.getCollectDirectoryPath(); // 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()); } // deactivate it in tomcat so that windows will release the index files if (Gatherer.GS3) { Gatherer.configGS3Server(Configuration.site_name, ServletConfiguration.DEACTIVATE_COMMAND + collection.getName()); } File index_dir = new File(getCollectionIndexDirectoryPath()); DebugStream.println("Index = " + index_dir.getAbsolutePath()); File building_dir = new File(getCollectionBuildingDirectoryPath()); DebugStream.println("Building = " + building_dir.getAbsolutePath()); // Get the build mode from the build options String build_mode = collection.build_options.getValue("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(Dictionary.get("CollectionManager.Index_Not_Deleted")); } } if (Gatherer.isGsdlRemote) { RemoteGreenstoneServer.deleteCollectionFile(collection.getName(), new File(getCollectionIndexDirectoryPath())); RemoteGreenstoneServer.moveCollectionFile(collection.getName(), new File(getCollectionBuildingDirectoryPath()), new File(getCollectionIndexDirectoryPath())); } // Move the building directory to become the new index directory if (building_dir.renameTo(index_dir) == false) { throw new Exception(Dictionary.get("CollectionManager.Build_Not_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, Dictionary.get("CollectionManager.Install_Exception", 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; // 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("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("-hfile")) { if(tokenizer.hasMoreTokens()) { text.append(" "); text.append(token); token = tokenizer.nextToken(); hfile = token; } } else if (token.equals("-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("-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("-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("-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("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); collection.setFilesChanged(true); } } /** 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); collection.setFilesChanged(true); } } /** 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); collection.setFilesChanged(true); } } /** 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); } } } }