source: trunk/gli/src/org/greenstone/gatherer/file/FileQueue.java@ 8313

Last change on this file since 8313 was 8313, checked in by mdewsnip, 20 years ago

Finally committing the (many) changes to the GLI to use the new metadata code... I hope this doesn't have too many bugs in it and committing it now doesn't stuff anyone up! (Katherine said I could commit it, so blame her if anything goes wrong).

  • Property svn:keywords set to Author Date Id Revision
File size: 35.0 KB
Line 
1/**
2 *#########################################################################
3 *
4 * A component of the Gatherer application, part of the Greenstone digital
5 * library suite from the New Zealand Digital Library Project at the
6 * University of Waikato, New Zealand.
7 *
8 * Author: John Thompson, Greenstone Digital Library, University of Waikato
9 *
10 * Copyright (C) 1999 New Zealand Digital Library Project
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 *########################################################################
26 */
27package org.greenstone.gatherer.file;
28
29import java.io.*;
30import java.util.*;
31import javax.swing.*;
32import javax.swing.event.*;
33import javax.swing.tree.*;
34import org.greenstone.gatherer.Configuration;
35import org.greenstone.gatherer.DebugStream;
36import org.greenstone.gatherer.Dictionary;
37import org.greenstone.gatherer.Gatherer;
38import org.greenstone.gatherer.gui.LongProgressBar;
39import org.greenstone.gatherer.gui.tree.DragTree;
40import org.greenstone.gatherer.metadata.MetadataValue;
41import org.greenstone.gatherer.metadata.MetadataXMLFileManager;
42import org.greenstone.gatherer.util.ArrayTools;
43import org.greenstone.gatherer.util.DragComponent;
44import org.greenstone.gatherer.util.SynchronizedTreeModelTools;
45import org.greenstone.gatherer.util.Utility;
46
47/** A threaded object which processes a queue of file actions such as copying and movement. It also handles updating the various trees involved so they are an accurate representation of the file system they are meant to match.
48 * @author John Thompson, Greenstone Digital Library, University of Waikato
49 * @version 2.3
50 */
51public class FileQueue
52 extends Thread
53 implements TreeSelectionListener {
54 /** When someone requests the movement queue to be dumped this cancel flag is set to true. */
55 private boolean cancel_action = false;
56 /** A temporary mapping from currently existing FileNode folder to their equivelent FileNode folder within the undo managers tree. */
57 private HashMap completed_folder_mappings = new HashMap();
58
59 /** The button which controls the stopping of the file queue. */
60 private JButton stop_button = null;
61
62 /** true to cause this file queue to return from run() as soon as there are no jobs left on the queue. Useful for undo jobs which must occur before a specific action. */
63 private boolean return_immediately = false;
64 /** We are only allowed to wait under specific circumstances. */
65 /* private boolean wait_allowed = true; */
66 /** true if the user has selected yes to all from a file 'clash' dialog. */
67 private boolean yes_to_all = false;
68 /** A temporary mapping from currently existing FileNodes to the potential FileNode folder within the undo managers tree. */
69 private HashMap recycle_folder_mappings = new HashMap();
70 /** A label explaining the current moving files status. */
71 private JLabel file_status = null;
72 /** A list containing a queue of waiting movement jobs. */
73 private ArrayList queue;
74 /** A progress bar which shows how many bytes, out of the total size of bytes, has been moved. */
75 private LongProgressBar progress = null;
76 /** The last piece of text shown on the file status label, just incase we are displaying a very temporary message. */
77 private String previous = null;
78 /** Constructor.
79 * @param return_immediately true to cause this file queue to return from run() as soon as there are no jobs left on the queue.
80 * @see org.greenstone.gatherer.Configuration
81 * @see org.greenstone.gatherer.gui.Coloring
82 * @see org.greenstone.gatherer.gui.LongProgressBar
83 */
84 public FileQueue(boolean return_immediately) {
85 this.return_immediately = return_immediately;
86 this.queue = new ArrayList();
87 String args[] = new String[2];
88 args[0] = "0";
89 args[1] = "0";
90 file_status = new JLabel();
91 Dictionary.setText(file_status, "FileActions.Selected", args);
92 progress = new LongProgressBar();
93 progress.setBackground(Configuration.getColor("coloring.collection_tree_background", false));
94 progress.setForeground(Configuration.getColor("coloring.collection_tree_foreground", false));
95 progress.setString(Dictionary.get("FileActions.No_Activity"));
96 progress.setStringPainted(true);
97 args = null;
98 }
99
100 /** Requeue an existing job into the queue.
101 * @param job A previously created FileJob.
102 */
103 synchronized public void addJob(FileJob job, int position) {
104 job.done = true; // Ensure that the requeued job is marked as done.
105 queue.add(position, job);
106 notify();
107 }
108
109 /** Add a new job to the queue, specifiying as many arguments as is necessary to complete this type of job (ie delete needs no target information).
110 * @param id A long id unique to all jobs created by a single action.
111 * @param source The DragComponent source of this file, most likely a DragTree.
112 * @param child The FileNode you wish to mode.
113 * @param target The DragComponent to move the file to, again most likely a DragTree.
114 * @param parent The files new FileNode parent within the target.
115 * @param type The type of this movement as an int, either COPY or DELETE.
116 * @param undo true if this job should generate undo jobs, false for redo ones.
117 * @param undoable true if this job can generate undo or redo jobs at all, false otherwise.
118 */
119 public void addJob(long id, DragComponent source, FileNode child, DragComponent target, FileNode parent, byte type, boolean undo, boolean undoable, boolean folder_level) {
120 addJob(id, source, child, target, parent, type, undo, undoable, folder_level, -1);
121 }
122
123 synchronized public void addJob(long id, DragComponent source, FileNode child, DragComponent target, FileNode parent, byte type, boolean undo, boolean undoable, boolean folder_level, int position) {
124 FileJob job = new FileJob(id, source, child, target, parent, type, undo, undoable);
125 job.folder_level = folder_level;
126 DebugStream.println("Adding job: " + job);
127 if(position != -1 && position <= queue.size() + 1) {
128 queue.add(position, job);
129 }
130 else {
131 queue.add(job);
132 }
133 notify();
134 }
135
136 /** Calculates the total deep file size of the selected file nodes.
137 * @param files a FileNode[] of selected files
138 * @return true if a cancel was signalled, false otherwise
139 * @see org.greenstone.gatherer.file.FileManager.Task#run()
140 */
141 public boolean calculateSize(FileNode[] files)
142 {
143 file_status.setText(Dictionary.get("FileActions.Calculating_Size"));
144 progress.setString(Dictionary.get("FileActions.Calculating_Size"));
145
146 // Calculate the total file size of all the selected file nodes
147 Vector remaining = new Vector();
148 for (int i = 0; !cancel_action && i < files.length; i++) {
149 remaining.add(files[i]);
150 }
151 while (!cancel_action && remaining.size() > 0) {
152 FileNode node = (FileNode) remaining.remove(0);
153 if (node.isLeaf()) {
154 progress.addMaximum(node.getFile().length());
155 }
156 else {
157 for (int i = 0; !cancel_action && i < node.getChildCount(); i++) {
158 remaining.add(node.getChildAt(i));
159 }
160 }
161 }
162
163 // Now we return if calculation was cancelled so that the FileManagers Task can skip the addJob phase correctly.
164 if (cancel_action) {
165 cancel_action = false; // reset
166 return true;
167 }
168 else {
169 return false;
170 }
171 }
172
173 /** This method is called to cancel the job queue at the next available moment. */
174 public void cancelAction() {
175 cancel_action = true;
176 }
177 /** Access to the file state label. */
178 public JLabel getFileStatus() {
179 return file_status;
180 }
181
182 /** Access to the progress bar. */
183 public LongProgressBar getProgressBar() {
184 return progress;
185 }
186 /** Prevent the progress bar updating momentarily, while its size is re-adjusted. */
187 public void pause() {
188 progress.setIndeterminate(true);
189 }
190
191
192 /** The run method exists in every thread, and here it is used to work its way through the queue of Jobs. If no jobs are waiting and it cans, it waits until a job arrives. If a job is present then it is either COPIED or DELETED, with the records being copied or removed as necessary, and directories being recursed through. Finally the user can press cancel to cause the loop to prematurely dump the job queue then wait.
193 * @see org.greenstone.gatherer.Gatherer
194 * @see org.greenstone.gatherer.collection.CollectionManager
195 * @see org.greenstone.gatherer.file.FileJob
196 * @see org.greenstone.gatherer.file.FileNode
197 * @see org.greenstone.gatherer.gui.LongProgressBar
198 * @see org.greenstone.gatherer.util.Utility
199 */
200 public void run()
201 {
202 super.setName("FileQueue");
203
204 while (!Gatherer.self.exit) {
205 try {
206 // Retrieve the next job
207 int position = queue.size() - 1;
208 FileJob job = removeJob(position);
209 if (job != null) {
210 ///ystem.err.println("Found job: " + job);
211 // Enabled stop button
212 stop_button.setEnabled(true);
213 // The user can cancel this individual action at several places, so keep track if the state is 'ready' for the next step.
214 boolean ready = true;
215 FileNode origin_node = job.getOrigin();
216 FileNode destination_node = job.getDestination();
217 FileSystemModel source_model = (FileSystemModel)job.source.getTreeModel();
218 FileSystemModel target_model = (FileSystemModel)job.target.getTreeModel();
219 if(destination_node == null) {
220 // Retrieve the root node of the target model instead. A delete, or course, has no target file so all deleted files are added to the root of the Recycle Bin model.
221 destination_node = (FileNode) target_model.getRoot();
222 }
223 // Extract common job details.
224 File source_file = origin_node.getFile();
225 File target_file = null;
226 // Determine the target file for a copy or move.
227 if(job.type == FileJob.COPY || job.type == FileJob.MOVE) {
228 //target_file = new File(destination_node.getFile(), source_file.getName());
229 // use the name of the filenode instead of the name of the file - these should be the same except for the collection directories where we want the collection name to be used, not 'import' which is the underlying name
230 target_file = new File(destination_node.getFile(), origin_node.toString());
231 }
232 // To copy a file, copy it then add any metadata found at the source. If this file was already in our collection then we must ensure the lastest version of its metadata.xml has been saved to disk. To copy a directory simply create the directory at the destination, then add all of its children files as new jobs.
233 if((job.type == FileJob.COPY || job.type == FileJob.MOVE) && !job.done) {
234 ///ystem.err.println("Copy/Move: " + origin_node);
235
236 // The number one thing to check is whether we are in a cyclic loop. The easiest way is just to check how deep we are
237 int max_folder_depth = Configuration.getInt("general.max_folder_depth", Configuration.COLLECTION_SPECIFIC);
238 boolean continue_over_depth = false;
239 if(FileManager.countFolderDepth(source_file) > max_folder_depth) {
240 Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("General.No"), Dictionary.get("FileActions.Increase_Depth") };
241 String args[] = { String.valueOf(max_folder_depth), source_file.getAbsolutePath() };
242 int result = JOptionPane.showOptionDialog(Gatherer.g_man, Utility.formatHTMLWidth(Dictionary.get("FileActions.Possible_Cyclic_Path", args), 80), Dictionary.get("General.Warning"), JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
243 args = null;
244 options = null;
245 switch(result) {
246 case 0: // Yes
247 continue_over_depth = true;
248 break;
249 case 2: // Continue and increase depth
250 continue_over_depth = true;
251 Configuration.setInt("general.max_folder_depth", Configuration.COLLECTION_SPECIFIC, (max_folder_depth + 1));
252 break;
253 }
254 }
255 else {
256 continue_over_depth = true;
257 }
258
259 if(continue_over_depth) {
260 FileNode new_node = null;
261 // Check if file exists, and action as necessary. Be aware the user can choose to cancel the action all together (where upon ready becomes false).
262 if(target_file.exists()) {
263 // We've previously been told
264 if(yes_to_all) {
265 // Remove the old file and tree entry.
266 target_file.delete();
267 ready = true;
268 }
269 else {
270 ///atherer.println("Opps! This filename already exists. Give the user some options.");
271 Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("FileActions.Yes_To_All"), Dictionary.get("General.No"), Dictionary.get("General.Cancel") };
272 int result = JOptionPane.showOptionDialog(Gatherer.g_man, Dictionary.get("FileActions.File_Exists", target_file.getName()), Dictionary.get("General.Warning"), JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
273 switch(result) {
274 case 1: // Yes To All
275 yes_to_all = true;
276 case 0: // Yes
277 // Remove the old file and tree entry.
278 if(destination_node != null) {
279 TreePath destination_path = new TreePath(destination_node.getPath());
280 FileNode temp_target_node = new FileNode(target_file, target_model, true);
281 TreePath target_path = destination_path.pathByAddingChild(temp_target_node);
282 SynchronizedTreeModelTools.removeNodeFromParent(target_model, target_model.getNode(target_path));
283 target_path = null;
284 temp_target_node = null;
285 destination_path = null;
286 }
287 target_file.delete();
288 ready = true;
289 break;
290 case 3: // No To All
291 cancel_action = true;
292 case 2: // No
293 default:
294 ready = false;
295 // Increment progress by size of potentially copied file
296 progress.addValue(origin_node.getFile().length());
297 }
298 }
299 }
300 // We proceed with the copy/move if the ready flag is still set. If it is that means there is no longer any existing file of the same name.
301 if(ready) {
302 // update status area
303 String args[] = new String[1];
304 args[0] = "" + (queue.size() + 1) + "";
305 if(job.type == FileJob.COPY) {
306 args[0] = Utility.formatPath("FileActions.Copying", source_file.getAbsolutePath(), file_status.getSize().width);
307 file_status.setText(Dictionary.get("FileActions.Copying", args));
308 }
309 else {
310 args[0] = Utility.formatPath("FileActions.Moving", source_file.getAbsolutePath(), file_status.getSize().width);
311 file_status.setText(Dictionary.get("FileActions.Moving", args));
312 }
313 args = null;
314
315 // If source is a file
316 if(source_file.isFile()) {
317 // copy the file. If anything goes wrong the copy file should throw the appropriate exception. No matter what exception is thrown (bar an IOException) we display some message, perhaps take some action, then cancel the remainder of the pending file jobs. No point in being told your out of hard drive space for each one of six thousand files eh?
318 try {
319 copyFile(source_file, target_file, progress);
320 }
321 // If we can't find the source file, then the most likely reason is that the file system has changed since the last time it was mapped. Warn the user that the requested file can't be found, then force a refresh of the source folder involved.
322 catch(FileNotFoundException fnf_exception) {
323 DebugStream.printStackTrace(fnf_exception);
324 cancel_action = true;
325 // Show warning.
326 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.File_Not_Found_Message", source_file.getName()), Dictionary.get("FileActions.File_Not_Found_Title"), JOptionPane.ERROR_MESSAGE);
327 // Force refresh of source folder.
328 source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
329 }
330 catch(FileAlreadyExistsException fae_exception) {
331 DebugStream.printStackTrace(fae_exception);
332 cancel_action = true;
333 // Show warning.
334 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.File_Already_Exists_Message", target_file.getName()), Dictionary.get("FileActions.File_Already_Exists_Title"), JOptionPane.ERROR_MESSAGE);
335 // Nothing else can be done by the Gatherer.
336 }
337 catch(InsufficientSpaceException is_exception) {
338 DebugStream.printStackTrace(is_exception);
339 cancel_action = true;
340 // Show warning. The message body of the expection explains how much more space is required for this file copy.
341 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Insufficient_Space_Message", is_exception.getMessage()), Dictionary.get("FileActions.Insufficient_Space_Title"), JOptionPane.ERROR_MESSAGE);
342 // Nothing else can be done by the Gatherer. In fact if we are really out of space I'm not even sure we can quit safely.
343 }
344 catch(UnknownFileErrorException ufe_exception) {
345 DebugStream.printStackTrace(ufe_exception);
346 cancel_action = true;
347 // Show warning
348 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Unknown_File_Error_Message"), Dictionary.get("FileActions.Unknown_File_Error_Title"), JOptionPane.ERROR_MESSAGE);
349 // Nothing else we can do.
350 }
351 catch(WriteNotPermittedException wnp_exception) {
352 DebugStream.printStackTrace(wnp_exception);
353 cancel_action = true;
354 // Show warning
355 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Write_Not_Permitted_Message", target_file.getAbsolutePath()), Dictionary.get("FileActions.Write_Not_Permitted_Title"), JOptionPane.ERROR_MESSAGE);
356 // Nothing else we can do.
357 }
358 catch(IOException exception) {
359 // Can't really do much about this.
360 DebugStream.printStackTrace(exception);
361 }
362 // If not cancelled
363 if(!cancel_action) {
364 // Step one is to create a dummy FileNode. Its important it has the correct structure so getPath works.
365 FileNode new_record = new FileNode(target_file);
366 SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, new_record);
367 new_node = new_record;
368
369 // create undo job
370 if(job.undoable) {
371 job.undoable = false;
372 if(job.type == FileJob.COPY) {
373 // A copy is undone with a delete, so it doesn't really matter where the file originally came from (we're not moving it back there, but into the recycle bin). You may also notice we don't make use of the target parent record. This is because no undo action needs this information, and even if it did it could simply ask for records parent!
374 // Gatherer.c_man.undo.addUndo(job.ID(), UndoManager.FILE_COPY, null, null, job.target, new_record, job.undo);
375 }
376 else {
377 // Movements however do need a source and source parent so the file can be moved back to the correct place.
378 // Gatherer.c_man.undo.addUndo(job.ID(), UndoManager.FILE_MOVE, job.source, (FileNode)origin_node.getParent(), job.target, new_record, job.undo);
379 }
380 }
381 new_record = null;
382 }
383 }
384 // Else
385 else if(source_file.isDirectory()) {
386 // create new record
387 FileNode directory_record = new FileNode(target_file);
388 ///ystem.err.println("Directory record = " + directory_record + " (" + target_file.getAbsolutePath() + ")");
389 SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, directory_record);
390 // Why is this not happening eh?
391 directory_record.setParent(destination_node);
392 if(!target_file.exists()) {
393 // make the directory
394 target_file.mkdirs();
395 new_node = directory_record;
396 // create undo job
397 if(job.undoable) {
398 job.undoable = false;
399 if(job.type == FileJob.COPY) {
400 // A copy is undone with a delete, so it doesn't really matter where the file originally came from (we're not moving it back there, but into the recycle bin). You may also notice we don't make use of the target parent record. This is because no undo action needs this information, and even if it did it could simply ask for records parent!
401 }
402 else {
403 // Movements however do need a source and source parent so the file can be moved back to the correct place.
404 }
405 }
406 }
407 // Else inform the users that a directory already exists and files will be copied into it
408 //else {
409 // JOptionPane.showMessageDialog(null, Dictionary.get("FileActions.Directory_Exists", target_file.toString()), Dictionary.get("General.Warning"), JOptionPane.WARNING_MESSAGE);
410 //}
411 // Queue non-filtered child files for copying. If this directory already existed, the child records will have to generate the undo jobs, as we don't want to entirely delete this directory if it already existed.
412 FileNode child_record = null;
413 // In order to have a sane copy proceedure (rather than always copying last file first as it used to) we always add the child node at the position the parent was removed from. Consider the file job 'a' at the end of the queue which generates three new jobs 'b', 'c' and 'd'. The resulting flow should look like this.
414 // -- Starting queue ...[a]
415 // remove(position) = 'a' ...
416 // add(position, 'b') ...[b]
417 // add(position, 'c') ...[c][b]
418 // add(position, 'd') ...[d][c][b]
419 // Next loop
420 // remove(position) = 'b' ...[d][c]
421 for(int i = 0; i < origin_node.getChildCount(); i++) {
422 child_record = (FileNode) origin_node.getChildAt(i);
423 addJob(job.ID(), job.source, child_record, job.target, directory_record, job.type, job.undo, false, false, position);
424 }
425 child_record = null;
426 directory_record = null;
427 }
428 // The file wasn't found!
429 else {
430 cancel_action = true;
431 // Show warning.
432 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.File_Not_Found_Message", source_file.getName()), Dictionary.get("FileActions.File_Not_Found_Title"), JOptionPane.ERROR_MESSAGE);
433 // Force refresh of source folder.
434 source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
435 }
436
437 // We can't have been cancelled, and we must have created a new FileNode during the above phase, before we can handle metadata.
438 if (!cancel_action && new_node != null) {
439 /* Time to handle any existing metadata. */
440 // If the directory came from inside our collection...
441 if (job.source.toString().equals("Collection")) {
442 // System.err.println("Move within collection...");
443
444 // Get the non-folder level metadata assigned to the origin node...
445 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
446 // ...and remove it from the original node and assign it to the new folder
447 for (int i = 0; i < assigned_metadata.size(); i++) {
448 MetadataValue metadata_value = (MetadataValue) assigned_metadata.get(i);
449 MetadataXMLFileManager.removeMetadata(origin_node, metadata_value);
450 MetadataXMLFileManager.addMetadata(new_node, metadata_value);
451 }
452 }
453 // If it came from the workspace search for metadata assigned to the file
454 else if (job.source.toString().equals("Workspace")) {
455 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToExternalFile(origin_node.getFile());
456 for (int i = 0; i < assigned_metadata.size(); i++) {
457 MetadataValue metadata_value = (MetadataValue) assigned_metadata.get(i);
458 MetadataXMLFileManager.addMetadata(new_node, metadata_value);
459 }
460 }
461 }
462 new_node = null;
463 }
464 }
465 }
466 // If we haven't been cancelled, and we've been asked to delete a directory/file, or perhaps as part of a move, we delete the file. This involves removing any existing metadata and then copying the file to the recycled bin (for a delete only), then deleting the file. When deleting a directory record from the tree (or from the filesystem for that matter) we must ensure that all of the descendant records have already been removed. If we fail to do this the delete will fail, or you will be bombarded with hundreds of 'Parent node of null not allowed' error messages. Also be aware that if the user has cancelled just this action, because of say a name clash, then we shouldn't do any deleting of any sort dammit.
467 if(!cancel_action && ready && (job.type == FileJob.DELETE || job.type == FileJob.MOVE)) {
468 ///atherer.println("Delete/Move: " + origin_node);
469 ///atherer.println(queue.size() + " jobs remain in queue");
470
471 if (source_file.isFile()) {
472 progress.addValue(source_file.length());
473 }
474
475 // If the source is a file or an empty directory (but not the root node of a tree)
476 File[] child_list = source_file.listFiles();
477 if (source_file.isFile() || (child_list != null && child_list.length == 0 && origin_node.getParent() != null)) {
478 // System.err.println("Deleting file: " + source_file.getAbsolutePath());
479
480 // Update status area
481 String args[] = new String[1];
482 args[0] = Utility.formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width);
483 file_status.setText(Dictionary.get("FileActions.Deleting", args));
484
485 // If it is a metadata.xml file, we must unload it
486 if (source_file.getName().equals(Utility.METADATA_XML)) {
487 MetadataXMLFileManager.unloadMetadataXMLFile(source_file);
488 }
489
490 // Remove the metadata assigned directly to the file
491 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(origin_node.getFile());
492 for (int i = 0; i < assigned_metadata.size(); i++) {
493 MetadataValue metadata_value = (MetadataValue) assigned_metadata.get(i);
494 MetadataXMLFileManager.removeMetadata(origin_node, metadata_value);
495 }
496
497 // Remove from model
498 FileNode parent_record = (FileNode) origin_node.getParent();
499 if (parent_record != null) {
500 SynchronizedTreeModelTools.removeNodeFromParent(source_model, origin_node);
501 }
502
503 // Delete the source file
504 Utility.delete(source_file);
505 }
506 // Else the source is a directory and it has children remaining
507 else if(child_list != null && child_list.length > 0) {
508 ///ystem.err.print("Nonempty directory -> ");
509 ///atherer.println("Directory is non-empty. Remove children first.");
510 FileNode recycle_folder_record = null;
511 // Don't worry about all this for true file move actions.
512 if(job.type == FileJob.DELETE) {
513 // queue all of its children, (both filtered and non-filtered), but for deleting only. Don't queue jobs for a current move event, as they would be queued as part of copying. I have no idea way, per sec, however the children within the origin node are always invalid during deletion (there are several copies of some nodes?!?). I'll check that each child is only added once.
514 ///ystem.err.println("Directory has " + origin_node.getChildCount() + " children.");
515 ///ystem.err.println("Directory actually has " + child_list.length + " children.");
516 origin_node.refresh();
517 ///atherer.println("Directory has " + origin_node.getChildCount() + " children.");
518 ///atherer.println("Directory actually has " + child_list.length + " children.");
519 for(int i = 0; i < origin_node.size(); i++) {
520 FileNode child_record = (FileNode) origin_node.get(i);
521 ///atherer.println("Queuing: " + child_record);
522 addJob(job.ID(), job.source, child_record, job.target, destination_node, FileJob.DELETE, job.undo, false, false, position);
523 //if(recycle_folder_record != null) {
524 // recycle_folder_mappings.put(child_record, recycle_folder_record);
525 //}
526 }
527 }
528 // Requeue a delete job -after- the children have been dealt with. Remember I've reversed the direction of the queue so sooner is later. Te-he. Also have to remember that we have have followed this path to get here for a move job: Copy Directory -> Queue Child Files -> Delete Directory (must occur after child files) -> Queue Directory.
529 // One special case. Do not requeue root nodes. Don't requeue jobs marked as done.
530 if(origin_node.getParent() != null && !job.done) {
531 ///atherer.println("Requeuing: " + origin_node.getFile().getAbsolutePath());
532 job.type = FileJob.DELETE; // You only requeue jobs that are deletes, as directories must be inspected before children, but deleted after.
533 addJob(job, position);
534 }
535 else {
536 DebugStream.println("I've already done this job twice. I refuse to requeue it again!!");
537 }
538 }
539 }
540 job = null;
541 source_file = null;
542 target_file = null;
543 origin_node = null;
544 // We can only break out of the while loop if we are out of files, or if the action was cancelled.
545 if(cancel_action) {
546 // Empty queue
547 clearJobs();
548 cancel_action = false;
549 }
550 // Debugging pause.
551 ///ystem.err.println("Job complete.");
552 }
553 else {
554 // Disable stop button
555 if(stop_button != null) {
556 stop_button.setEnabled(false);
557 }
558 synchronized(this) {
559 // Force both workspace and collection trees to refresh
560 if (Gatherer.g_man != null) {
561 Gatherer.g_man.refreshWorkspaceTree(DragTree.COLLECTION_CONTENTS_CHANGED);
562 Gatherer.g_man.refreshCollectionTree(DragTree.COLLECTION_CONTENTS_CHANGED);
563 }
564
565 // Reset status area
566 file_status.setText(Dictionary.get("FileActions.No_Activity"));
567 progress.reset();
568 progress.setString(Dictionary.get("FileActions.No_Activity"));
569 yes_to_all = false;
570 completed_folder_mappings.clear();
571 recycle_folder_mappings.clear();
572
573 // Reset whether we complain about no sets.
574 if(Gatherer.f_man != null) {
575 Gatherer.f_man.complain_if_no_sets = true;
576 }
577
578 // Now wait if applicable.
579 if(return_immediately) {
580 return;
581 }
582 ///ystem.err.println("Waiting");
583 wait();
584 }
585 }
586 }
587 catch (Exception error) {
588 DebugStream.printStackTrace(error);
589 }
590 }
591 }
592
593 /** Register the button that will be responsible for stopping executing file actions.
594 * @param stop_button a JButton
595 */
596 public void registerStopButton(JButton stop_button) {
597 this.stop_button = stop_button;
598 }
599
600 /** Called when the user makes some selection in one of the trees we are listening to. From this we update the status details. */
601 public void valueChanged(TreeSelectionEvent event) {
602 JTree tree = (JTree) event.getSource();
603 if(tree.getSelectionCount() > 0) {
604 TreePath selection[] = tree.getSelectionPaths();
605 int file_count = 0;
606 int dir_count = 0;
607 for(int i = 0; i < selection.length; i++) {
608 TreeNode record = (TreeNode) selection[i].getLastPathComponent();
609 if(record.isLeaf()) {
610 file_count++;
611 }
612 else {
613 dir_count++;
614 }
615 record = null;
616 }
617 selection = null;
618 }
619 tree = null;
620 }
621
622 synchronized private void clearJobs() {
623 queue.clear();
624 }
625
626 /** Copy the contents from the source directory to the destination
627 * directory.
628 * @param source The source directory
629 * @param destination The destination directory
630 * @param progress A progress bar to monitor copying progress
631 * @see org.greenstone.gatherer.Gatherer
632 */
633 public void copyDirectoryContents(File source, File destination, LongProgressBar progress)
634 throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, UnknownFileErrorException, WriteNotPermittedException
635 {
636 if (!source.isDirectory()) return;
637 // check that dest dirs exist
638 destination.mkdirs();
639
640 File [] src_files = source.listFiles();
641 if (src_files.length == 0) return; // nothing to copy
642 for (int i=0; i<src_files.length; i++) {
643 File f = src_files[i];
644 String f_name = f.getName();
645 File new_file = new File(destination, f_name);
646 if (f.isDirectory()) {
647 copyDirectoryContents(f, new_file, progress);
648 } else if (f.isFile()) {
649 copyFile(f, new_file, progress);
650 }
651 }
652
653 }
654
655 /** Copy a file from the source location to the destination location.
656 * @param source The source File.
657 * @param destination The destination File.
658 * @see org.greenstone.gatherer.Gatherer
659 */
660 public void copyFile(File source, File destination, LongProgressBar progress)
661 throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, UnknownFileErrorException, WriteNotPermittedException {
662 if(source.isDirectory()) {
663 destination.mkdirs();
664 }
665 else {
666 // Check if the origin file exists.
667 if(!source.exists()) {
668 DebugStream.println("Couldn't find the source file.");
669 throw(new FileNotFoundException());
670 }
671 // Check if the destination file does not exist.
672 if(destination.exists()) {
673 throw(new FileAlreadyExistsException());
674 }
675 File dirs = destination.getParentFile();
676 dirs.mkdirs();
677 // Copy the file.
678 FileInputStream f_in = new FileInputStream(source);
679 FileOutputStream f_out = null;
680 // This may throw a file not found exception, but this translates to a WriteNotPermittedException, in this case
681 try {
682 f_out = new FileOutputStream(destination);
683 }
684 catch (FileNotFoundException exception) {
685 throw new WriteNotPermittedException(exception.toString());
686 }
687 byte data[] = new byte[Utility.BUFFER_SIZE];
688 int data_size = 0;
689 while((data_size = f_in.read(data, 0, Utility.BUFFER_SIZE)) != -1 && !cancel_action) {
690 long destination_size = destination.length();
691 try {
692 f_out.write(data, 0, data_size);
693 }
694 // If an IO exception occurs, we can do some maths to determine if the number of bytes written to the file was less than expected. If so we assume a InsufficientSpace exception. If not we just throw the exception again.
695 catch (IOException io_exception) {
696 if(destination_size + (long) data_size > destination.length()) {
697 // Determine the difference (which I guess is in bytes).
698 long difference = (destination_size + (long) data_size) - destination.length();
699 // Transform that into a human readable string.
700 String message = Utility.formatFileLength(difference);
701 throw(new InsufficientSpaceException(message));
702 }
703 else {
704 throw(io_exception);
705 }
706 }
707 if(progress != null) {
708 progress.addValue(data_size);
709 }
710 }
711 // Flush and close the streams to ensure all bytes are written.
712 f_in.close();
713 f_out.close();
714 // We have now, in theory, produced an exact copy of the source file. Check this by comparing sizes.
715 if(!destination.exists() || (!cancel_action && source.length() != destination.length())) {
716 throw(new UnknownFileErrorException());
717 }
718 // If we were cancelled, ensure that none of the destination file exists.
719 if(cancel_action) {
720 destination.delete();
721 }
722 }
723 }
724
725
726 private FileJob removeJob(int position) {
727 FileJob job = null;
728 if(queue.size() > 0) {
729 job = (FileJob) queue.remove(position);
730 }
731 return job;
732 }
733}
Note: See TracBrowser for help on using the repository browser.