/** *######################################################################### * * 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.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.LocalGreenstone; import org.greenstone.gatherer.greenstone.LocalLibraryServer; import org.greenstone.gatherer.greenstone.Plugins; import org.greenstone.gatherer.greenstone3.ServletConfiguration; 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 responsible 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? */ static private boolean building = false; /** Are we currently in the process of importing? */ static private boolean importing = false; /** Are we currently in the process of scheduling? */ static private boolean scheduling = false; /** The objects listening for CollectionContentsChanged events. */ static 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. */ static private CollectionTreeModel collection_tree_model = null; /** An inner class listener responsible for noting tree changes and resetting saved when they occur. */ static private FMTreeModelListener fm_tree_model_listener = null; /** The monitor responsible for parsing the build process. */ static private GShellProgressMonitor build_monitor = null; /** The monitor responsible for parsing the import process. */ static private GShellProgressMonitor import_monitor = null; /** The monitor responsible for parsing the scheduler process. */ static private GShellProgressMonitor schedule_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; /** Used to indicate the source of the message is in the scheduling methods...? */ static final public int SCHEDULING = 7; /** Constructor. */ public CollectionManager() { // Initialisation. this.building = false; this.importing = false; this.scheduling = 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(); } } static 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"); } if (Configuration.fedora_info.isActive()) { command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "g2f-buildcol.pl"); command_parts_list.add("-hostname"); command_parts_list.add(Configuration.fedora_info.getHostname()); command_parts_list.add("-port"); command_parts_list.add(Configuration.fedora_info.getPort()); command_parts_list.add("-username"); command_parts_list.add(Configuration.fedora_info.getUsername()); command_parts_list.add("-password"); command_parts_list.add(Configuration.fedora_info.getPassword()); command_parts_list.add("-protocol"); command_parts_list.add(Configuration.fedora_info.getProtocol()); } else { 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 and 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(); } /*probably repeating alot of work, but I want to keep this separate... wendy*/ public void scheduleBuild(boolean incremental_build) { DebugStream.println("In CollectionManager.scheduleBuild(), incremental_build: " + incremental_build); DebugStream.println("Is event dispatch threa: " + SwingUtilities.isEventDispatchThread()); ArrayList sched_list = new ArrayList(); if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) { sched_list.add(Configuration.perl_path); sched_list.add("-S"); } sched_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "schedule.pl"); sched_list.add("-colname"); sched_list.add(collection.getName()); sched_list.add("-gli"); // First, generate the import.pl command, also converting to a string // Generate the import.pl command ArrayList import_list = new ArrayList(); if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) { import_list.add(Configuration.perl_path); import_list.add("-S"); } import_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "import.pl"); import_list.add("-language"); import_list.add(Configuration.getLanguage()); import_list.add("-collectdir"); import_list.add(getCollectDirectory()); String[] import_options = collection.import_options.getValues(); int i = 0; for (i = 0; i < import_options.length; i++) { import_list.add(import_options[i]); } import_list.add(collection.getName()); String[] import_parts = (String[]) import_list.toArray(new String[0]); String command = ""; i = 0; for (i = 0; i < import_parts.length-1; i++) { command = command + import_parts[i] + " "; } command = command + import_parts[i]; sched_list.add("-import"); sched_list.add("\"" + command + "\""); // Generate the buildcol.pl command, also converting to a string ArrayList build_list = new ArrayList(); // i'm not doing this in schedule.pl right now - should i be? if ((Utility.isWindows()) && (!Gatherer.isGsdlRemote)) { build_list.add(Configuration.perl_path); build_list.add("-S"); } build_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "buildcol.pl"); build_list.add("-language"); build_list.add(Configuration.getLanguage()); build_list.add("-collectdir"); build_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")) { build_list.add(incremental_build ? "-keepold" : "-removeold"); } String[] build_options = collection.build_options.getValues(); for (i = 0; i < build_options.length; i++) { build_list.add(build_options[i]); } build_list.add(collection.getName()); //build actual string String[] build_parts = (String[]) build_list.toArray(new String[0]); String command2 = ""; for(i = 0; i < build_parts.length-1; i++) { command2 = command2 + build_parts[i] + " "; } command2 = command2 + build_parts[i]; sched_list.add("-build"); sched_list.add("\"" + command2 + "\""); //next, the scheduling frequency goes here String[] schedule_options = collection.schedule_options.getValues(); for(i = 0; i < schedule_options.length; i++) { sched_list.add(schedule_options[i]); } //now, hope it will run. ;) String[] sched_parts = (String[]) sched_list.toArray(new String[0]); GShell shell = new GShell(sched_parts, GShell.SCHEDULE, SCHEDULING, this, schedule_monitor, GShell.GSHELL_SCHEDULE); 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 (gs2) // buildConfig.xml (gs3) or export.inf (fedora) file String file_name = ""; if (Configuration.fedora_info != null && Configuration.fedora_info.isActive()) { // FLI case // Fedora build //file_name = getLoadedCollectionArchivesDirectoryPath() + "import.inf"; file_name = getLoadedCollectionExportDirectoryPath() + "export.inf"; } else { // GLI is running, check if it's greenstone 3 or greenstone 2 if (Gatherer.GS3) { // GS3 GLI file_name = getLoadedCollectionIndexDirectoryPath() + Utility.BUILD_CONFIG_XML; } else { // greenstone 2 GLI file_name = getLoadedCollectionIndexDirectoryPath() + Utility.BUILD_CFG; } } File test_file = new File(file_name); return test_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 */ static private 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; } /** Returns the absolute filename of the specified collection's directory. */ static public String getCollectionDirectoryPath(String collection_name) { return Gatherer.getCollectDirectoryPath() + collection_name + File.separator; } /** Returns the absolute filename of the loaded collection's archives directory. */ static public String getLoadedCollectionArchivesDirectoryPath() { return getLoadedCollectionDirectoryPath() + "archives" + File.separator; } /** Returns the absolute filename of the loaded collection's export directory. */ static public String getLoadedCollectionExportDirectoryPath() { return getLoadedCollectionDirectoryPath() + "export" + File.separator; } /** Returns the absolute filename of the loaded collection's building directory. */ static public String getLoadedCollectionBuildingDirectoryPath() { return getLoadedCollectionDirectoryPath() + "building" + File.separator; } /** Returns the absolute filename of the loaded collection's collect.cfg file. */ static public String getLoadedCollectionCfgFilePath() { String path = (Gatherer.GS3 == true)? Utility.COLLECTION_CONFIG_XML : Utility.COLLECT_CFG; return getLoadedCollectionEtcDirectoryPath() + path; } /** Returns the absolute filename of the loaded collection's directory. */ static public String getLoadedCollectionDirectoryPath() { return collection.getCollectionDirectory().getPath() + File.separator; } /** Returns the absolute filename of the loaded collection's etc directory. */ static public String getLoadedCollectionEtcDirectoryPath() { return getLoadedCollectionDirectoryPath() + "etc" + File.separator; } /** Returns the absolute filename of the loaded collection's .col file. */ static public String getLoadedCollectionColFilePath() { return getLoadedCollectionDirectoryPath() + collection.getName() + ".col"; } /** Returns the absolute filename of the loaded collection's images directory. */ static public String getLoadedCollectionImagesDirectoryPath() { return getLoadedCollectionDirectoryPath() + "images" + File.separator; } /** Returns the absolute filename of the loaded collection's import directory. */ static public String getLoadedCollectionImportDirectoryPath() { return getLoadedCollectionDirectoryPath() + "import" + File.separator; } /** Returns the absolute filename of the loaded collection's index directory. */ static public String getLoadedCollectionIndexDirectoryPath() { return getLoadedCollectionDirectoryPath() + "index" + File.separator; } /** Returns the absolute filename of the loaded collection's log directory. */ static public String getLoadedCollectionLogDirectoryPath() { return getLoadedCollectionDirectoryPath() + "log" + File.separator; } /** Returns the absolute filename of the loaded collection's macros directory. */ static public String getLoadedCollectionMacrosDirectoryPath() { return getLoadedCollectionDirectoryPath() + "macros" + File.separator; } /** Returns the absolute filename of the loaded collection's metadata directory. */ static public String getLoadedCollectionMetadataDirectoryPath() { return getLoadedCollectionDirectoryPath() + "metadata" + File.separator; } /** Returns the name of the loaded collection. */ static public String getLoadedCollectionName() { if (collection != null) { return collection.getName(); } return null; } /** Returns the "collectionGroupName/collectionName" or just the collectionName * depending on whether the collection is part of a collection group or not. * If url = true, then returns the sub-path as a URL (containing / only), * and if url = false, then the sub-path is returned in filepath form * (\ or /, depending on the OS). */ static public String getLoadedColNameWithGroup(boolean url) { if (collection != null) { return collection.getGroupWithName(url); } return null; } 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(getLoadedCollectionImportDirectoryPath()))); // 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(getLoadedCollectionIndexDirectoryPath()); 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"); } if (Configuration.fedora_info.isActive()) { command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "g2f-import.pl"); command_parts_list.add("-hostname"); command_parts_list.add(Configuration.fedora_info.getHostname()); command_parts_list.add("-port"); command_parts_list.add(Configuration.fedora_info.getPort()); command_parts_list.add("-username"); command_parts_list.add(Configuration.fedora_info.getUsername()); command_parts_list.add("-password"); command_parts_list.add(Configuration.fedora_info.getPassword()); command_parts_list.add("-protocol"); command_parts_list.add(Configuration.fedora_info.getProtocol()); } else { 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(getLoadedCollectionMetadataDirectoryPath(), 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) { Gatherer.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(); Gatherer.setMenuBarEnabled(true); } } /** 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 (Gatherer.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; } String file_str = (Gatherer.GS3)? Utility.CONFIG_GS3_FILE : Utility.CONFIG_FILE; File collection_config_file = new File(collection_directory, file_str); 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_Message", new String[]{lock_file.getAbsolutePath()}); if(Gatherer.client_operating_system.toUpperCase().indexOf("WINDOWS")!=-1){ //if(Gatherer.client_operating_system.toUpperCase().indexOf("VISTA")!=-1){ args[1] += Dictionary.get("FileActions.File_Permission_Detail", new String[]{Configuration.gsdl_path, System.getProperty("user.name")}); //} } JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Cannot_Open_With_Reason", args), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); args = null; return; } if (canDoScheduling()) { //THIS LOOKS LIKE THE BEST PLACE TO TRY AND UPDATE .col FILES FOR EXISTING COLLECTIONS...Wendy //First, see if "Schedule" exists in the XMl File... BufferedReader bir = new BufferedReader(new FileReader(collection_file)); boolean flag = false; try { String stmp = new String(); while((stmp = bir.readLine()) != null) { stmp = stmp.trim(); if(stmp.equals("") || stmp.equals("")) { flag = true; break; } } bir.close(); } catch (IOException ioe) { DebugStream.printStackTrace(ioe); } //modify if old .col (i.e. no Schedule exists in XML file) if(!flag) { File new_collection_file = new File(collection_directory.getAbsolutePath() + "/tmp.col"); BufferedWriter bor = new BufferedWriter(new FileWriter(new_collection_file)); bir = new BufferedReader(new FileReader(collection_file)); try { String stmp = new String(); while((stmp = bir.readLine()) != null) { String stmp2 = stmp.trim(); if(stmp2.startsWith("\n"); } else if(stmp2.equals("")) { bor.write(" \n"); } bor.write(stmp + "\n"); } bir.close(); bor.close(); } catch (IOException ioe) { DebugStream.printStackTrace(ioe); } //copy over tmp.col to replace try { collection_file.delete(); new_collection_file.renameTo(collection_file); } catch (Exception e) { DebugStream.printStackTrace(e); } } } // 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 } if (canDoScheduling()) { scheduling(); } 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,collection.toSkimFile()); // get rid of the previous scan through docxml files DocXMLFileManager.clearDocXMLFiles(); if (Configuration.fedora_info.isActive()) { // FLI case // Read through the docmets.xml files in the export directory File collection_export_directory = new File(getLoadedCollectionExportDirectoryPath()); DocXMLFileManager.loadDocXMLFiles(collection_export_directory,"docmets.xml"); } else { // Read through the doc.xml files in the archives directory File collection_archives_directory = new File(getLoadedCollectionArchivesDirectoryPath()); DocXMLFileManager.loadDocXMLFiles(collection_archives_directory,"doc.xml"); } // 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); error.printStackTrace(); if(error.getMessage() != null) { String[] args = new String[2]; args[0] = location; //args[1] = error.getMessage(); args[1] = "The Librarian Interface does not have permission to write to... Please check file permissions."; 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; } /** At present, scheduling only works for GS2, only when GS2 is local and only when GLI runs from * within a GS2 installation. This method can be adjusted as scheduling becomes available for more * more situations. */ public static boolean canDoScheduling() { // Would be nice to support more of these, rather than returning false if(Gatherer.isGsdlRemote) { return false; } if(Gatherer.GS3) { return false; } if (Configuration.fedora_info.isActive()) { return false; } // GS2's etc/main.cfg is necessary for scheduling, but scheduling looks for it locally: // it assumes GLI is inside a GS2 installation File mcfg = new File(LocalGreenstone.getDirectoryPath() + File.separator + "etc" + File.separator + "main.cfg"); if(!mcfg.exists()) { System.out.println("Cannot do scheduling, since there is no file: " + mcfg.getAbsolutePath() + ".\nScheduling presently depends on GLI running from inside a GS2."); return false; } return true; } 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"); if(Gatherer.GS3) { command_parts_list.add(Utility.GS3MODE_ARGUMENT); // add '-gs3mode' } command_parts_list.add("-collectdir"); command_parts_list.add(getDefaultCollectDirectory()); 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]); //for(int i = 0; i < command_parts.length; i++) { ///ystem.err.println("\""+command_parts[i]+"\""); //} 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) { // 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); } else if(event.getType() == GShell.SCHEDULE && event.getStatus() == GShell.OK ) { WarningDialog collection_built_warning_dialog = new WarningDialog("warning.ScheduleBuilt", Dictionary.get("ScheduleBuilt.Title"), Dictionary.get("ScheduleBuilt.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; } // 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) { //xiao comment out this: 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) { if (event.getType() == GShell.NEW) { String name = event.getMessage(); String collectDir = getCollectionDirectoryPath(name); String errMsg = ""; if (!new File(getCollectionDirectoryPath(name)).exists() || !new File(getCollectionDirectoryPath(name)).canWrite()) { String reason = Dictionary.get("FileActions.Write_Not_Permitted_Message", new String[]{collectDir}); errMsg = Dictionary.get("CollectionManager.Cannot_Create_Collection_With_Reason", new String[]{reason}); if(Gatherer.client_operating_system.toUpperCase().indexOf("WINDOWS") != -1){ //if(Gatherer.client_operating_system.toUpperCase().indexOf("VISTA")!=-1){ errMsg += Dictionary.get("FileActions.File_Permission_Detail", new String[]{Configuration.gsdl_path, System.getProperty("user.name")}); //} } } else { errMsg = Dictionary.get("CollectionManager.Cannot_Create_Collection"); } JOptionPane.showMessageDialog(Gatherer.g_man, errMsg, Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE); } else if(event.getType() == GShell.SCHEDULE) { JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CollectionManager.Schedule_Failed"), Dictionary.get("CollectionManager.Schedule_Ready_Title"), 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 registerScheduleMonitor(GShellProgressMonitor monitor) { schedule_monitor = monitor; } static 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) { Gatherer.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(getLoadedCollectionColFilePath()); 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)); } private String getDefaultCollectDirectory() { 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; } // used as arg in the perl scripts private String getCollectDirectory() { String collect_dir = collection.getCollectionDirectory().getParentFile().getPath(); 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() { if (Configuration.fedora_info.isActive()) { DebugStream.println("Fedora build complete. No need to move files."); return true; } 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.isGsdlRemote) { Gatherer.configGS3Server(Configuration.site_name, ServletConfiguration.DEACTIVATE_COMMAND + collection.getName()); } File index_dir = new File(getLoadedCollectionIndexDirectoryPath()); DebugStream.println("Index = " + index_dir.getAbsolutePath()); File building_dir = new File(getLoadedCollectionBuildingDirectoryPath()); 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) { Gatherer.remoteGreenstoneServer.deleteCollectionFile( collection.getName(), new File(getLoadedCollectionIndexDirectoryPath())); Gatherer.remoteGreenstoneServer.moveCollectionFile(collection.getName(), new File(getLoadedCollectionBuildingDirectoryPath()), new File(getLoadedCollectionIndexDirectoryPath())); } // 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 updateCollectionConfigXML(File base_cfg, File new_cfg) { //In this method, the files base_cfg and new_cfg are all xml files. Document base_cfg_doc = XMLTools.parseXMLFile(base_cfg); XMLTools.writeXMLFile(new_cfg, base_cfg_doc); Document new_cfg_doc = XMLTools.parseXMLFile(new_cfg); Element collection_config = new_cfg_doc.getDocumentElement(); Node browseNode = XMLTools.getChildByTagNameIndexed(collection_config, StaticStrings.BROWSE_STR, 0); NodeList classifier_children = ((Element)browseNode).getElementsByTagName(StaticStrings.CLASSIFIER_STR); int num_nodes = classifier_children.getLength(); if (num_nodes < 1) { return; } // Read in the classifier command watching for hfile, metadata and sort arguments. String buttonname = null; String hfile = null; String metadata = null; String sort = null; for (int i=0; i] 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); } } } }