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

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

Fixed a minor bug where an extra file icon was added to the tree if you overwrote an existing file with the same name.

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