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

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

Fixed up some formatting.

  • Property svn:keywords set to Author Date Id Revision
File size: 51.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.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
408 if (target_file.exists()) {
409 int result = showOverwriteDialog(target_file.getName());
410 if (result == JOptionPane.NO_OPTION) {
411 // Don't overwrite
412 return;
413 }
414 if (result == JOptionPane.CANCEL_OPTION) {
415 clearJobs(); // Aborting action
416 return;
417 }
418 }
419
420 // Copy the file
421 try {
422 copyFile(source_file, target_file, true);
423 }
424 catch (FileAlreadyExistsException exception) {
425 // This should not ever happen, since we've called copyFile with overwrite set
426 DebugStream.printStackTrace(exception);
427 return;
428 }
429 catch (FileNotFoundException exception) {
430 DebugStream.printStackTrace(exception);
431 if (showErrorDialog(Dictionary.get("FileActions.File_Not_Found_Message", source_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
432 clearJobs(); // Aborting action
433 }
434 // Refresh the source tree model
435 FileSystemModel source_model = file_job.source.getTreeModel();
436 source_model.refresh(new TreePath(((FileNode) file_job.getOrigin().getParent()).getPath()));
437 return;
438 }
439 catch (InsufficientSpaceException exception) {
440 DebugStream.printStackTrace(exception);
441 if (showErrorDialog(Dictionary.get("FileActions.Insufficient_Space_Message", exception.getMessage())) == JOptionPane.CANCEL_OPTION) {
442 clearJobs(); // Aborting action
443 }
444 return;
445 }
446 catch (IOException exception) {
447 DebugStream.printStackTrace(exception);
448 if (showErrorDialog(exception.getMessage()) == JOptionPane.CANCEL_OPTION) {
449 clearJobs(); // Aborting action
450 }
451 return;
452 }
453 catch (ReadNotPermittedException exception) {
454 DebugStream.printStackTrace(exception);
455 if (showErrorDialog(Dictionary.get("FileActions.Read_Not_Permitted_Message", source_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
456 clearJobs(); // Aborting action
457 }
458 return;
459 }
460 catch (UnknownFileErrorException exception) {
461 DebugStream.printStackTrace(exception);
462 if (showErrorDialog(Dictionary.get("FileActions.Unknown_File_Error_Message")) == JOptionPane.CANCEL_OPTION) {
463 clearJobs(); // Aborting action
464 }
465 return;
466 }
467 catch (WriteNotPermittedException exception) {
468 DebugStream.printStackTrace(exception);
469 if (showErrorDialog(Dictionary.get("FileActions.Write_Not_Permitted_Message", target_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
470 clearJobs(); // Aborting action
471 }
472 return;
473 }
474
475 CollectionTreeNode new_target_node = new CollectionTreeNode(target_file);
476 FileSystemModel target_model = file_job.target.getTreeModel();
477 SynchronizedTreeModelTools.insertNodeInto(target_model, target_node, new_target_node);
478 Gatherer.c_man.fireFileAddedToCollection(target_file);
479
480 // Copy the non-folder level metadata assigned to the original file to the new file
481 if (file_job.type == FileJob.COPY) {
482 // do metadata too
483 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToExternalFile(source_file);
484 MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_target_node, assigned_metadata);
485 }
486 }
487
488
489 private void doFileMove(FileJob file_job)
490 {
491 FileNode source_node = file_job.getOrigin();
492 FileNode target_node = file_job.getDestination();
493
494 File source_file = source_node.getFile();
495 File target_file = new File(target_node.getFile(), source_file.getName());
496 if (file_job.type == FileJob.RENAME) {
497 // This is the only difference between moves and renames
498 target_file = target_node.getFile();
499 target_node = (FileNode) source_node.getParent();
500 }
501
502 // Check the target file isn't the source file
503 if (target_file.equals(source_file)) {
504 DebugStream.println("Target file is the source file!");
505 return;
506 }
507
508 // The target file shouldn't already exist
509 if (target_file.exists()) {
510 int result = showOverwriteDialog(target_file.getName());
511 if (result == JOptionPane.NO_OPTION) {
512 // Don't overwrite
513 return;
514 }
515 if (result == JOptionPane.CANCEL_OPTION) {
516 clearJobs(); // Aborting action
517 return;
518 }
519 }
520
521 // Move the file by renaming it
522 if (!source_file.renameTo(target_file)) {
523 String args[] = { source_file.getName(), target_file.getAbsolutePath() };
524 if (showErrorDialog(Dictionary.get("FileActions.File_Move_Error_Message", args)) == JOptionPane.CANCEL_OPTION) {
525 clearJobs(); // Aborting action
526 }
527 return;
528 }
529
530 // Remove the node from the source model and add it to the target model
531 SynchronizedTreeModelTools.removeNodeFromParent(file_job.source.getTreeModel(), source_node);
532 CollectionTreeNode new_target_node = new CollectionTreeNode(target_file);
533 FileSystemModel target_model = file_job.target.getTreeModel();
534 SynchronizedTreeModelTools.insertNodeInto(target_model, target_node, new_target_node);
535
536 // Move the non-folder level metadata assigned to the original file to the new file
537 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
538 MetadataXMLFileManager.removeMetadata((CollectionTreeNode) source_node, assigned_metadata);
539 MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_target_node, assigned_metadata);
540 }
541
542
543 /** all this does is move the metadata, and delete the source */
544 private void doFileReplace(FileJob file_job)
545 {
546 FileNode source_node = file_job.getOrigin();
547 FileNode target_node = file_job.getDestination();
548
549 File source_file = source_node.getFile();
550 File target_file = target_node.getFile();
551
552 // Move the non-folder level metadata assigned to the original file to the new file
553 CollectionTreeNode new_target_node = new CollectionTreeNode(target_file);
554 ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
555 MetadataXMLFileManager.removeMetadata((CollectionTreeNode) source_node, assigned_metadata);
556 MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_target_node, assigned_metadata);
557
558 // now delete the original
559 doFileDelete(file_job);
560 }
561
562
563 private void processFileJob(FileJob file_job)
564 {
565 DebugStream.println("Processing file job " + file_job + "...");
566
567 // Ensure that the source file exists
568 File source_file = file_job.getOrigin().getFile();
569 if (!source_file.exists()) {
570 // The source file doesn't exist, so give the user the option of continuing or cancelling
571 if (showErrorDialog(Dictionary.get("FileActions.File_Not_Found_Message", source_file.getAbsolutePath())) == JOptionPane.CANCEL_OPTION) {
572 clearJobs(); // Aborting action
573 }
574 // Refresh the source tree model
575 FileSystemModel source_model = file_job.source.getTreeModel();
576 source_model.refresh(new TreePath(((FileNode) file_job.getOrigin().getParent()).getPath()));
577 return;
578 }
579
580 // Enable the "Stop" button
581 stop_button.setEnabled(true);
582
583 // Delete empty directory job
584 if (file_job.type == FileJob.DELETE_EMPTY_DIRECTORY) {
585 file_status.setText(Dictionary.get("FileActions.Deleting", formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width)));
586 doEmptyDirectoryDelete(file_job);
587 return;
588 }
589
590 // Delete job
591 if (file_job.type == FileJob.DELETE) {
592 file_status.setText(Dictionary.get("FileActions.Deleting", formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width)));
593 if (source_file.isFile()) {
594 long source_file_size = source_file.length();
595 doFileDelete(file_job);
596 progress.addValue(source_file_size); // Update progress bar
597 }
598 else {
599 doDirectoryDelete(file_job);
600 }
601 return;
602 }
603
604 // Copy job
605 if (file_job.type == FileJob.COPY || file_job.type == FileJob.COPY_FILE_ONLY) {
606 file_status.setText(Dictionary.get("FileActions.Copying", formatPath("FileActions.Copying", source_file.getAbsolutePath(), file_status.getSize().width)));
607 if (source_file.isFile()) {
608 long source_file_size = source_file.length();
609 doFileCopy(file_job);
610 progress.addValue(source_file_size); // Update progress bar
611 }
612 else {
613 doDirectoryCopy(file_job);
614 }
615 return;
616 }
617
618 // Move (or rename) job
619 if (file_job.type == FileJob.MOVE || file_job.type == FileJob.RENAME) {
620 file_status.setText(Dictionary.get("FileActions.Moving", formatPath("FileActions.Moving", source_file.getAbsolutePath(), file_status.getSize().width)));
621 if (source_file.isFile()) {
622 long source_file_size = source_file.length();
623 doFileMove(file_job);
624 progress.addValue(source_file_size); // Update progress bar
625 }
626 else {
627 doDirectoryMove(file_job);
628 }
629 return;
630 }
631
632 // Replace job
633 if (file_job.type == FileJob.REPLACE) {
634 file_status.setText(Dictionary.get("FileActions.Replacing", formatPath("FileActions.Replacing", source_file.getAbsolutePath(), file_status.getSize().width)));
635 doFileReplace(file_job);
636 return;
637 }
638 }
639
640
641 private int showErrorDialog(String error_message)
642 {
643 Object[] options = { Dictionary.get("General.OK"), Dictionary.get("General.Cancel") };
644 int result = JOptionPane.showOptionDialog(Gatherer.g_man, error_message, Dictionary.get("General.Error"), JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
645 if (result == 0) {
646 return JOptionPane.OK_OPTION;
647 }
648 else {
649 return JOptionPane.CANCEL_OPTION;
650 }
651 }
652
653
654 private int showOverwriteDialog(String target_file_name)
655 {
656 // Has "yes to all" been set?
657 if (yes_to_all) {
658 return JOptionPane.YES_OPTION;
659 }
660
661 Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("FileActions.Yes_To_All"), Dictionary.get("General.No"), Dictionary.get("General.Cancel") };
662 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]);
663 if (result == 0) {
664 return JOptionPane.YES_OPTION;
665 }
666 else if (result == 1) {
667 yes_to_all = true;
668 return JOptionPane.YES_OPTION;
669 }
670 else if (result == 2) {
671 return JOptionPane.NO_OPTION;
672 }
673 else {
674 return JOptionPane.CANCEL_OPTION;
675 }
676 }
677
678
679 public void run()
680 {
681 super.setName("FileQueue");
682
683 while (!Gatherer.exit) {
684 // Retrieve the next job
685 int position = queue.size() - 1;
686 if (position >= 0) {
687 // We have a file job, so process it
688 processFileJob((FileJob) queue.remove(position));
689 }
690 else {
691 // No jobs, so reset and wait until we are notified of one
692 synchronized(this) {
693 // Force both workspace and collection trees to refresh
694 if (Gatherer.g_man != null) {
695 Gatherer.g_man.refreshWorkspaceTree(DragTree.COLLECTION_CONTENTS_CHANGED);
696 // Gatherer.g_man.refreshCollectionTree(DragTree.COLLECTION_CONTENTS_CHANGED);
697 }
698
699 // Reset status area
700 file_status.setText(Dictionary.get("FileActions.No_Activity"));
701 progress.reset();
702 progress.setString(Dictionary.get("FileActions.No_Activity"));
703
704 // Reset "yes to all" and "cancel" flags
705 yes_to_all = false;
706 cancel_action = false;
707
708 // Wait for a new file job
709 try {
710 wait();
711 }
712 catch (InterruptedException exception) {}
713 }
714 }
715 }
716 }
717
718
719 /** 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.
720 * @see org.greenstone.gatherer.Gatherer
721 * @see org.greenstone.gatherer.collection.CollectionManager
722 * @see org.greenstone.gatherer.file.FileJob
723 * @see org.greenstone.gatherer.file.FileNode
724 * @see org.greenstone.gatherer.gui.GProgressBar
725 * @see org.greenstone.gatherer.util.Utility
726 */
727// public void run()
728// {
729// super.setName("FileQueue");
730
731// while (!Gatherer.exit) {
732// try {
733// // Retrieve the next job
734// int position = queue.size() - 1;
735// FileJob job = null;
736// if (position >= 0) {
737// job = (FileJob) queue.remove(position);
738// }
739
740// if (job != null) {
741// ///ystem.err.println("Found job: " + job);
742// // Enabled stop button
743// stop_button.setEnabled(true);
744// // The user can cancel this individual action at several places, so keep track if the state is 'ready' for the next step.
745// boolean ready = true;
746// FileNode origin_node = job.getOrigin();
747// FileNode destination_node = job.getDestination();
748// FileSystemModel source_model = (FileSystemModel)job.source.getTreeModel();
749// FileSystemModel target_model = (FileSystemModel)job.target.getTreeModel();
750// if(destination_node == null) {
751// // 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.
752// destination_node = (FileNode) target_model.getRoot();
753// }
754
755// // Extract common job details.
756// File source_file = origin_node.getFile();
757// File target_file = null;
758// // Determine the target file for a copy or move.
759// if (job.type == FileJob.COPY || job.type == FileJob.MOVE) {
760// // 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
761// target_file = new File(destination_node.getFile(), origin_node.toString());
762// }
763// // 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.
764// if((job.type == FileJob.COPY || job.type == FileJob.MOVE) && !job.done) {
765// ///ystem.err.println("Copy/Move: " + origin_node);
766
767// // 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
768// int max_folder_depth = Configuration.getInt("general.max_folder_depth", Configuration.COLLECTION_SPECIFIC);
769// boolean continue_over_depth = false;
770// if (countFolderDepth(source_file) > max_folder_depth) {
771// Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("General.No"), Dictionary.get("FileActions.Increase_Depth") };
772// String args[] = { String.valueOf(max_folder_depth), source_file.getAbsolutePath() };
773// 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]);
774// args = null;
775// options = null;
776// switch(result) {
777// case 0: // Yes
778// continue_over_depth = true;
779// break;
780// case 2: // Continue and increase depth
781// continue_over_depth = true;
782// Configuration.setInt("general.max_folder_depth", Configuration.COLLECTION_SPECIFIC, (max_folder_depth + 1));
783// break;
784// }
785// }
786// else {
787// continue_over_depth = true;
788// }
789
790// if(continue_over_depth) {
791// FileNode new_node = null;
792// // 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).
793// if(target_file.exists()) {
794// // We've previously been told
795// if(yes_to_all) {
796// // Remove the old file and tree entry.
797// target_file.delete();
798// ready = true;
799// }
800// else {
801// ///atherer.println("Opps! This filename already exists. Give the user some options.");
802// Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("FileActions.Yes_To_All"), Dictionary.get("General.No"), Dictionary.get("General.Cancel") };
803// 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]);
804// switch(result) {
805// case 1: // Yes To All
806// yes_to_all = true;
807// case 0: // Yes
808// // Remove the old file and tree entry.
809// if(destination_node != null) {
810// TreePath destination_path = new TreePath(destination_node.getPath());
811// CollectionTreeNode temp_target_node = new CollectionTreeNode(target_file); // !!! , target_model, true);
812// TreePath target_path = destination_path.pathByAddingChild(temp_target_node);
813// SynchronizedTreeModelTools.removeNodeFromParent(target_model, target_model.getNode(target_path));
814// target_path = null;
815// temp_target_node = null;
816// destination_path = null;
817// }
818// target_file.delete();
819// ready = true;
820// break;
821// case 3: // No To All
822// cancel_action = true;
823// case 2: // No
824// default:
825// ready = false;
826// // Increment progress by size of potentially copied file
827// progress.addValue(origin_node.getFile().length());
828// }
829// }
830// }
831// // 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.
832// if(ready) {
833// // update status area
834// String args[] = new String[1];
835// args[0] = "" + (queue.size() + 1) + "";
836// if(job.type == FileJob.COPY) {
837// args[0] = formatPath("FileActions.Copying", source_file.getAbsolutePath(), file_status.getSize().width);
838// file_status.setText(Dictionary.get("FileActions.Copying", args));
839// }
840// else {
841// args[0] = formatPath("FileActions.Moving", source_file.getAbsolutePath(), file_status.getSize().width);
842// file_status.setText(Dictionary.get("FileActions.Moving", args));
843// }
844// args = null;
845
846// // If source is a file
847// if(source_file.isFile()) {
848// // 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?
849// try {
850// copyFile(source_file, target_file, false);
851// progress.addValue(source_file.length());
852// }
853// // 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.
854// catch(FileNotFoundException fnf_exception) {
855// DebugStream.printStackTrace(fnf_exception);
856// cancel_action = true;
857// // Show warning.
858// 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);
859// // Force refresh of source folder.
860// source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
861// }
862// catch(FileAlreadyExistsException fae_exception) {
863// DebugStream.printStackTrace(fae_exception);
864// cancel_action = true;
865// // Show warning.
866// 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);
867// // Nothing else can be done by the Gatherer.
868// }
869// catch(InsufficientSpaceException is_exception) {
870// DebugStream.printStackTrace(is_exception);
871// cancel_action = true;
872// // Show warning. The message body of the expection explains how much more space is required for this file copy.
873// JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Insufficient_Space_Message", is_exception.getMessage()), Dictionary.get("FileActions.Insufficient_Space_Title"), JOptionPane.ERROR_MESSAGE);
874// // 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.
875// }
876// catch (ReadNotPermittedException rnp_exception) {
877// if (DebugStream.isDebuggingEnabled()) {
878// DebugStream.printStackTrace(rnp_exception);
879// }
880// cancel_action = true;
881// // Show warning
882// 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);
883// // Nothing else we can do.
884// }
885// catch(UnknownFileErrorException ufe_exception) {
886// DebugStream.printStackTrace(ufe_exception);
887// cancel_action = true;
888// // Show warning
889// JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Unknown_File_Error_Message"), Dictionary.get("FileActions.Unknown_File_Error_Title"), JOptionPane.ERROR_MESSAGE);
890// // Nothing else we can do.
891// }
892// catch(WriteNotPermittedException wnp_exception) {
893// if (DebugStream.isDebuggingEnabled()) {
894// DebugStream.printStackTrace(wnp_exception);
895// }
896// cancel_action = true;
897// // Show warning
898// 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);
899// // Nothing else we can do.
900// }
901// catch(IOException exception) {
902// // Can't really do much about this.
903// DebugStream.printStackTrace(exception);
904// }
905// // If not cancelled
906// if (!cancel_action) {
907// // Create a dummy FileNode with the correct structure (so getPath works)
908// new_node = new CollectionTreeNode(target_file);
909// SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, new_node);
910// }
911// }
912// // Else
913// else if(source_file.isDirectory()) {
914// // create new record
915// CollectionTreeNode directory_record = new CollectionTreeNode(target_file);
916// SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, directory_record);
917// // Why is this not happening eh?
918// directory_record.setParent(destination_node);
919// if(!target_file.exists()) {
920// // make the directory
921// target_file.mkdirs();
922// new_node = directory_record;
923// }
924
925// // 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.
926// FileNode child_record = null;
927// // 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.
928// // -- Starting queue ...[a]
929// // remove(position) = 'a' ...
930// // add(position, 'b') ...[b]
931// // add(position, 'c') ...[c][b]
932// // add(position, 'd') ...[d][c][b]
933// // Next loop
934// // remove(position) = 'b' ...[d][c]
935// //for(int i = 0; i < origin_node.getChildCount(); i++) {
936// for (int i=origin_node.getChildCount()-1; i>=0; i--) {
937// child_record = (FileNode) origin_node.getChildAt(i);
938// addJob(job.ID(), job.source, child_record, job.target, directory_record, job.type, false, position);
939// }
940// child_record = null;
941// directory_record = null;
942// }
943// // The file wasn't found!
944// else {
945// cancel_action = true;
946// // Show warning.
947// 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);
948// // Force refresh of source folder.
949// source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
950// }
951
952// // If we haven't been cancelled and we created a new FileNode during the above phase, now is the time to deal with metadata
953// if (!cancel_action && new_node != null) {
954// // If the file came from inside our collection...
955// if (job.source.toString().equals("Collection")) {
956// // Get the non-folder level metadata assigned to the origin node...
957// ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
958// // ...and remove it from the original node and assign it to the new folder
959// MetadataXMLFileManager.removeMetadata((CollectionTreeNode) origin_node, assigned_metadata);
960// MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_node, assigned_metadata);
961// }
962// // If it came from the workspace search for metadata assigned to the file
963// else if (job.source.toString().equals("Workspace")) {
964// ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToExternalFile(origin_node.getFile());
965// MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_node, assigned_metadata);
966// }
967
968// if (job.type == FileJob.COPY && new_node.getFile().isFile()) {
969// Gatherer.c_man.fireFileAddedToCollection(new_node.getFile());
970// }
971// }
972// new_node = null;
973// }
974// }
975// }
976// // 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.
977// if(!cancel_action && ready && (job.type == FileJob.DELETE || job.type == FileJob.MOVE)) {
978// // Update the progress bar for this job
979// if (source_file.isFile()) {
980// progress.addValue(source_file.length());
981// }
982
983// // If the source is a file or an empty directory (but not the root node of a tree)
984// File[] child_list = source_file.listFiles();
985// if (source_file.isFile() || (child_list != null && child_list.length == 0 && origin_node.getParent() != null)) {
986// // Update status area
987// String args[] = new String[1];
988// args[0] = formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width);
989// file_status.setText(Dictionary.get("FileActions.Deleting", args));
990
991// // If it is a metadata.xml file, we must unload it
992// if (source_file.getName().equals(StaticStrings.METADATA_XML)) {
993// MetadataXMLFileManager.unloadMetadataXMLFile(source_file);
994// }
995
996// // Remove the metadata assigned directly to the file
997// ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(origin_node.getFile());
998// MetadataXMLFileManager.removeMetadata((CollectionTreeNode) origin_node, assigned_metadata);
999
1000// // Remove from model
1001// FileNode parent_record = (FileNode) origin_node.getParent();
1002// if (parent_record != null) {
1003// SynchronizedTreeModelTools.removeNodeFromParent(source_model, origin_node);
1004// }
1005
1006// // Delete the source file
1007// if (!Utility.delete(source_file)) {
1008// // Show message that we couldn't delete
1009// 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);
1010// }
1011// }
1012// // Else the source is a directory and it has children remaining
1013// else if(child_list != null && child_list.length > 0) {
1014// // Don't worry about all this for true file move actions.
1015// if(job.type == FileJob.DELETE) {
1016// // 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.
1017// origin_node.refresh();
1018// for(int i = 0; i < origin_node.size(); i++) {
1019// FileNode child_record = (FileNode) origin_node.getChildAtUnfiltered(i);
1020// ///atherer.println("Queuing: " + child_record);
1021// addJob(job.ID(), job.source, child_record, job.target, destination_node, FileJob.DELETE, false, position);
1022// }
1023// }
1024// // 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.
1025// // One special case. Do not requeue root nodes. Don't requeue jobs marked as done.
1026// if(origin_node.getParent() != null && !job.done) {
1027// ///atherer.println("Requeuing: " + origin_node.getFile().getAbsolutePath());
1028// job.type = FileJob.DELETE; // You only requeue jobs that are deletes, as directories must be inspected before children, but deleted after.
1029// addJob(job, position);
1030// }
1031// else {
1032// DebugStream.println("I've already done this job twice. I refuse to requeue it again!");
1033// }
1034// }
1035// }
1036// job = null;
1037// source_file = null;
1038// target_file = null;
1039// origin_node = null;
1040
1041// // We only break out of the while loop if we are out of files or the action was cancelled
1042// if (cancel_action) {
1043// // Empty queue
1044// clearJobs();
1045// cancel_action = false;
1046// }
1047// }
1048// else { // job == null
1049// // Disable stop button
1050// if (stop_button != null) {
1051// stop_button.setEnabled(false);
1052// }
1053// synchronized(this) {
1054// // Force both workspace and collection trees to refresh
1055// if (Gatherer.g_man != null) {
1056// Gatherer.g_man.refreshWorkspaceTree(DragTree.COLLECTION_CONTENTS_CHANGED);
1057// Gatherer.g_man.refreshCollectionTree(DragTree.COLLECTION_CONTENTS_CHANGED);
1058// }
1059
1060// // Reset status area
1061// file_status.setText(Dictionary.get("FileActions.No_Activity"));
1062// progress.reset();
1063// progress.setString(Dictionary.get("FileActions.No_Activity"));
1064// yes_to_all = false;
1065// try {
1066// wait();
1067// }
1068// catch (InterruptedException exception) {}
1069// }
1070// }
1071// }
1072// catch (Exception error) {
1073// DebugStream.printStackTrace(error);
1074// }
1075// }
1076// }
1077
1078
1079 /** Register the button that will be responsible for stopping executing file actions.
1080 * @param stop_button a JButton
1081 */
1082 public void registerStopButton(JButton stop_button) {
1083 this.stop_button = stop_button;
1084 }
1085
1086
1087 synchronized private void clearJobs() {
1088 queue.clear();
1089 }
1090
1091 /** Copy the contents from the source directory to the destination
1092 * directory.
1093 * @param source The source directory
1094 * @param destination The destination directory
1095 * @see org.greenstone.gatherer.Gatherer
1096 */
1097 public void copyDirectoryContents(File source, File destination)
1098 throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, ReadNotPermittedException, UnknownFileErrorException, WriteNotPermittedException
1099 {
1100 if (!source.isDirectory()) return;
1101 // check that dest dirs exist
1102 destination.mkdirs();
1103
1104 File [] src_files = source.listFiles();
1105 if (src_files.length == 0) return; // nothing to copy
1106 for (int i=0; i<src_files.length; i++) {
1107 File f = src_files[i];
1108 String f_name = f.getName();
1109 File new_file = new File(destination, f_name);
1110 if (f.isDirectory()) {
1111 copyDirectoryContents(f, new_file);
1112 } else if (f.isFile()) {
1113 copyFile(f, new_file, false);
1114 }
1115 }
1116 }
1117
1118
1119 /** Copy a file from the source location to the destination location.
1120 * @param source The source File.
1121 * @param destination The destination File.
1122 * @see org.greenstone.gatherer.Gatherer
1123 */
1124 public void copyFile(File source, File destination, boolean overwrite)
1125 throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, ReadNotPermittedException, UnknownFileErrorException, WriteNotPermittedException
1126 {
1127 if (source.isDirectory()) {
1128 destination.mkdirs();
1129 return;
1130 }
1131
1132 // Check if the origin file exists.
1133 if (!source.exists()) {
1134 DebugStream.println("Couldn't find the source file.");
1135 throw new FileNotFoundException();
1136 }
1137
1138 // Make sure the destination file does not exist.
1139 if (destination.exists() && !overwrite) {
1140 throw new FileAlreadyExistsException();
1141 }
1142
1143 // Open an input stream to the source file
1144 FileInputStream f_in = null;
1145 try {
1146 f_in = new FileInputStream(source);
1147 }
1148 catch (FileNotFoundException exception) {
1149 // A FileNotFoundException translates into a ReadNotPermittedException in this case
1150 throw new ReadNotPermittedException(exception.toString());
1151 }
1152
1153 // Create an necessary directories for the target file
1154 File dirs = destination.getParentFile();
1155 dirs.mkdirs();
1156
1157 // Open an output stream to the target file
1158 FileOutputStream f_out = null;
1159 try {
1160 f_out = new FileOutputStream(destination);
1161 }
1162 catch (FileNotFoundException exception) {
1163 // A FileNotFoundException translates into a WriteNotPermittedException in this case
1164 throw new WriteNotPermittedException(exception.toString());
1165 }
1166
1167 // Copy the file
1168 byte data[] = new byte[Utility.BUFFER_SIZE];
1169 int data_size = 0;
1170 while ((data_size = f_in.read(data, 0, Utility.BUFFER_SIZE)) != -1 && !cancel_action) {
1171 long destination_size = destination.length();
1172 try {
1173 f_out.write(data, 0, data_size);
1174 }
1175 // 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.
1176 catch (IOException io_exception) {
1177 if (destination_size + (long) data_size > destination.length()) {
1178 // Determine the difference (which I guess is in bytes).
1179 long difference = (destination_size + (long) data_size) - destination.length();
1180 // Transform that into a human readable string.
1181 String message = Utility.formatFileLength(difference);
1182 throw new InsufficientSpaceException(message);
1183 }
1184 else {
1185 throw(io_exception);
1186 }
1187 }
1188 }
1189
1190 // Flush and close the streams to ensure all bytes are written.
1191 f_in.close();
1192 f_out.close();
1193
1194 // We have now, in theory, produced an exact copy of the source file. Check this by comparing sizes.
1195 if(!destination.exists() || (!cancel_action && source.length() != destination.length())) {
1196 throw new UnknownFileErrorException();
1197 }
1198
1199 // If we were cancelled, ensure that none of the destination file exists.
1200 if (cancel_action) {
1201 destination.delete();
1202 }
1203 }
1204}
Note: See TracBrowser for help on using the repository browser.