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

Last change on this file since 11388 was 11388, checked in by mdewsnip, 18 years ago

Minor improvement to previous change.

  • Property svn:keywords set to Author Date Id Revision
File size: 51.6 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.collection.CollectionTreeNode;
39import org.greenstone.gatherer.gui.GProgressBar;
40import org.greenstone.gatherer.gui.tree.DragTree;
41import org.greenstone.gatherer.metadata.MetadataValue;
42import org.greenstone.gatherer.metadata.MetadataXMLFileManager;
43import org.greenstone.gatherer.util.DragComponent;
44import org.greenstone.gatherer.util.StaticStrings;
45import org.greenstone.gatherer.util.SynchronizedTreeModelTools;
46import org.greenstone.gatherer.util.Utility;
47
48/** 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.
49 * @author John Thompson, Greenstone Digital Library, University of Waikato
50 * @version 2.3
51 */
52public class FileQueue
53 extends Thread
54{
55 /** When someone requests the movement queue to be dumped this cancel flag is set to true. */
56 private boolean cancel_action = false;
57 /** The button which controls the stopping of the file queue. */
58 private JButton stop_button = null;
59 /** true if the user has selected yes to all from a file 'clash' dialog. */
60 private boolean yes_to_all = false;
61 /** A label explaining the current moving files status. */
62 private JLabel file_status = null;
63 /** A list containing a queue of waiting movement jobs. */
64 private ArrayList queue = null;
65 /** A progress bar which shows how many bytes, out of the total size of bytes, has been moved. */
66 private GProgressBar progress = null;
67
68
69 /** Constructor.
70 */
71 public FileQueue() {
72 DebugStream.println("FileQueue started.");
73 this.queue = new ArrayList();
74 file_status = new JLabel();
75 Dictionary.setText(file_status, "FileActions.No_Activity");
76 progress = new GProgressBar();
77 progress.setBackground(Configuration.getColor("coloring.collection_tree_background", false));
78 progress.setForeground(Configuration.getColor("coloring.collection_tree_foreground", false));
79 progress.setString(Dictionary.get("FileActions.No_Activity"));
80 progress.setStringPainted(true);
81 }
82
83 /** Requeue an existing job into the queue.
84 * @param job A previously created FileJob.
85 */
86// synchronized private void addJob(FileJob job, int position) {
87// job.done = true; // Ensure that the requeued job is marked as done.
88// queue.add(position, job);
89// notify();
90// }
91
92 /** 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).
93 * @param id A long id unique to all jobs created by a single action.
94 * @param source The DragComponent source of this file, most likely a DragTree.
95 * @param child The FileNode you wish to mode.
96 * @param target The DragComponent to move the file to, again most likely a DragTree.
97 * @param parent The files new FileNode parent within the target.
98 * @param type The type of this movement as an int, either COPY or DELETE.
99 */
100 public void addJob(long id, DragComponent source, FileNode[] children, DragComponent target, FileNode parent, byte type)
101 {
102 // Queue the sub-job(s) (this may fail if we are asked to delete a read only file)
103 for (int i = 0; i < children.length; i++) {
104 addJob(id, source, children[i], target, parent, type, -1);
105 }
106 }
107
108 synchronized private void addJob(long id, DragComponent source, FileNode child, DragComponent target, FileNode parent, byte type, int position) {
109 FileJob job = new FileJob(id, source, child, target, parent, type);
110 DebugStream.println("Adding job: " + job);
111 if(position != -1 && position <= queue.size() + 1) {
112 queue.add(position, job);
113 }
114 else {
115 queue.add(job);
116 }
117 notify();
118 }
119
120 /** Calculates the total deep file size of the selected file nodes.
121 * @param files a FileNode[] of selected files
122 * @return true if a cancel was signalled, false otherwise
123 * @see org.greenstone.gatherer.file.FileManager.Task#run()
124 */
125 public boolean calculateSize(FileNode[] files)
126 {
127 file_status.setText(Dictionary.get("FileActions.Calculating_Size"));
128 progress.setString(Dictionary.get("FileActions.Calculating_Size"));
129
130 // Calculate the total file size of all the selected file nodes
131 Vector remaining = new Vector();
132 for (int i = 0; !cancel_action && i < files.length; i++) {
133 remaining.add(files[i]);
134 }
135 while (!cancel_action && remaining.size() > 0) {
136 FileNode node = (FileNode) remaining.remove(0);
137 if (node.isLeaf()) {
138 progress.addMaximum(node.getFile().length());
139 }
140 else {
141 for (int i = 0; !cancel_action && i < node.getChildCount(); i++) {
142 remaining.add(node.getChildAt(i));
143 }
144 }
145 }
146
147 // Now we return if calculation was cancelled so that the FileManagers Task can skip the addJob phase correctly.
148 if (cancel_action) {
149 cancel_action = false; // reset
150 return true;
151 }
152 else {
153 return false;
154 }
155 }
156
157 /** This method is called to cancel the job queue at the next available moment. */
158 public void cancelAction() {
159 cancel_action = true;
160 clearJobs();
161 }
162
163
164// private int countFolderDepth(File file)
165// {
166// int depth = 0;
167// while (file != null) {
168// depth++;
169// file = file.getParentFile();
170// }
171// return depth;
172// }
173
174
175 /** Format the given filename path string so that it is no longer than the given width. If it is wider replace starting directories with ...
176 * @param key The key <strong>String</Strong> used to retrieve a phrase from the dictionary for this item.
177 * @param raw The raw filename path <strong>String</strong>.
178 * @param width The maximum width as an <i>int</i>.
179 * @return A path <strong>String</strong> no longer than width.
180 */
181 private String formatPath(String key, String raw, int width)
182 {
183 JLabel label = new JLabel(Dictionary.get(key, raw));
184 int position = -1;
185 while(label.getPreferredSize().width > width && (position = raw.indexOf(File.separator)) != -1) {
186 raw = "..." + raw.substring(position + 1);
187 label.setText(Dictionary.get(key, raw));
188 }
189 if(raw.indexOf(File.separator) == -1 && raw.startsWith("...")) {
190 raw = raw.substring(3);
191 }
192 return raw;
193 }
194
195
196 /** Access to the file state label. */
197 public JLabel getFileStatus() {
198 return file_status;
199 }
200
201 /** Access to the progress bar. */
202 public GProgressBar getProgressBar() {
203 return progress;
204 }
205
206
207 synchronized private void addFileJob(long id, DragComponent source, FileNode child, DragComponent target, FileNode parent, byte type)
208 {
209 queue.add(new FileJob(id, source, child, target, parent, type));
210 notify();
211 }
212
213
214 private void doEmptyDirectoryDelete(FileJob file_job)
215 {
216 FileNode source_node = file_job.getOrigin();
217 File source_directory = source_node.getFile();
218
219 // If the directory isn't empty then this will fail
220 if (source_directory.delete() == false) {
221 // The source directory couldn't be deleted, so give the user the option of continuing or cancelling
222 if (showErrorDialog(Dictionary.get("FileActions.Could_Not_Delete", source_directory.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
223 clearJobs(); // Aborting action
224 }
225 return;
226 }
227
228 // Remove the node from the model
229 SynchronizedTreeModelTools.removeNodeFromParent(file_job.source.getTreeModel(), source_node);
230 }
231
232
233 private void doDirectoryDelete(FileJob file_job)
234 {
235 FileNode source_node = file_job.getOrigin();
236 File source_directory = source_node.getFile();
237
238 // The last thing we will do is delete this directory (which should be empty by then)
239 addFileJob(file_job.ID(), file_job.source, source_node, null, null, FileJob.DELETE_EMPTY_DIRECTORY);
240
241 // Add a new Delete job for each child of this directory (except metadata.xml files)
242 source_node.refresh();
243 for (int i = 0; i < source_node.size(); i++) {
244 FileNode child_file_node = (FileNode) source_node.getChildAtUnfiltered(i);
245 if (!child_file_node.getFile().getName().equals(StaticStrings.METADATA_XML)) {
246 addFileJob(file_job.ID(), file_job.source, child_file_node, null, null, FileJob.DELETE);
247 }
248 }
249
250 // Treat metadata.xml files specially: delete them first
251 for (int i = 0; i < source_node.size(); i++) {
252 FileNode child_file_node = (FileNode) source_node.getChildAtUnfiltered(i);
253 if (child_file_node.getFile().getName().equals(StaticStrings.METADATA_XML)) {
254 addFileJob(file_job.ID(), file_job.source, child_file_node, null, null, FileJob.DELETE);
255 break;
256 }
257 }
258 }
259
260
261 private void doDirectoryCopy(FileJob file_job)
262 {
263 FileNode source_node = file_job.getOrigin();
264 FileNode target_node = file_job.getDestination();
265
266 File source_directory = source_node.getFile();
267 File target_directory = new File(target_node.getFile(), source_directory.getName());
268
269 // Check that the source directory doesn't contain the target directory (will create a cyclic loop)
270 if (target_directory.getAbsolutePath().startsWith(source_directory.getAbsolutePath())) {
271 if (showErrorDialog(Dictionary.get("FileActions.Cyclic_Path", source_directory.getName())) == JOptionPane.CANCEL_OPTION) {
272 clearJobs(); // Aborting action
273 }
274 return;
275 }
276
277 // The target directory shouldn't already exist
278 if (target_directory.exists()) {
279 if (showErrorDialog(Dictionary.get("FileActions.Folder_Already_Exists", target_directory.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
280 clearJobs(); // Aborting action
281 }
282 return;
283 }
284 target_directory.mkdirs();
285
286 // Create a node for the new directory in the collection tree
287 FileSystemModel target_model = (FileSystemModel) file_job.target.getTreeModel();
288 CollectionTreeNode new_target_node = new CollectionTreeNode(target_directory);
289 SynchronizedTreeModelTools.insertNodeInto(target_model, target_node, new_target_node);
290 new_target_node.setParent(target_node);
291
292 // Copy the non-folder level metadata assigned to the original directory to the new directory
293 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToExternalFile(source_directory);
294 MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_target_node, assigned_metadata);
295
296 // Add a new Copy job for each child of this directory (except metadata.xml files)
297 source_node.refresh();
298 for (int i = 0; i < source_node.size(); i++) {
299 FileNode child_file_node = (FileNode) source_node.getChildAtUnfiltered(i);
300 if (!child_file_node.getFile().getName().equals(StaticStrings.METADATA_XML)) {
301 addFileJob(file_job.ID(), file_job.source, child_file_node, file_job.target, new_target_node, FileJob.COPY);
302 }
303 }
304 }
305
306
307 private void doDirectoryMove(FileJob file_job)
308 {
309 FileNode source_node = file_job.getOrigin();
310 FileNode target_node = file_job.getDestination();
311
312 File source_directory = source_node.getFile();
313 File target_directory = new File(target_node.getFile(), source_directory.getName());
314 if (file_job.type == FileJob.RENAME) {
315 // This is the only difference between moves and renames
316 target_directory = target_node.getFile();
317 target_node = (FileNode) source_node.getParent();
318 }
319
320 // Check the target directory isn't the source directory
321 if (target_directory.equals(source_directory)) {
322 DebugStream.println("Target directory is the source directory!");
323 return;
324 }
325
326 // The target directory shouldn't already exist
327 if (target_directory.exists()) {
328 if (showErrorDialog(Dictionary.get("FileActions.Folder_Already_Exists", target_directory.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
329 clearJobs(); // Aborting action
330 }
331 return;
332 }
333 target_directory.mkdirs();
334
335 // Create a node for the new directory in the collection tree
336 FileSystemModel target_model = (FileSystemModel) file_job.target.getTreeModel();
337 CollectionTreeNode new_target_node = new CollectionTreeNode(target_directory);
338 SynchronizedTreeModelTools.insertNodeInto(target_model, target_node, new_target_node);
339 new_target_node.setParent(target_node);
340
341 // Move the folder level metadata assigned to the original directory to the new directory
342 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_directory);
343 MetadataXMLFileManager.removeMetadata((CollectionTreeNode) source_node, assigned_metadata);
344 MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_target_node, assigned_metadata);
345
346 // The last thing we will do is delete this directory
347 addFileJob(file_job.ID(), file_job.source, source_node, null, null, FileJob.DELETE);
348
349 // Treat metadata.xml files specially: delete them last
350 source_node.refresh();
351 for (int i = 0; i < source_node.size(); i++) {
352 FileNode child_file_node = (FileNode) source_node.getChildAtUnfiltered(i);
353 if (child_file_node.getFile().getName().equals(StaticStrings.METADATA_XML)) {
354 addFileJob(file_job.ID(), file_job.source, child_file_node, null, null, FileJob.DELETE);
355 break;
356 }
357 }
358
359 // Add a new Move job for each child of this directory (except metadata.xml files)
360 for (int i = 0; i < source_node.size(); i++) {
361 FileNode child_file_node = (FileNode) source_node.getChildAtUnfiltered(i);
362 if (!child_file_node.getFile().getName().equals(StaticStrings.METADATA_XML)) {
363 addFileJob(file_job.ID(), file_job.source, child_file_node, file_job.target, new_target_node, FileJob.MOVE);
364 }
365 }
366 }
367
368
369 private void doFileDelete(FileJob file_job)
370 {
371 FileNode source_node = file_job.getOrigin();
372 File source_file = source_node.getFile();
373
374 // If we're deleting a metadata.xml file we must unload it
375 boolean metadata_xml_file = source_file.getName().equals(StaticStrings.METADATA_XML);
376 if (metadata_xml_file) {
377 MetadataXMLFileManager.unloadMetadataXMLFile(source_file);
378 }
379 // Otherwise remove any metadata assigned directly to the file
380 else {
381 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
382 MetadataXMLFileManager.removeMetadata((CollectionTreeNode) source_node, assigned_metadata);
383 }
384
385 // Delete the source file
386 if (!Utility.delete(source_file)) {
387 // The source file couldn't be deleted, so give the user the option of continuing or cancelling
388 if (showErrorDialog(Dictionary.get("FileActions.File_Not_Deleted_Message", source_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
389 clearJobs(); // Aborting action
390 }
391 return;
392 }
393
394 // Remove the node from the model
395 SynchronizedTreeModelTools.removeNodeFromParent(file_job.source.getTreeModel(), source_node);
396 }
397
398
399 private void doFileCopy(FileJob file_job)
400 {
401 FileNode source_node = file_job.getOrigin();
402 FileNode target_node = file_job.getDestination();
403
404 File source_file = source_node.getFile();
405 File target_file = new File(target_node.getFile(), source_file.getName());
406
407 // The target file shouldn't already exist -- if it does ask the user whether they want to overwrite
408 boolean overwrite_file = false;
409 if (target_file.exists()) {
410 int result = showOverwriteDialog(target_file.getName());
411 if (result == JOptionPane.NO_OPTION) {
412 // Don't overwrite
413 return;
414 }
415 if (result == JOptionPane.CANCEL_OPTION) {
416 clearJobs(); // Aborting action
417 return;
418 }
419
420 overwrite_file = true;
421 }
422
423 // Copy the file
424 try {
425 copyFile(source_file, target_file, true);
426 }
427 catch (FileAlreadyExistsException exception) {
428 // This should not ever happen, since we've called copyFile with overwrite set
429 DebugStream.printStackTrace(exception);
430 return;
431 }
432 catch (FileNotFoundException exception) {
433 DebugStream.printStackTrace(exception);
434 if (showErrorDialog(Dictionary.get("FileActions.File_Not_Found_Message", source_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
435 clearJobs(); // Aborting action
436 }
437 // Refresh the source tree model
438 FileSystemModel source_model = file_job.source.getTreeModel();
439 source_model.refresh(new TreePath(((FileNode) file_job.getOrigin().getParent()).getPath()));
440 return;
441 }
442 catch (InsufficientSpaceException exception) {
443 DebugStream.printStackTrace(exception);
444 if (showErrorDialog(Dictionary.get("FileActions.Insufficient_Space_Message", exception.getMessage())) == JOptionPane.CANCEL_OPTION) {
445 clearJobs(); // Aborting action
446 }
447 return;
448 }
449 catch (IOException exception) {
450 DebugStream.printStackTrace(exception);
451 if (showErrorDialog(exception.getMessage()) == JOptionPane.CANCEL_OPTION) {
452 clearJobs(); // Aborting action
453 }
454 return;
455 }
456 catch (ReadNotPermittedException exception) {
457 DebugStream.printStackTrace(exception);
458 if (showErrorDialog(Dictionary.get("FileActions.Read_Not_Permitted_Message", source_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
459 clearJobs(); // Aborting action
460 }
461 return;
462 }
463 catch (UnknownFileErrorException exception) {
464 DebugStream.printStackTrace(exception);
465 if (showErrorDialog(Dictionary.get("FileActions.Unknown_File_Error_Message")) == JOptionPane.CANCEL_OPTION) {
466 clearJobs(); // Aborting action
467 }
468 return;
469 }
470 catch (WriteNotPermittedException exception) {
471 DebugStream.printStackTrace(exception);
472 if (showErrorDialog(Dictionary.get("FileActions.Write_Not_Permitted_Message", target_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
473 clearJobs(); // Aborting action
474 }
475 return;
476 }
477
478 CollectionTreeNode new_target_node = new CollectionTreeNode(target_file);
479 if (overwrite_file == false) {
480 // Add the new node into the tree
481 FileSystemModel target_model = file_job.target.getTreeModel();
482 SynchronizedTreeModelTools.insertNodeInto(target_model, target_node, new_target_node);
483 }
484 Gatherer.c_man.fireFileAddedToCollection(target_file);
485
486 // Copy the non-folder level metadata assigned to the original file to the new file
487 if (file_job.type == FileJob.COPY) {
488 // do metadata too
489 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToExternalFile(source_file);
490 MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_target_node, assigned_metadata);
491 }
492 }
493
494
495 private void doFileMove(FileJob file_job)
496 {
497 FileNode source_node = file_job.getOrigin();
498 FileNode target_node = file_job.getDestination();
499
500 File source_file = source_node.getFile();
501 File target_file = new File(target_node.getFile(), source_file.getName());
502 if (file_job.type == FileJob.RENAME) {
503 // This is the only difference between moves and renames
504 target_file = target_node.getFile();
505 target_node = (FileNode) source_node.getParent();
506 }
507
508 // Check the target file isn't the source file
509 if (target_file.equals(source_file)) {
510 DebugStream.println("Target file is the source file!");
511 return;
512 }
513
514 // The target file shouldn't already exist
515 if (target_file.exists()) {
516 int result = showOverwriteDialog(target_file.getName());
517 if (result == JOptionPane.NO_OPTION) {
518 // Don't overwrite
519 return;
520 }
521 if (result == JOptionPane.CANCEL_OPTION) {
522 clearJobs(); // Aborting action
523 return;
524 }
525 }
526
527 // Move the file by renaming it
528 if (!source_file.renameTo(target_file)) {
529 String args[] = { source_file.getName(), target_file.getAbsolutePath() };
530 if (showErrorDialog(Dictionary.get("FileActions.File_Move_Error_Message", args)) == JOptionPane.CANCEL_OPTION) {
531 clearJobs(); // Aborting action
532 }
533 return;
534 }
535
536 // Remove the node from the source model and add it to the target model
537 SynchronizedTreeModelTools.removeNodeFromParent(file_job.source.getTreeModel(), source_node);
538 CollectionTreeNode new_target_node = new CollectionTreeNode(target_file);
539 FileSystemModel target_model = file_job.target.getTreeModel();
540 SynchronizedTreeModelTools.insertNodeInto(target_model, target_node, new_target_node);
541
542 // Move the non-folder level metadata assigned to the original file to the new file
543 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
544 MetadataXMLFileManager.removeMetadata((CollectionTreeNode) source_node, assigned_metadata);
545 MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_target_node, assigned_metadata);
546 }
547
548
549 /** all this does is move the metadata, and delete the source */
550 private void doFileReplace(FileJob file_job)
551 {
552 FileNode source_node = file_job.getOrigin();
553 FileNode target_node = file_job.getDestination();
554
555 File source_file = source_node.getFile();
556 File target_file = target_node.getFile();
557
558 // Move the non-folder level metadata assigned to the original file to the new file
559 CollectionTreeNode new_target_node = new CollectionTreeNode(target_file);
560 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
561 MetadataXMLFileManager.removeMetadata((CollectionTreeNode) source_node, assigned_metadata);
562 MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_target_node, assigned_metadata);
563
564 // now delete the original
565 doFileDelete(file_job);
566 }
567
568
569 private void processFileJob(FileJob file_job)
570 {
571 DebugStream.println("Processing file job " + file_job + "...");
572
573 // Ensure that the source file exists
574 File source_file = file_job.getOrigin().getFile();
575 if (!source_file.exists()) {
576 // The source file doesn't exist, so give the user the option of continuing or cancelling
577 if (showErrorDialog(Dictionary.get("FileActions.File_Not_Found_Message", source_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
578 clearJobs(); // Aborting action
579 }
580 // Refresh the source tree model
581 FileSystemModel source_model = file_job.source.getTreeModel();
582 source_model.refresh(new TreePath(((FileNode) file_job.getOrigin().getParent()).getPath()));
583 return;
584 }
585
586 // Enable the "Stop" button
587 stop_button.setEnabled(true);
588
589 // Delete empty directory job
590 if (file_job.type == FileJob.DELETE_EMPTY_DIRECTORY) {
591 file_status.setText(Dictionary.get("FileActions.Deleting", formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width)));
592 doEmptyDirectoryDelete(file_job);
593 return;
594 }
595
596 // Delete job
597 if (file_job.type == FileJob.DELETE) {
598 file_status.setText(Dictionary.get("FileActions.Deleting", formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width)));
599 if (source_file.isFile()) {
600 long source_file_size = source_file.length();
601 doFileDelete(file_job);
602 progress.addValue(source_file_size); // Update progress bar
603 }
604 else {
605 doDirectoryDelete(file_job);
606 }
607 return;
608 }
609
610 // Copy job
611 if (file_job.type == FileJob.COPY || file_job.type == FileJob.COPY_FILE_ONLY) {
612 file_status.setText(Dictionary.get("FileActions.Copying", formatPath("FileActions.Copying", source_file.getAbsolutePath(), file_status.getSize().width)));
613 if (source_file.isFile()) {
614 long source_file_size = source_file.length();
615 doFileCopy(file_job);
616 progress.addValue(source_file_size); // Update progress bar
617 }
618 else {
619 doDirectoryCopy(file_job);
620 }
621 return;
622 }
623
624 // Move (or rename) job
625 if (file_job.type == FileJob.MOVE || file_job.type == FileJob.RENAME) {
626 file_status.setText(Dictionary.get("FileActions.Moving", formatPath("FileActions.Moving", source_file.getAbsolutePath(), file_status.getSize().width)));
627 if (source_file.isFile()) {
628 long source_file_size = source_file.length();
629 doFileMove(file_job);
630 progress.addValue(source_file_size); // Update progress bar
631 }
632 else {
633 doDirectoryMove(file_job);
634 }
635 return;
636 }
637
638 // Replace job
639 if (file_job.type == FileJob.REPLACE) {
640 file_status.setText(Dictionary.get("FileActions.Replacing", formatPath("FileActions.Replacing", source_file.getAbsolutePath(), file_status.getSize().width)));
641 doFileReplace(file_job);
642 return;
643 }
644 }
645
646
647 private int showErrorDialog(String error_message)
648 {
649 Object[] options = { Dictionary.get("General.OK"), Dictionary.get("General.Cancel") };
650 int result = JOptionPane.showOptionDialog(Gatherer.g_man, error_message, Dictionary.get("General.Error"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
651 if (result == 0) {
652 return JOptionPane.OK_OPTION;
653 }
654 else {
655 return JOptionPane.CANCEL_OPTION;
656 }
657 }
658
659
660 private int showOverwriteDialog(String target_file_name)
661 {
662 // Has "yes to all" been set?
663 if (yes_to_all) {
664 return JOptionPane.YES_OPTION;
665 }
666
667 Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("FileActions.Yes_To_All"), Dictionary.get("General.No"), Dictionary.get("General.Cancel") };
668 int result = JOptionPane.showOptionDialog(Gatherer.g_man, Dictionary.get("FileActions.File_Exists", target_file_name), Dictionary.get("General.Warning"), JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
669 if (result == 0) {
670 return JOptionPane.YES_OPTION;
671 }
672 else if (result == 1) {
673 yes_to_all = true;
674 return JOptionPane.YES_OPTION;
675 }
676 else if (result == 2) {
677 return JOptionPane.NO_OPTION;
678 }
679 else {
680 return JOptionPane.CANCEL_OPTION;
681 }
682 }
683
684
685 public void run()
686 {
687 super.setName("FileQueue");
688
689 while (!Gatherer.exit) {
690 // Retrieve the next job
691 int position = queue.size() - 1;
692 if (position >= 0) {
693 // We have a file job, so process it
694 processFileJob((FileJob) queue.remove(position));
695 }
696 else {
697 // No jobs, so reset and wait until we are notified of one
698 synchronized(this) {
699 // Force both workspace and collection trees to refresh
700 if (Gatherer.g_man != null) {
701 Gatherer.g_man.refreshWorkspaceTree(DragTree.COLLECTION_CONTENTS_CHANGED);
702 // Gatherer.g_man.refreshCollectionTree(DragTree.COLLECTION_CONTENTS_CHANGED);
703 }
704
705 // Reset status area
706 file_status.setText(Dictionary.get("FileActions.No_Activity"));
707 progress.reset();
708 progress.setString(Dictionary.get("FileActions.No_Activity"));
709
710 // Reset "yes to all" and "cancel" flags
711 yes_to_all = false;
712 cancel_action = false;
713
714 // Wait for a new file job
715 try {
716 wait();
717 }
718 catch (InterruptedException exception) {}
719 }
720 }
721 }
722 }
723
724
725 /** 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.
726 * @see org.greenstone.gatherer.Gatherer
727 * @see org.greenstone.gatherer.collection.CollectionManager
728 * @see org.greenstone.gatherer.file.FileJob
729 * @see org.greenstone.gatherer.file.FileNode
730 * @see org.greenstone.gatherer.gui.GProgressBar
731 * @see org.greenstone.gatherer.util.Utility
732 */
733// public void run()
734// {
735// super.setName("FileQueue");
736
737// while (!Gatherer.exit) {
738// try {
739// // Retrieve the next job
740// int position = queue.size() - 1;
741// FileJob job = null;
742// if (position >= 0) {
743// job = (FileJob) queue.remove(position);
744// }
745
746// if (job != null) {
747// ///ystem.err.println("Found job: " + job);
748// // Enabled stop button
749// stop_button.setEnabled(true);
750// // The user can cancel this individual action at several places, so keep track if the state is 'ready' for the next step.
751// boolean ready = true;
752// FileNode origin_node = job.getOrigin();
753// FileNode destination_node = job.getDestination();
754// FileSystemModel source_model = (FileSystemModel)job.source.getTreeModel();
755// FileSystemModel target_model = (FileSystemModel)job.target.getTreeModel();
756// if(destination_node == null) {
757// // 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.
758// destination_node = (FileNode) target_model.getRoot();
759// }
760
761// // Extract common job details.
762// File source_file = origin_node.getFile();
763// File target_file = null;
764// // Determine the target file for a copy or move.
765// if (job.type == FileJob.COPY || job.type == FileJob.MOVE) {
766// // 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
767// target_file = new File(destination_node.getFile(), origin_node.toString());
768// }
769// // 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.
770// if((job.type == FileJob.COPY || job.type == FileJob.MOVE) && !job.done) {
771// ///ystem.err.println("Copy/Move: " + origin_node);
772
773// // 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
774// int max_folder_depth = Configuration.getInt("general.max_folder_depth", Configuration.COLLECTION_SPECIFIC);
775// boolean continue_over_depth = false;
776// if (countFolderDepth(source_file) > max_folder_depth) {
777// Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("General.No"), Dictionary.get("FileActions.Increase_Depth") };
778// String args[] = { String.valueOf(max_folder_depth), source_file.getAbsolutePath() };
779// 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]);
780// args = null;
781// options = null;
782// switch(result) {
783// case 0: // Yes
784// continue_over_depth = true;
785// break;
786// case 2: // Continue and increase depth
787// continue_over_depth = true;
788// Configuration.setInt("general.max_folder_depth", Configuration.COLLECTION_SPECIFIC, (max_folder_depth + 1));
789// break;
790// }
791// }
792// else {
793// continue_over_depth = true;
794// }
795
796// if(continue_over_depth) {
797// FileNode new_node = null;
798// // 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).
799// if(target_file.exists()) {
800// // We've previously been told
801// if(yes_to_all) {
802// // Remove the old file and tree entry.
803// target_file.delete();
804// ready = true;
805// }
806// else {
807// ///atherer.println("Opps! This filename already exists. Give the user some options.");
808// Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("FileActions.Yes_To_All"), Dictionary.get("General.No"), Dictionary.get("General.Cancel") };
809// 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]);
810// switch(result) {
811// case 1: // Yes To All
812// yes_to_all = true;
813// case 0: // Yes
814// // Remove the old file and tree entry.
815// if(destination_node != null) {
816// TreePath destination_path = new TreePath(destination_node.getPath());
817// CollectionTreeNode temp_target_node = new CollectionTreeNode(target_file); // !!! , target_model, true);
818// TreePath target_path = destination_path.pathByAddingChild(temp_target_node);
819// SynchronizedTreeModelTools.removeNodeFromParent(target_model, target_model.getNode(target_path));
820// target_path = null;
821// temp_target_node = null;
822// destination_path = null;
823// }
824// target_file.delete();
825// ready = true;
826// break;
827// case 3: // No To All
828// cancel_action = true;
829// case 2: // No
830// default:
831// ready = false;
832// // Increment progress by size of potentially copied file
833// progress.addValue(origin_node.getFile().length());
834// }
835// }
836// }
837// // 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.
838// if(ready) {
839// // update status area
840// String args[] = new String[1];
841// args[0] = "" + (queue.size() + 1) + "";
842// if(job.type == FileJob.COPY) {
843// args[0] = formatPath("FileActions.Copying", source_file.getAbsolutePath(), file_status.getSize().width);
844// file_status.setText(Dictionary.get("FileActions.Copying", args));
845// }
846// else {
847// args[0] = formatPath("FileActions.Moving", source_file.getAbsolutePath(), file_status.getSize().width);
848// file_status.setText(Dictionary.get("FileActions.Moving", args));
849// }
850// args = null;
851
852// // If source is a file
853// if(source_file.isFile()) {
854// // 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?
855// try {
856// copyFile(source_file, target_file, false);
857// progress.addValue(source_file.length());
858// }
859// // 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.
860// catch(FileNotFoundException fnf_exception) {
861// DebugStream.printStackTrace(fnf_exception);
862// cancel_action = true;
863// // Show warning.
864// 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);
865// // Force refresh of source folder.
866// source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
867// }
868// catch(FileAlreadyExistsException fae_exception) {
869// DebugStream.printStackTrace(fae_exception);
870// cancel_action = true;
871// // Show warning.
872// 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);
873// // Nothing else can be done by the Gatherer.
874// }
875// catch(InsufficientSpaceException is_exception) {
876// DebugStream.printStackTrace(is_exception);
877// cancel_action = true;
878// // Show warning. The message body of the expection explains how much more space is required for this file copy.
879// JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Insufficient_Space_Message", is_exception.getMessage()), Dictionary.get("FileActions.Insufficient_Space_Title"), JOptionPane.ERROR_MESSAGE);
880// // 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.
881// }
882// catch (ReadNotPermittedException rnp_exception) {
883// if (DebugStream.isDebuggingEnabled()) {
884// DebugStream.printStackTrace(rnp_exception);
885// }
886// cancel_action = true;
887// // Show warning
888// JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Read_Not_Permitted_Message", source_file.getAbsolutePath()), Dictionary.get("FileActions.Write_Not_Permitted_Title"), JOptionPane.ERROR_MESSAGE);
889// // Nothing else we can do.
890// }
891// catch(UnknownFileErrorException ufe_exception) {
892// DebugStream.printStackTrace(ufe_exception);
893// cancel_action = true;
894// // Show warning
895// JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Unknown_File_Error_Message"), Dictionary.get("FileActions.Unknown_File_Error_Title"), JOptionPane.ERROR_MESSAGE);
896// // Nothing else we can do.
897// }
898// catch(WriteNotPermittedException wnp_exception) {
899// if (DebugStream.isDebuggingEnabled()) {
900// DebugStream.printStackTrace(wnp_exception);
901// }
902// cancel_action = true;
903// // Show warning
904// 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);
905// // Nothing else we can do.
906// }
907// catch(IOException exception) {
908// // Can't really do much about this.
909// DebugStream.printStackTrace(exception);
910// }
911// // If not cancelled
912// if (!cancel_action) {
913// // Create a dummy FileNode with the correct structure (so getPath works)
914// new_node = new CollectionTreeNode(target_file);
915// SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, new_node);
916// }
917// }
918// // Else
919// else if(source_file.isDirectory()) {
920// // create new record
921// CollectionTreeNode directory_record = new CollectionTreeNode(target_file);
922// SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, directory_record);
923// // Why is this not happening eh?
924// directory_record.setParent(destination_node);
925// if(!target_file.exists()) {
926// // make the directory
927// target_file.mkdirs();
928// new_node = directory_record;
929// }
930
931// // 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.
932// FileNode child_record = null;
933// // 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.
934// // -- Starting queue ...[a]
935// // remove(position) = 'a' ...
936// // add(position, 'b') ...[b]
937// // add(position, 'c') ...[c][b]
938// // add(position, 'd') ...[d][c][b]
939// // Next loop
940// // remove(position) = 'b' ...[d][c]
941// //for(int i = 0; i < origin_node.getChildCount(); i++) {
942// for (int i=origin_node.getChildCount()-1; i>=0; i--) {
943// child_record = (FileNode) origin_node.getChildAt(i);
944// addJob(job.ID(), job.source, child_record, job.target, directory_record, job.type, false, position);
945// }
946// child_record = null;
947// directory_record = null;
948// }
949// // The file wasn't found!
950// else {
951// cancel_action = true;
952// // Show warning.
953// 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);
954// // Force refresh of source folder.
955// source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
956// }
957
958// // If we haven't been cancelled and we created a new FileNode during the above phase, now is the time to deal with metadata
959// if (!cancel_action && new_node != null) {
960// // If the file came from inside our collection...
961// if (job.source.toString().equals("Collection")) {
962// // Get the non-folder level metadata assigned to the origin node...
963// ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
964// // ...and remove it from the original node and assign it to the new folder
965// MetadataXMLFileManager.removeMetadata((CollectionTreeNode) origin_node, assigned_metadata);
966// MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_node, assigned_metadata);
967// }
968// // If it came from the workspace search for metadata assigned to the file
969// else if (job.source.toString().equals("Workspace")) {
970// ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToExternalFile(origin_node.getFile());
971// MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_node, assigned_metadata);
972// }
973
974// if (job.type == FileJob.COPY && new_node.getFile().isFile()) {
975// Gatherer.c_man.fireFileAddedToCollection(new_node.getFile());
976// }
977// }
978// new_node = null;
979// }
980// }
981// }
982// // 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.
983// if(!cancel_action && ready && (job.type == FileJob.DELETE || job.type == FileJob.MOVE)) {
984// // Update the progress bar for this job
985// if (source_file.isFile()) {
986// progress.addValue(source_file.length());
987// }
988
989// // If the source is a file or an empty directory (but not the root node of a tree)
990// File[] child_list = source_file.listFiles();
991// if (source_file.isFile() || (child_list != null && child_list.length == 0 && origin_node.getParent() != null)) {
992// // Update status area
993// String args[] = new String[1];
994// args[0] = formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width);
995// file_status.setText(Dictionary.get("FileActions.Deleting", args));
996
997// // If it is a metadata.xml file, we must unload it
998// if (source_file.getName().equals(StaticStrings.METADATA_XML)) {
999// MetadataXMLFileManager.unloadMetadataXMLFile(source_file);
1000// }
1001
1002// // Remove the metadata assigned directly to the file
1003// ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(origin_node.getFile());
1004// MetadataXMLFileManager.removeMetadata((CollectionTreeNode) origin_node, assigned_metadata);
1005
1006// // Remove from model
1007// FileNode parent_record = (FileNode) origin_node.getParent();
1008// if (parent_record != null) {
1009// SynchronizedTreeModelTools.removeNodeFromParent(source_model, origin_node);
1010// }
1011
1012// // Delete the source file
1013// if (!Utility.delete(source_file)) {
1014// // Show message that we couldn't delete
1015// JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.File_Not_Deleted_Message", source_file.getName()), Dictionary.get("FileActions.File_Not_Deleted_Title"), JOptionPane.ERROR_MESSAGE);
1016// }
1017// }
1018// // Else the source is a directory and it has children remaining
1019// else if(child_list != null && child_list.length > 0) {
1020// // Don't worry about all this for true file move actions.
1021// if(job.type == FileJob.DELETE) {
1022// // 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.
1023// origin_node.refresh();
1024// for(int i = 0; i < origin_node.size(); i++) {
1025// FileNode child_record = (FileNode) origin_node.getChildAtUnfiltered(i);
1026// ///atherer.println("Queuing: " + child_record);
1027// addJob(job.ID(), job.source, child_record, job.target, destination_node, FileJob.DELETE, false, position);
1028// }
1029// }
1030// // 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.
1031// // One special case. Do not requeue root nodes. Don't requeue jobs marked as done.
1032// if(origin_node.getParent() != null && !job.done) {
1033// ///atherer.println("Requeuing: " + origin_node.getFile().getAbsolutePath());
1034// job.type = FileJob.DELETE; // You only requeue jobs that are deletes, as directories must be inspected before children, but deleted after.
1035// addJob(job, position);
1036// }
1037// else {
1038// DebugStream.println("I've already done this job twice. I refuse to requeue it again!");
1039// }
1040// }
1041// }
1042// job = null;
1043// source_file = null;
1044// target_file = null;
1045// origin_node = null;
1046
1047// // We only break out of the while loop if we are out of files or the action was cancelled
1048// if (cancel_action) {
1049// // Empty queue
1050// clearJobs();
1051// cancel_action = false;
1052// }
1053// }
1054// else { // job == null
1055// // Disable stop button
1056// if (stop_button != null) {
1057// stop_button.setEnabled(false);
1058// }
1059// synchronized(this) {
1060// // Force both workspace and collection trees to refresh
1061// if (Gatherer.g_man != null) {
1062// Gatherer.g_man.refreshWorkspaceTree(DragTree.COLLECTION_CONTENTS_CHANGED);
1063// Gatherer.g_man.refreshCollectionTree(DragTree.COLLECTION_CONTENTS_CHANGED);
1064// }
1065
1066// // Reset status area
1067// file_status.setText(Dictionary.get("FileActions.No_Activity"));
1068// progress.reset();
1069// progress.setString(Dictionary.get("FileActions.No_Activity"));
1070// yes_to_all = false;
1071// try {
1072// wait();
1073// }
1074// catch (InterruptedException exception) {}
1075// }
1076// }
1077// }
1078// catch (Exception error) {
1079// DebugStream.printStackTrace(error);
1080// }
1081// }
1082// }
1083
1084
1085 /** Register the button that will be responsible for stopping executing file actions.
1086 * @param stop_button a JButton
1087 */
1088 public void registerStopButton(JButton stop_button) {
1089 this.stop_button = stop_button;
1090 }
1091
1092
1093 synchronized private void clearJobs() {
1094 queue.clear();
1095 }
1096
1097 /** Copy the contents from the source directory to the destination
1098 * directory.
1099 * @param source The source directory
1100 * @param destination The destination directory
1101 * @see org.greenstone.gatherer.Gatherer
1102 */
1103 public void copyDirectoryContents(File source, File destination)
1104 throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, ReadNotPermittedException, UnknownFileErrorException, WriteNotPermittedException
1105 {
1106 if (!source.isDirectory()) return;
1107 // check that dest dirs exist
1108 destination.mkdirs();
1109
1110 File [] src_files = source.listFiles();
1111 if (src_files.length == 0) return; // nothing to copy
1112 for (int i=0; i<src_files.length; i++) {
1113 File f = src_files[i];
1114 String f_name = f.getName();
1115 File new_file = new File(destination, f_name);
1116 if (f.isDirectory()) {
1117 copyDirectoryContents(f, new_file);
1118 } else if (f.isFile()) {
1119 copyFile(f, new_file, false);
1120 }
1121 }
1122 }
1123
1124
1125 /** Copy a file from the source location to the destination location.
1126 * @param source The source File.
1127 * @param destination The destination File.
1128 * @see org.greenstone.gatherer.Gatherer
1129 */
1130 public void copyFile(File source, File destination, boolean overwrite)
1131 throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, ReadNotPermittedException, UnknownFileErrorException, WriteNotPermittedException
1132 {
1133 if (source.isDirectory()) {
1134 destination.mkdirs();
1135 return;
1136 }
1137
1138 // Check if the origin file exists.
1139 if (!source.exists()) {
1140 DebugStream.println("Couldn't find the source file.");
1141 throw new FileNotFoundException();
1142 }
1143
1144 // Make sure the destination file does not exist.
1145 if (destination.exists() && !overwrite) {
1146 throw new FileAlreadyExistsException();
1147 }
1148
1149 // Open an input stream to the source file
1150 FileInputStream f_in = null;
1151 try {
1152 f_in = new FileInputStream(source);
1153 }
1154 catch (FileNotFoundException exception) {
1155 // A FileNotFoundException translates into a ReadNotPermittedException in this case
1156 throw new ReadNotPermittedException(exception.toString());
1157 }
1158
1159 // Create an necessary directories for the target file
1160 File dirs = destination.getParentFile();
1161 dirs.mkdirs();
1162
1163 // Open an output stream to the target file
1164 FileOutputStream f_out = null;
1165 try {
1166 f_out = new FileOutputStream(destination);
1167 }
1168 catch (FileNotFoundException exception) {
1169 // A FileNotFoundException translates into a WriteNotPermittedException in this case
1170 throw new WriteNotPermittedException(exception.toString());
1171 }
1172
1173 // Copy the file
1174 byte data[] = new byte[Utility.BUFFER_SIZE];
1175 int data_size = 0;
1176 while ((data_size = f_in.read(data, 0, Utility.BUFFER_SIZE)) != -1 && !cancel_action) {
1177 long destination_size = destination.length();
1178 try {
1179 f_out.write(data, 0, data_size);
1180 }
1181 // 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.
1182 catch (IOException io_exception) {
1183 if (destination_size + (long) data_size > destination.length()) {
1184 // Determine the difference (which I guess is in bytes).
1185 long difference = (destination_size + (long) data_size) - destination.length();
1186 // Transform that into a human readable string.
1187 String message = Utility.formatFileLength(difference);
1188 throw new InsufficientSpaceException(message);
1189 }
1190 else {
1191 throw(io_exception);
1192 }
1193 }
1194 }
1195
1196 // Flush and close the streams to ensure all bytes are written.
1197 f_in.close();
1198 f_out.close();
1199
1200 // We have now, in theory, produced an exact copy of the source file. Check this by comparing sizes.
1201 if(!destination.exists() || (!cancel_action && source.length() != destination.length())) {
1202 throw new UnknownFileErrorException();
1203 }
1204
1205 // If we were cancelled, ensure that none of the destination file exists.
1206 if (cancel_action) {
1207 destination.delete();
1208 }
1209 }
1210}
Note: See TracBrowser for help on using the repository browser.