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

Last change on this file since 5785 was 5785, checked in by mdewsnip, 21 years ago

Commented out about 60 unused functions.

  • Property svn:keywords set to Author Date Id Revision
File size: 37.4 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.Dictionary;
35import org.greenstone.gatherer.Gatherer;
36import org.greenstone.gatherer.file.FileJob;
37import org.greenstone.gatherer.file.FileNode;
38import org.greenstone.gatherer.gui.LongProgressBar;
39import org.greenstone.gatherer.gui.tree.DragTree;
40import org.greenstone.gatherer.msm.GDMManager;
41import org.greenstone.gatherer.undo.UndoManager;
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 /** 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. */
59 private boolean return_immediately = false;
60 /** We are only allowed to wait under specific circumstances. */
61 private boolean wait_allowed = true;
62 /** true if the user has selected yes to all from a file 'clash' dialog. */
63 private boolean yes_to_all = false;
64 /** A temporary mapping from currently existing FileNodes to the potential FileNode folder within the undo managers tree. */
65 private HashMap recycle_folder_mappings = new HashMap();
66 /** A label explaining the current moving files status. */
67 private JLabel file_status = null;
68 /** A list containing a queue of waiting movement jobs. */
69 //private LinkedList queue;
70 private ArrayList queue;
71 /** A progress bar which shows how many bytes, out of the total size of bytes, has been moved. */
72 private LongProgressBar progress = null;
73 /** The last piece of text shown on the file status label, just incase we are displaying a very temporary message. */
74 private String previous = null;
75 /** Constructor.
76 * @param return_immediately true to cause this file queue to return from run() as soon as there are no jobs left on the queue.
77 * @see org.greenstone.gatherer.Configuration
78 * @see org.greenstone.gatherer.gui.Coloring
79 * @see org.greenstone.gatherer.gui.LongProgressBar
80 */
81 public FileQueue(boolean return_immediately) {
82 this.return_immediately = return_immediately;
83 this.queue = new ArrayList();//LinkedList();
84 String args[] = new String[2];
85 args[0] = "0";
86 args[1] = "0";
87 file_status = new JLabel();
88 Dictionary.setText(file_status, "FileActions.Selected", args);
89 progress = new LongProgressBar();
90 progress.setBackground(Gatherer.config.getColor("coloring.collection_tree_background", false));
91 progress.setForeground(Gatherer.config.getColor("coloring.collection_tree_foreground", false));
92 progress.setString(Dictionary.get("FileActions.No_Activity"));
93 progress.setStringPainted(true);
94 args = null;
95 }
96
97 /** Requeue an existing job into the queue.
98 * @param job A previously created FileJob.
99 */
100 synchronized public void addJob(FileJob job, int position) {
101 job.done = true; // Ensure that the requeued job is marked as done.
102 queue.add(position, job);
103 notify();
104 }
105
106 /** 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).
107 * @param id A long id unique to all jobs created by a single action.
108 * @param source The DragComponent source of this file, most likely a DragTree.
109 * @param child The FileNode you wish to mode.
110 * @param target The DragComponent to move the file to, again most likely a DragTree.
111 * @param parent The files new FileNode parent within the target.
112 * @param type The type of this movement as an int, either COPY or DELETE.
113 * @param undo true if this job should generate undo jobs, false for redo ones.
114 * @param undoable true if this job can generate undo or redo jobs at all, false otherwise.
115 */
116 public void addJob(long id, DragComponent source, FileNode child, DragComponent target, FileNode parent, byte type, boolean undo, boolean undoable, boolean folder_level) {
117 addJob(id, source, child, target, parent, type, undo, undoable, folder_level, -1);
118 }
119
120 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) {
121 FileJob job = new FileJob(id, source, child, target, parent, type, undo, undoable);
122 job.folder_level = folder_level;
123 ///ystem.err.println("Adding job: " + job);
124 if(position != -1 && position <= queue.size() + 1) {
125 queue.add(position, job);
126 }
127 else {
128 queue.add(job);
129 }
130 notify();
131 }
132
133 /** Calculates the total deep file size of the selected file nodes.
134 * @param files a FileNode[] of selected files
135 * @return true if a cancel was signalled, false otherwise
136 * @see org.greenstone.gatherer.file.FileManager.Task#run()
137 */
138 public boolean calculateSize(FileNode[] files) {
139 progress.reset();
140 progress.setString(Dictionary.get("FileActions.Calculating_Size"));
141 progress.setIndeterminate(true);
142 Vector remaining = new Vector();
143 for(int i = 0; !cancel_action && i < files.length; i++) {
144 remaining.add(files[i]);
145 }
146 while(!cancel_action && remaining.size() > 0) {
147 FileNode node = (FileNode)remaining.remove(0);
148 if(node.isLeaf()) {
149 progress.addMaximum(node.getFile().length());
150 }
151 else {
152 for(int i = 0; !cancel_action && i < node.getChildCount(); i++) {
153 remaining.add(node.getChildAt(i));
154 }
155 }
156 }
157 progress.setString(Dictionary.get("FileActions.No_Activity"));
158 progress.setIndeterminate(false);
159 // Now we return if calculation was cancelled so that the FileManagers Task can skip the addJob phase correctly.
160 if(cancel_action) {
161 cancel_action = false; // reset
162 return true;
163 }
164 else {
165 return false;
166 }
167 }
168
169 /** This method is called to cancel the job queue at the next available moment. */
170 public void cancelAction() {
171 cancel_action = true;
172 }
173 /** Access to the file state label. */
174 public JLabel getFileStatus() {
175 return file_status;
176 }
177 /** Access to the job state label. */
178// public JLabel getJobStatus() {
179// return job_status;
180// }
181 /** Access to the progress bar. */
182 public LongProgressBar getProgress() {
183 return progress;
184 }
185 /** Prevent the progress bar updating momentarily, while the progress bar size is re-adjusted. */
186 public void pause() {
187 progress.setIndeterminate(true);
188 }
189 /** 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.
190 * @see org.greenstone.gatherer.Gatherer
191 * @see org.greenstone.gatherer.collection.CollectionManager
192 * @see org.greenstone.gatherer.file.FileJob
193 * @see org.greenstone.gatherer.file.FileNode
194 * @see org.greenstone.gatherer.gui.LongProgressBar
195 * @see org.greenstone.gatherer.msm.MetadataSetManager
196 * @see org.greenstone.gatherer.undo.UndoManager
197 * @see org.greenstone.gatherer.util.Utility
198 */
199 public void run() {
200 super.setName("FileQueue");
201 while(!Gatherer.self.exit) {
202 try {
203 // Retrieve the next job
204 int position = queue.size() - 1;
205 FileJob job = removeJob(position);
206 if(job != null) {
207 ///ystem.err.println("Found job: " + job);
208 // The user can cancel this individual action at several places, so keep track if the state is 'ready' for the next step.
209 boolean ready = true;
210 FileNode origin_node = job.getOrigin();
211 FileNode destination_node = job.getDestination();
212 FileSystemModel source_model = (FileSystemModel)job.source.getTreeModel();
213 FileSystemModel target_model = (FileSystemModel)job.target.getTreeModel();
214 if(destination_node == null) {
215 // 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.
216 destination_node = (FileNode) target_model.getRoot();
217 }
218 // Extract common job details.
219 File source_file = origin_node.getFile();
220 File target_file = null;
221 // Determine the target file for a copy or move.
222 if(job.type == FileJob.COPY || job.type == FileJob.MOVE) {
223 //target_file = new File(destination_node.getFile(), source_file.getName());
224 // 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
225 target_file = new File(destination_node.getFile(), origin_node.toString());
226 }
227 // 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.
228 if((job.type == FileJob.COPY || job.type == FileJob.MOVE) && !job.done) {
229 ///ystem.err.println("Copy/Move: " + origin_node);
230 FileNode new_node = null;
231 // 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).
232 if(target_file.exists()) {
233 // We've previously been told
234 if(yes_to_all) {
235 // Remove the old file and tree entry.
236 target_file.delete();
237 ready = true;
238 }
239 else {
240 ///atherer.println("Opps! This filename already exists. Give the user some options.");
241 Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("FileActions.Yes_To_All"), Dictionary.get("General.No"), Dictionary.get("General.Cancel") };
242 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]);
243 switch(result) {
244 case 1: // Yes To All
245 yes_to_all = true;
246 case 0: // Yes
247 // Remove the old file and tree entry.
248 if(destination_node != null) {
249 TreePath destination_path = new TreePath(destination_node.getPath());
250 FileNode temp_target_node = new FileNode(target_file, target_model, true);
251 TreePath target_path = destination_path.pathByAddingChild(temp_target_node);
252 SynchronizedTreeModelTools.removeNodeFromParent(target_model, target_model.getNode(target_path));
253 target_path = null;
254 temp_target_node = null;
255 destination_path = null;
256 }
257 target_file.delete();
258 ready = true;
259 break;
260 case 3: // No To All
261 cancel_action = true;
262 case 2: // No
263 default:
264 ready = false;
265 // Increment progress by size of potentially copied file
266 progress.addValue(origin_node.getFile().length());
267 }
268 }
269 }
270 // 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.
271 if(ready) {
272 // update status area
273 String args[] = new String[1];
274 args[0] = "" + (queue.size() + 1) + "";
275 if(job.type == FileJob.COPY) {
276 args[0] = Utility.formatPath("FileActions.Copying", source_file.getAbsolutePath(), file_status.getSize().width);
277 file_status.setText(Dictionary.get("FileActions.Copying", args));
278 }
279 else {
280 args[0] = Utility.formatPath("FileActions.Moving", source_file.getAbsolutePath(), file_status.getSize().width);
281 file_status.setText(Dictionary.get("FileActions.Moving", args));
282 }
283 args = null;
284
285 // If source is a file
286 if(source_file.isFile()) {
287 // 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?
288 try {
289 copyFile(source_file, target_file, progress);
290 }
291 // 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.
292 catch(FileNotFoundException fnf_exception) {
293 Gatherer.printStackTrace(fnf_exception);
294 cancel_action = true;
295 // Show warning.
296 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);
297 // Force refresh of source folder.
298 source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
299 }
300 catch(FileAlreadyExistsException fae_exception) {
301 Gatherer.printStackTrace(fae_exception);
302 cancel_action = true;
303 // Show warning.
304 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);
305 // Nothing else can be done by the Gatherer.
306 }
307 catch(InsufficientSpaceException is_exception) {
308 Gatherer.printStackTrace(is_exception);
309 cancel_action = true;
310 // Show warning. The message body of the expection explains how much more space is required for this file copy.
311 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Insufficient_Space_Message", is_exception.getMessage()), Dictionary.get("FileActions.Insufficient_Space_Title"), JOptionPane.ERROR_MESSAGE);
312 // 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.
313 }
314 catch(UnknownFileErrorException ufe_exception) {
315 Gatherer.printStackTrace(ufe_exception);
316 cancel_action = true;
317 // Show warning
318 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Unknown_File_Error_Message"), Dictionary.get("FileActions.Unknown_File_Error_Title"), JOptionPane.ERROR_MESSAGE);
319 // Nothing else we can do.
320 }
321 catch(WriteNotPermittedException wnp_exception) {
322 Gatherer.printStackTrace(wnp_exception);
323 cancel_action = true;
324 // Show warning
325 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);
326 // Nothing else we can do.
327 }
328 catch(IOException exception) {
329 // Can't really do much about this.
330 Gatherer.printStackTrace(exception);
331 }
332 // If not cancelled
333 if(!cancel_action) {
334 // Step one is to create a dummy FileNode. Its important it has the correct structure so getPath works.
335 FileNode new_record = new FileNode(target_file);
336 SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, new_record);
337 new_node = new_record;
338
339 // create undo job
340 if(job.undoable) {
341 job.undoable = false;
342 if(job.type == FileJob.COPY) {
343 // 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!
344 Gatherer.c_man.undo.addUndo(job.ID(), UndoManager.FILE_COPY, null, null, job.target, new_record, job.undo);
345 }
346 else {
347 // Movements however do need a source and source parent so the file can be moved back to the correct place.
348 Gatherer.c_man.undo.addUndo(job.ID(), UndoManager.FILE_MOVE, job.source, (FileNode)origin_node.getParent(), job.target, new_record, job.undo);
349 }
350 }
351 new_record = null;
352 }
353 }
354 // Else
355 else if(source_file.isDirectory()) {
356 // create new record
357 FileNode directory_record = new FileNode(target_file);
358 ///ystem.err.println("Directory record = " + directory_record + " (" + target_file.getAbsolutePath() + ")");
359 SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, directory_record);
360 // Why is this not happening eh?
361 directory_record.setParent(destination_node);
362 if(!target_file.exists()) {
363 // make the directory
364 target_file.mkdirs();
365 new_node = directory_record;
366 // create undo job
367 if(job.undoable) {
368 job.undoable = false;
369 if(job.type == FileJob.COPY) {
370 // 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!
371 Gatherer.c_man.undo.addUndo(job.ID(), UndoManager.FILE_COPY, null, null, job.target, directory_record, job.undo);
372 }
373 else {
374 // Movements however do need a source and source parent so the file can be moved back to the correct place.
375 Gatherer.c_man.undo.addUndo(job.ID(), UndoManager.FILE_MOVE, job.source, (FileNode)origin_node.getParent(), job.target, directory_record, job.undo);
376 }
377 }
378 }
379 // Else inform the users that a directory already exists and files will be copied into it
380 //else {
381 // JOptionPane.showMessageDialog(null, Dictionary.get("FileActions.Directory_Exists", target_file.toString()), Dictionary.get("General.Warning"), JOptionPane.WARNING_MESSAGE);
382 //}
383 // 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.
384 FileNode child_record = null;
385 // 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.
386 // -- Starting queue ...[a]
387 // remove(position) = 'a' ...
388 // add(position, 'b') ...[b]
389 // add(position, 'c') ...[c][b]
390 // add(position, 'd') ...[d][c][b]
391 // Next loop
392 // remove(position) = 'b' ...[d][c]
393 for(int i = 0; i < origin_node.getChildCount(); i++) {
394 child_record = (FileNode) origin_node.getChildAt(i);
395 addJob(job.ID(), job.source, child_record, job.target, directory_record, job.type, job.undo, false, false, position);
396 }
397 child_record = null;
398 directory_record = null;
399 }
400 // The file wasn't found!
401 else {
402 cancel_action = true;
403 // Show warning.
404 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);
405 // Force refresh of source folder.
406 source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
407 }
408
409 // We can't have been cancelled, and we must have created a new FileNode during the above phase, before we can handle metadata.
410 if(!cancel_action && new_node != null) {
411 /* Time to handle any existing metadata. */
412 // If the directory came from inside our collection...
413 if (job.source.toString().equals("Collection")) {
414 ///ystem.err.println("Move within collection...");
415 GDMManager gdm = Gatherer.c_man.getCollection().gdm;
416 // we just retrieve the metadata attached to the origin node...
417 ArrayList existing_metadata = gdm.getMetadataOnly(source_file);
418 //Gatherer.println("Existing metadata for " + origin_node + ": " + gdm.toString(existing_metadata));
419 // then assign this remainder to the new folder.
420 ///ystem.err.println("New metadata: " + gdm.toString(existing_metadata));
421 gdm.addMetadata(new_node, existing_metadata);
422 existing_metadata = null;
423 gdm = null;
424 }
425 // If it came from the recycle bin retrieve the metadata from there, once again remembering to account for inherited metadata
426 else if (job.source.toString().equals("Undo")) {
427 GDMManager gdm = Gatherer.c_man.getCollection().gdm;
428 // Retrieve metadata from the recycle bin
429 ArrayList existing_metadata = Gatherer.c_man.undo.getMetadata(source_file);
430 // then assign this remainder to the new folder.
431 gdm.addMetadata(new_node, existing_metadata);
432 existing_metadata = null;
433 gdm = null;
434 }
435 // Otherwise if it came from the workspace use the MSMs parsers to search for folder level metadata (such as metadata.xml or marc records).
436 else if (job.source.toString().equals("Workspace")) {
437 cancel_action = Gatherer.c_man.getCollection().msm.searchForMetadata(new_node, origin_node, job.folder_level);
438 }
439 }
440 new_node = null;
441
442 }
443 }
444 // 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.
445 if(!cancel_action && ready && (job.type == FileJob.DELETE || job.type == FileJob.MOVE)) {
446 ///ystem.err.print("Delete/Move: " + origin_node + " -> ");
447 // If the source is an empty directory or a file. Don't do anything to the root node of a tree.
448 File[] child_list = source_file.listFiles();
449 if(source_file.isFile() || (child_list != null && (child_list.length == 0 || (child_list.length == 1 && child_list[0].getName().equals(Utility.METADATA_XML))) && origin_node.getParent() != null)) {
450 ///ystem.err.println("File or empty directory.");
451 // Delete any metadata.xml still in the directory.
452 if(child_list != null && child_list.length == 1) {
453 child_list[0].delete();
454 }
455
456 ///ystem.err.println("Origin is file or is directory and is empty.");
457 // update status area
458 String args[] = new String[1];
459 args[0] = "" + (queue.size() + 1) + "";
460 //job_status.setText(Dictionary.get("FileActions.Jobs", args));
461 args[0] = Utility.formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width);
462 file_status.setText(Dictionary.get("FileActions.Deleting", args));
463 args = null;
464
465 // Remove its metadata
466 ArrayList metadatum = null;
467 if(job.source == Gatherer.c_man.undo) {
468 Gatherer.c_man.undo.addMetadata(target_file, metadatum);
469 }
470 else {
471 metadatum = Gatherer.c_man.getCollection().gdm.removeMetadata(origin_node.getFile());
472 }
473 // determine its parent node
474 FileNode parent_record = (FileNode)origin_node.getParent();
475 // Remove from model
476 SynchronizedTreeModelTools.removeNodeFromParent(source_model, origin_node);
477 // If we are deleting
478 File recycled_file = null;
479 FileNode recycled_parent = null;
480 if(job.type == FileJob.DELETE) {
481
482 /** If we ever decide to reenable undo then this code will have to be seriously improved.
483 // See if this record already has a previous recycle folder noted in the recycle folder mappings.
484 recycled_parent = (FileNode) recycle_folder_mappings.get(origin_node);
485 if(recycled_parent != null) {
486 recycle_folder_mappings.remove(origin_node);
487 }
488 else {
489 recycled_parent = (FileNode) Gatherer.c_man.undo.getTreeModel().getRoot();
490 }
491 // This may be a directory which we have already added previously.
492 if(completed_folder_mappings.containsKey(origin_node)) {
493 FileNode recycled_record = (FileNode) completed_folder_mappings.get(origin_node);
494 // Replace the temporary directory record in the undo tree with this one.
495 SynchronizedTreeModelTools.replaceNode(Gatherer.c_man.undo.getTreeModel(), recycled_record, origin_node);
496 origin_node.setFile(recycled_record.getFile());
497 }
498 else {
499 // copy the file to the recycle bin
500 recycled_file = new File(recycled_parent.getFile(), origin_node.toString());
501 // If the file already exists, delete it.
502 if(recycled_file.exists()) {
503 recycled_file.delete();
504 }
505 recycled_file.deleteOnExit();
506 copyFile(source_file, recycled_file, progress);
507 origin_node.setFile(recycled_file);
508 // Add the node to the appropriate place in the UndoManagers tree model. Unfortunately this one does have the possibility of altering the GUI (if the removeNodeFromParent above hasn't occured yet), so we must put it on the queue.
509 SynchronizedTreeModelTools.insertNodeInto(Gatherer.c_man.undo.getTreeModel(), recycled_parent, origin_node);
510 }
511 Gatherer.c_man.undo.addMetadata(source_file, metadatum);
512 **/
513 }
514 // delete the source file
515 Utility.delete(source_file);
516 /**
517 // create undo job as necessary. File move would have been handled above.
518 if(job.undoable) {
519 job.undoable = false;
520 // The target is null, indicating that we moved this file to the recycle bin. The UndoManager will replace null with 'this'.
521 Gatherer.c_man.undo.addUndo(job.ID(), UndoManager.FILE_DELETE, job.source, parent_record, null, origin_node, job.undo);
522 }
523 recycled_parent = null;
524 recycled_file = null;
525 **/
526 //metadatum = null;
527 }
528 // Else the source is a directory and it has children remaining
529 else if(child_list != null && child_list.length > 0) {
530 ///ystem.err.print("Nonempty directory -> ");
531 ///ystem.err.println("Directory is non-empty. Remove children first.");
532 FileNode recycle_folder_record = null;
533 // Don't worry about all this for true file move actions.
534 if(job.type == FileJob.DELETE) {
535 /** Again, if we reenable undo then this code must be debugged.
536 // See if this record already has a previous recycle folder noted in the recycle folder mappings.
537 FileNode parent = (FileNode) recycle_folder_mappings.get(origin_node);
538 if(parent != null) {
539 recycle_folder_mappings.remove(origin_node);
540 }
541 else {
542 parent = (FileNode) Gatherer.c_man.undo.getTreeModel().getRoot();
543 }
544 // We must add the folder node to our undo manager tree now, so we'll have something to add children to. We use a copy of the directory file record.
545 File recycle_folder = new File(parent.getFile(), origin_node.toString());
546 recycle_folder.deleteOnExit();
547 recycle_folder.mkdirs();
548 recycle_folder_record = new FileNode(recycle_folder);
549 // Add this node to the undo tree model.
550 SynchronizedTreeModelTools.insertNodeInto(Gatherer.c_man.undo.getTreeModel(), parent, recycle_folder_record);
551 // We add an entry to the complete mappings to ensure this directory isn't added again
552 completed_folder_mappings.put(origin_node, recycle_folder_record);
553 ///ystem.err.println("Added completed directories mapping " + origin_node);
554 **/
555 // 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.
556 ///ystem.err.println("Directory has " + origin_node.getChildCount() + " children.");
557 ///ystem.err.println("Directory actually has " + child_list.length + " children.");
558 origin_node.unmap();
559 origin_node.map();
560 ///ystem.err.println("Directory has " + origin_node.getChildCount() + " children.");
561 ///ystem.err.println("Directory actually has " + child_list.length + " children.");
562 for(int i = 0; i < origin_node.getChildCount(); i++) {
563 FileNode child_record = (FileNode) origin_node.getChildAt(i);
564 addJob(job.ID(), job.source, child_record, job.target, destination_node, FileJob.DELETE, job.undo, false, false, position);
565 //if(recycle_folder_record != null) {
566 // recycle_folder_mappings.put(child_record, recycle_folder_record);
567 //}
568 }
569
570 }
571 // 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.
572 // One special case. Do not requeue root nodes. Don't requeue jobs marked as done.
573 if(origin_node.getParent() != null && !job.done) {
574 System.err.println("Requeuing: " + origin_node.getFile().getAbsolutePath());
575 job.type = FileJob.DELETE; // You only requeue jobs that are deletes, as directories must be inspected before children, but deleted after.
576 addJob(job, position);
577 }
578 else {
579 System.err.println("I've already done this job twice. I refuse to requeue it again!!!");
580 }
581 }
582 }
583 job = null;
584 source_file = null;
585 target_file = null;
586 origin_node = null;
587 // We can only break out of the while loop if we are out of files, or if the action was cancelled.
588 if(cancel_action) {
589 // Empty queue
590 clearJobs();
591 cancel_action = false;
592 }
593 // Debugging pause.
594 ///ystem.err.println("Job complete.");
595 }
596 else {
597 synchronized(this) {
598 ///ystem.err.println("Queue size = " + queue.size());
599 // Force the trees to refresh (but only if there is something on screen!)
600 if(Gatherer.g_man != null) {
601 Gatherer.g_man.refreshTrees();
602 }
603 // Reset status area
604 //job_status.setText(Dictionary.get("No_Selection"));
605 file_status.setText(Dictionary.get("FileActions.No_Activity"));
606 progress.reset();
607 progress.setString(Dictionary.get("FileActions.No_Activity"));
608 yes_to_all = false;
609 completed_folder_mappings.clear();
610 recycle_folder_mappings.clear();
611 // Now wait if applicable.
612 if(return_immediately) {
613 return;
614 }
615 ///ystem.err.println("Waiting");
616 wait();
617 }
618 }
619 }
620 catch (Exception error) {
621 Gatherer.printStackTrace(error);
622 }
623 }
624 }
625 /** A second lock is necessary to prevent the thread waiting, because its notify occured momentarily before it waited. If the flag is set then the thread can't wait, but loops around. This may chew processor time so should only be used if you are certain files are about to be placed on the queue.
626 * @param wait_allowed The new state of the wait_allowed flag, as a boolean.
627 */
628 /* private void setWaitAllowed(boolean wait_allowed) {
629 this.wait_allowed = wait_allowed;
630 } */
631 /** Restore the progress bar so that it updates normally.
632 * @see org.greenstone.gatherer.gui.LongProgressBar
633 */
634 /* synchronized private void unpause() {
635 progress.setIndeterminate(false);
636 if(previous != null) {
637 progress.setString(previous);
638 previous = null;
639 }
640 } */
641 /** Called when the user makes some selection in one of the trees we are listening to. From this we update the status details. */
642 public void valueChanged(TreeSelectionEvent event) {
643 JTree tree = (JTree) event.getSource();
644 if(tree.getSelectionCount() > 0) {
645 TreePath selection[] = tree.getSelectionPaths();
646 int file_count = 0;
647 int dir_count = 0;
648 for(int i = 0; i < selection.length; i++) {
649 TreeNode record = (TreeNode) selection[i].getLastPathComponent();
650 if(record.isLeaf()) {
651 file_count++;
652 }
653 else {
654 dir_count++;
655 }
656 record = null;
657 }
658 selection = null;
659 // String args[] = new String[2];
660 // args[0] = "" + file_count + "";
661 // args[1] = "" + dir_count + "";
662 // job_status.setText(get("Selected", args));
663 // args = null;
664 }
665 tree = null;
666 }
667
668 synchronized private void clearJobs() {
669 queue.clear();
670 }
671
672 /** Copy a file from the source location to the destination location.
673 * @param source The source File.
674 * @param destination The destination File.
675 * @see org.greenstone.gatherer.Gatherer
676 */
677 public void copyFile(File source, File destination, LongProgressBar progress)
678 throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, UnknownFileErrorException, WriteNotPermittedException {
679 if(source.isDirectory()) {
680 destination.mkdirs();
681 }
682 else {
683 // Check if the origin file exists.
684 if(!source.exists()) {
685 System.err.println("Couldn't find the source file.");
686 throw(new FileNotFoundException());
687 }
688 // Check if the destination file does not exist.
689 if(destination.exists()) {
690 throw(new FileAlreadyExistsException());
691 }
692 File dirs = destination.getParentFile();
693 dirs.mkdirs();
694 // Copy the file.
695 FileInputStream f_in = new FileInputStream(source);
696 FileOutputStream f_out = null;
697 // This may throw a file not found exception, but this translates to a WriteNotPermittedException, in this case
698 try {
699 f_out = new FileOutputStream(destination);
700 }
701 catch (FileNotFoundException exception) {
702 throw new WriteNotPermittedException(exception.toString());
703 }
704 byte data[] = new byte[Utility.BUFFER_SIZE];
705 int data_size = 0;
706 while((data_size = f_in.read(data, 0, Utility.BUFFER_SIZE)) != -1 && !cancel_action) {
707 long destination_size = destination.length();
708 try {
709 f_out.write(data, 0, data_size);
710 }
711 // 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.
712 catch (IOException io_exception) {
713 if(destination_size + (long) data_size > destination.length()) {
714 // Determine the difference (which I guess is in bytes).
715 long difference = (destination_size + (long) data_size) - destination.length();
716 // Transform that into a human readable string.
717 String message = Utility.formatFileLength(difference);
718 throw(new InsufficientSpaceException(message));
719 }
720 else {
721 throw(io_exception);
722 }
723 }
724 if(progress != null) {
725 progress.addValue(data_size);
726 }
727 }
728 // Flush and close the streams to ensure all bytes are written.
729 f_in.close();
730 f_out.close();
731 // We have now, in theory, produced an exact copy of the source file. Check this by comparing sizes.
732 if(!destination.exists() || (!cancel_action && source.length() != destination.length())) {
733 throw(new UnknownFileErrorException());
734 }
735 // If we were cancelled, ensure that none of the destination file exists.
736 if(cancel_action) {
737 destination.delete();
738 }
739 }
740 }
741
742
743 private FileJob removeJob(int position) {
744 FileJob job = null;
745 if(queue.size() > 0) {
746 job = (FileJob) queue.remove(position);
747 }
748 return job;
749 }
750}
Note: See TracBrowser for help on using the repository browser.