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 | */
|
---|
27 | package org.greenstone.gatherer.file;
|
---|
28 |
|
---|
29 | import java.io.*;
|
---|
30 | import java.util.*;
|
---|
31 | import javax.swing.*;
|
---|
32 | import javax.swing.event.*;
|
---|
33 | import javax.swing.tree.*;
|
---|
34 | import org.greenstone.gatherer.Configuration;
|
---|
35 | import org.greenstone.gatherer.DebugStream;
|
---|
36 | import org.greenstone.gatherer.Dictionary;
|
---|
37 | import org.greenstone.gatherer.Gatherer;
|
---|
38 | import org.greenstone.gatherer.collection.CollectionTreeNode;
|
---|
39 | import org.greenstone.gatherer.gui.LongProgressBar;
|
---|
40 | import org.greenstone.gatherer.gui.tree.DragTree;
|
---|
41 | import org.greenstone.gatherer.metadata.MetadataValue;
|
---|
42 | import org.greenstone.gatherer.metadata.MetadataXMLFileManager;
|
---|
43 | import org.greenstone.gatherer.util.DragComponent;
|
---|
44 | import org.greenstone.gatherer.util.StaticStrings;
|
---|
45 | import org.greenstone.gatherer.util.SynchronizedTreeModelTools;
|
---|
46 | import 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 | */
|
---|
52 | public 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 LongProgressBar 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 LongProgressBar();
|
---|
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, boolean folder_level)
|
---|
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, folder_level, -1);
|
---|
105 | }
|
---|
106 | }
|
---|
107 |
|
---|
108 | synchronized private void addJob(long id, DragComponent source, FileNode child, DragComponent target, FileNode parent, byte type, boolean folder_level, int position) {
|
---|
109 | FileJob job = new FileJob(id, source, child, target, parent, type);
|
---|
110 | job.folder_level = folder_level;
|
---|
111 | DebugStream.println("Adding job: " + job);
|
---|
112 | if(position != -1 && position <= queue.size() + 1) {
|
---|
113 | queue.add(position, job);
|
---|
114 | }
|
---|
115 | else {
|
---|
116 | queue.add(job);
|
---|
117 | }
|
---|
118 | notify();
|
---|
119 | }
|
---|
120 |
|
---|
121 | /** Calculates the total deep file size of the selected file nodes.
|
---|
122 | * @param files a FileNode[] of selected files
|
---|
123 | * @return true if a cancel was signalled, false otherwise
|
---|
124 | * @see org.greenstone.gatherer.file.FileManager.Task#run()
|
---|
125 | */
|
---|
126 | public boolean calculateSize(FileNode[] files)
|
---|
127 | {
|
---|
128 | file_status.setText(Dictionary.get("FileActions.Calculating_Size"));
|
---|
129 | progress.setString(Dictionary.get("FileActions.Calculating_Size"));
|
---|
130 |
|
---|
131 | // Calculate the total file size of all the selected file nodes
|
---|
132 | Vector remaining = new Vector();
|
---|
133 | for (int i = 0; !cancel_action && i < files.length; i++) {
|
---|
134 | remaining.add(files[i]);
|
---|
135 | }
|
---|
136 | while (!cancel_action && remaining.size() > 0) {
|
---|
137 | FileNode node = (FileNode) remaining.remove(0);
|
---|
138 | if (node.isLeaf()) {
|
---|
139 | progress.addMaximum(node.getFile().length());
|
---|
140 | }
|
---|
141 | else {
|
---|
142 | for (int i = 0; !cancel_action && i < node.getChildCount(); i++) {
|
---|
143 | remaining.add(node.getChildAt(i));
|
---|
144 | }
|
---|
145 | }
|
---|
146 | }
|
---|
147 |
|
---|
148 | // Now we return if calculation was cancelled so that the FileManagers Task can skip the addJob phase correctly.
|
---|
149 | if (cancel_action) {
|
---|
150 | cancel_action = false; // reset
|
---|
151 | return true;
|
---|
152 | }
|
---|
153 | else {
|
---|
154 | return false;
|
---|
155 | }
|
---|
156 | }
|
---|
157 |
|
---|
158 | /** This method is called to cancel the job queue at the next available moment. */
|
---|
159 | public void cancelAction() {
|
---|
160 | cancel_action = true;
|
---|
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 LongProgressBar getProgressBar() {
|
---|
203 | return progress;
|
---|
204 | }
|
---|
205 |
|
---|
206 |
|
---|
207 | /** 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.
|
---|
208 | * @see org.greenstone.gatherer.Gatherer
|
---|
209 | * @see org.greenstone.gatherer.collection.CollectionManager
|
---|
210 | * @see org.greenstone.gatherer.file.FileJob
|
---|
211 | * @see org.greenstone.gatherer.file.FileNode
|
---|
212 | * @see org.greenstone.gatherer.gui.LongProgressBar
|
---|
213 | * @see org.greenstone.gatherer.util.Utility
|
---|
214 | */
|
---|
215 | public void run()
|
---|
216 | {
|
---|
217 | super.setName("FileQueue");
|
---|
218 |
|
---|
219 | while (!Gatherer.exit) {
|
---|
220 | try {
|
---|
221 | // Retrieve the next job
|
---|
222 | int position = queue.size() - 1;
|
---|
223 | FileJob job = null;
|
---|
224 | if (position >= 0) {
|
---|
225 | job = (FileJob) queue.remove(position);
|
---|
226 | }
|
---|
227 |
|
---|
228 | if (job != null) {
|
---|
229 | ///ystem.err.println("Found job: " + job);
|
---|
230 | // Enabled stop button
|
---|
231 | stop_button.setEnabled(true);
|
---|
232 | // The user can cancel this individual action at several places, so keep track if the state is 'ready' for the next step.
|
---|
233 | boolean ready = true;
|
---|
234 | FileNode origin_node = job.getOrigin();
|
---|
235 | FileNode destination_node = job.getDestination();
|
---|
236 | FileSystemModel source_model = (FileSystemModel)job.source.getTreeModel();
|
---|
237 | FileSystemModel target_model = (FileSystemModel)job.target.getTreeModel();
|
---|
238 | if(destination_node == null) {
|
---|
239 | // 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.
|
---|
240 | destination_node = (FileNode) target_model.getRoot();
|
---|
241 | }
|
---|
242 |
|
---|
243 | // Extract common job details.
|
---|
244 | File source_file = origin_node.getFile();
|
---|
245 | File target_file = null;
|
---|
246 | // Determine the target file for a copy or move.
|
---|
247 | if (job.type == FileJob.COPY || job.type == FileJob.MOVE) {
|
---|
248 | // 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
|
---|
249 | target_file = new File(destination_node.getFile(), origin_node.toString());
|
---|
250 | }
|
---|
251 | // 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.
|
---|
252 | if((job.type == FileJob.COPY || job.type == FileJob.MOVE) && !job.done) {
|
---|
253 | ///ystem.err.println("Copy/Move: " + origin_node);
|
---|
254 |
|
---|
255 | // 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
|
---|
256 | int max_folder_depth = Configuration.getInt("general.max_folder_depth", Configuration.COLLECTION_SPECIFIC);
|
---|
257 | boolean continue_over_depth = false;
|
---|
258 | if (countFolderDepth(source_file) > max_folder_depth) {
|
---|
259 | Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("General.No"), Dictionary.get("FileActions.Increase_Depth") };
|
---|
260 | String args[] = { String.valueOf(max_folder_depth), source_file.getAbsolutePath() };
|
---|
261 | 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]);
|
---|
262 | args = null;
|
---|
263 | options = null;
|
---|
264 | switch(result) {
|
---|
265 | case 0: // Yes
|
---|
266 | continue_over_depth = true;
|
---|
267 | break;
|
---|
268 | case 2: // Continue and increase depth
|
---|
269 | continue_over_depth = true;
|
---|
270 | Configuration.setInt("general.max_folder_depth", Configuration.COLLECTION_SPECIFIC, (max_folder_depth + 1));
|
---|
271 | break;
|
---|
272 | }
|
---|
273 | }
|
---|
274 | else {
|
---|
275 | continue_over_depth = true;
|
---|
276 | }
|
---|
277 |
|
---|
278 | if(continue_over_depth) {
|
---|
279 | FileNode new_node = null;
|
---|
280 | // 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).
|
---|
281 | if(target_file.exists()) {
|
---|
282 | // We've previously been told
|
---|
283 | if(yes_to_all) {
|
---|
284 | // Remove the old file and tree entry.
|
---|
285 | target_file.delete();
|
---|
286 | ready = true;
|
---|
287 | }
|
---|
288 | else {
|
---|
289 | ///atherer.println("Opps! This filename already exists. Give the user some options.");
|
---|
290 | Object[] options = { Dictionary.get("General.Yes"), Dictionary.get("FileActions.Yes_To_All"), Dictionary.get("General.No"), Dictionary.get("General.Cancel") };
|
---|
291 | 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]);
|
---|
292 | switch(result) {
|
---|
293 | case 1: // Yes To All
|
---|
294 | yes_to_all = true;
|
---|
295 | case 0: // Yes
|
---|
296 | // Remove the old file and tree entry.
|
---|
297 | if(destination_node != null) {
|
---|
298 | TreePath destination_path = new TreePath(destination_node.getPath());
|
---|
299 | CollectionTreeNode temp_target_node = new CollectionTreeNode(target_file); // !!! , target_model, true);
|
---|
300 | TreePath target_path = destination_path.pathByAddingChild(temp_target_node);
|
---|
301 | SynchronizedTreeModelTools.removeNodeFromParent(target_model, target_model.getNode(target_path));
|
---|
302 | target_path = null;
|
---|
303 | temp_target_node = null;
|
---|
304 | destination_path = null;
|
---|
305 | }
|
---|
306 | target_file.delete();
|
---|
307 | ready = true;
|
---|
308 | break;
|
---|
309 | case 3: // No To All
|
---|
310 | cancel_action = true;
|
---|
311 | case 2: // No
|
---|
312 | default:
|
---|
313 | ready = false;
|
---|
314 | // Increment progress by size of potentially copied file
|
---|
315 | progress.addValue(origin_node.getFile().length());
|
---|
316 | }
|
---|
317 | }
|
---|
318 | }
|
---|
319 | // 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.
|
---|
320 | if(ready) {
|
---|
321 | // update status area
|
---|
322 | String args[] = new String[1];
|
---|
323 | args[0] = "" + (queue.size() + 1) + "";
|
---|
324 | if(job.type == FileJob.COPY) {
|
---|
325 | args[0] = formatPath("FileActions.Copying", source_file.getAbsolutePath(), file_status.getSize().width);
|
---|
326 | file_status.setText(Dictionary.get("FileActions.Copying", args));
|
---|
327 | }
|
---|
328 | else {
|
---|
329 | args[0] = formatPath("FileActions.Moving", source_file.getAbsolutePath(), file_status.getSize().width);
|
---|
330 | file_status.setText(Dictionary.get("FileActions.Moving", args));
|
---|
331 | }
|
---|
332 | args = null;
|
---|
333 |
|
---|
334 | // If source is a file
|
---|
335 | if(source_file.isFile()) {
|
---|
336 | // 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?
|
---|
337 | try {
|
---|
338 | copyFile(source_file, target_file, progress);
|
---|
339 | }
|
---|
340 | // 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.
|
---|
341 | catch(FileNotFoundException fnf_exception) {
|
---|
342 | DebugStream.printStackTrace(fnf_exception);
|
---|
343 | cancel_action = true;
|
---|
344 | // Show warning.
|
---|
345 | 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);
|
---|
346 | // Force refresh of source folder.
|
---|
347 | source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
|
---|
348 | }
|
---|
349 | catch(FileAlreadyExistsException fae_exception) {
|
---|
350 | DebugStream.printStackTrace(fae_exception);
|
---|
351 | cancel_action = true;
|
---|
352 | // Show warning.
|
---|
353 | 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);
|
---|
354 | // Nothing else can be done by the Gatherer.
|
---|
355 | }
|
---|
356 | catch(InsufficientSpaceException is_exception) {
|
---|
357 | DebugStream.printStackTrace(is_exception);
|
---|
358 | cancel_action = true;
|
---|
359 | // Show warning. The message body of the expection explains how much more space is required for this file copy.
|
---|
360 | JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Insufficient_Space_Message", is_exception.getMessage()), Dictionary.get("FileActions.Insufficient_Space_Title"), JOptionPane.ERROR_MESSAGE);
|
---|
361 | // 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.
|
---|
362 | }
|
---|
363 | catch (ReadNotPermittedException rnp_exception) {
|
---|
364 | if (DebugStream.isDebuggingEnabled()) {
|
---|
365 | DebugStream.printStackTrace(rnp_exception);
|
---|
366 | }
|
---|
367 | cancel_action = true;
|
---|
368 | // Show warning
|
---|
369 | 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);
|
---|
370 | // Nothing else we can do.
|
---|
371 | }
|
---|
372 | catch(UnknownFileErrorException ufe_exception) {
|
---|
373 | DebugStream.printStackTrace(ufe_exception);
|
---|
374 | cancel_action = true;
|
---|
375 | // Show warning
|
---|
376 | JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("FileActions.Unknown_File_Error_Message"), Dictionary.get("FileActions.Unknown_File_Error_Title"), JOptionPane.ERROR_MESSAGE);
|
---|
377 | // Nothing else we can do.
|
---|
378 | }
|
---|
379 | catch(WriteNotPermittedException wnp_exception) {
|
---|
380 | if (DebugStream.isDebuggingEnabled()) {
|
---|
381 | DebugStream.printStackTrace(wnp_exception);
|
---|
382 | }
|
---|
383 | cancel_action = true;
|
---|
384 | // Show warning
|
---|
385 | 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);
|
---|
386 | // Nothing else we can do.
|
---|
387 | }
|
---|
388 | catch(IOException exception) {
|
---|
389 | // Can't really do much about this.
|
---|
390 | DebugStream.printStackTrace(exception);
|
---|
391 | }
|
---|
392 | // If not cancelled
|
---|
393 | if (!cancel_action) {
|
---|
394 | // Create a dummy FileNode with the correct structure (so getPath works)
|
---|
395 | new_node = new CollectionTreeNode(target_file);
|
---|
396 | SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, new_node);
|
---|
397 | }
|
---|
398 | }
|
---|
399 | // Else
|
---|
400 | else if(source_file.isDirectory()) {
|
---|
401 | // create new record
|
---|
402 | CollectionTreeNode directory_record = new CollectionTreeNode(target_file);
|
---|
403 | SynchronizedTreeModelTools.insertNodeInto(target_model, destination_node, directory_record);
|
---|
404 | // Why is this not happening eh?
|
---|
405 | directory_record.setParent(destination_node);
|
---|
406 | if(!target_file.exists()) {
|
---|
407 | // make the directory
|
---|
408 | target_file.mkdirs();
|
---|
409 | new_node = directory_record;
|
---|
410 | }
|
---|
411 | // Else inform the users that a directory already exists and files will be copied into it
|
---|
412 | //else {
|
---|
413 | // JOptionPane.showMessageDialog(null, Dictionary.get("FileActions.Directory_Exists", target_file.toString()), Dictionary.get("General.Warning"), JOptionPane.WARNING_MESSAGE);
|
---|
414 | //}
|
---|
415 | // 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.
|
---|
416 | FileNode child_record = null;
|
---|
417 | // 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.
|
---|
418 | // -- Starting queue ...[a]
|
---|
419 | // remove(position) = 'a' ...
|
---|
420 | // add(position, 'b') ...[b]
|
---|
421 | // add(position, 'c') ...[c][b]
|
---|
422 | // add(position, 'd') ...[d][c][b]
|
---|
423 | // Next loop
|
---|
424 | // remove(position) = 'b' ...[d][c]
|
---|
425 | for(int i = 0; i < origin_node.getChildCount(); i++) {
|
---|
426 | child_record = (FileNode) origin_node.getChildAt(i);
|
---|
427 | addJob(job.ID(), job.source, child_record, job.target, directory_record, job.type, false, position);
|
---|
428 | }
|
---|
429 | child_record = null;
|
---|
430 | directory_record = null;
|
---|
431 | }
|
---|
432 | // The file wasn't found!
|
---|
433 | else {
|
---|
434 | cancel_action = true;
|
---|
435 | // Show warning.
|
---|
436 | 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);
|
---|
437 | // Force refresh of source folder.
|
---|
438 | source_model.refresh(new TreePath(((FileNode)origin_node.getParent()).getPath()));
|
---|
439 | }
|
---|
440 |
|
---|
441 | // If we haven't been cancelled and we created a new FileNode during the above phase, now is the time to deal with metadata
|
---|
442 | if (!cancel_action && new_node != null) {
|
---|
443 | // If the file came from inside our collection...
|
---|
444 | if (job.source.toString().equals("Collection")) {
|
---|
445 | // Get the non-folder level metadata assigned to the origin node...
|
---|
446 | ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(source_file);
|
---|
447 | // ...and remove it from the original node and assign it to the new folder
|
---|
448 | for (int i = 0; i < assigned_metadata.size(); i++) {
|
---|
449 | MetadataValue metadata_value = (MetadataValue) assigned_metadata.get(i);
|
---|
450 | MetadataXMLFileManager.removeMetadata((CollectionTreeNode) origin_node, metadata_value);
|
---|
451 | MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_node, metadata_value);
|
---|
452 | }
|
---|
453 | }
|
---|
454 | // If it came from the workspace search for metadata assigned to the file
|
---|
455 | else if (job.source.toString().equals("Workspace")) {
|
---|
456 | ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToExternalFile(origin_node.getFile());
|
---|
457 | for (int i = 0; i < assigned_metadata.size(); i++) {
|
---|
458 | MetadataValue metadata_value = (MetadataValue) assigned_metadata.get(i);
|
---|
459 | MetadataXMLFileManager.addMetadata((CollectionTreeNode) new_node, metadata_value);
|
---|
460 | }
|
---|
461 | }
|
---|
462 |
|
---|
463 | if (job.type == FileJob.COPY && new_node.getFile().isFile()) {
|
---|
464 | Gatherer.c_man.fireFileAddedToCollection(new_node.getFile());
|
---|
465 | }
|
---|
466 | }
|
---|
467 | new_node = null;
|
---|
468 | }
|
---|
469 | }
|
---|
470 | }
|
---|
471 | // 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.
|
---|
472 | if(!cancel_action && ready && (job.type == FileJob.DELETE || job.type == FileJob.MOVE)) {
|
---|
473 | // Update the progress bar for this job
|
---|
474 | if (source_file.isFile()) {
|
---|
475 | progress.addValue(source_file.length());
|
---|
476 | }
|
---|
477 |
|
---|
478 | // If the source is a file or an empty directory (but not the root node of a tree)
|
---|
479 | File[] child_list = source_file.listFiles();
|
---|
480 | if (source_file.isFile() || (child_list != null && child_list.length == 0 && origin_node.getParent() != null)) {
|
---|
481 | // Update status area
|
---|
482 | String args[] = new String[1];
|
---|
483 | args[0] = formatPath("FileActions.Deleting", source_file.getAbsolutePath(), file_status.getSize().width);
|
---|
484 | file_status.setText(Dictionary.get("FileActions.Deleting", args));
|
---|
485 |
|
---|
486 | // If it is a metadata.xml file, we must unload it
|
---|
487 | if (source_file.getName().equals(StaticStrings.METADATA_XML)) {
|
---|
488 | MetadataXMLFileManager.unloadMetadataXMLFile(source_file);
|
---|
489 | }
|
---|
490 |
|
---|
491 | // Remove the metadata assigned directly to the file
|
---|
492 | ArrayList assigned_metadata = MetadataXMLFileManager.getMetadataAssignedDirectlyToFile(origin_node.getFile());
|
---|
493 | for (int i = 0; i < assigned_metadata.size(); i++) {
|
---|
494 | MetadataValue metadata_value = (MetadataValue) assigned_metadata.get(i);
|
---|
495 | MetadataXMLFileManager.removeMetadata((CollectionTreeNode) origin_node, metadata_value);
|
---|
496 | }
|
---|
497 |
|
---|
498 | // Remove from model
|
---|
499 | FileNode parent_record = (FileNode) origin_node.getParent();
|
---|
500 | if (parent_record != null) {
|
---|
501 | SynchronizedTreeModelTools.removeNodeFromParent(source_model, origin_node);
|
---|
502 | }
|
---|
503 |
|
---|
504 | // Delete the source file
|
---|
505 | Utility.delete(source_file);
|
---|
506 | }
|
---|
507 | // Else the source is a directory and it has children remaining
|
---|
508 | else if(child_list != null && child_list.length > 0) {
|
---|
509 | // Don't worry about all this for true file move actions.
|
---|
510 | if(job.type == FileJob.DELETE) {
|
---|
511 | // 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.
|
---|
512 | origin_node.refresh();
|
---|
513 | for(int i = 0; i < origin_node.size(); i++) {
|
---|
514 | FileNode child_record = (FileNode) origin_node.getChildAtUnfiltered(i);
|
---|
515 | ///atherer.println("Queuing: " + child_record);
|
---|
516 | addJob(job.ID(), job.source, child_record, job.target, destination_node, FileJob.DELETE, false, position);
|
---|
517 | }
|
---|
518 | }
|
---|
519 | // 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.
|
---|
520 | // One special case. Do not requeue root nodes. Don't requeue jobs marked as done.
|
---|
521 | if(origin_node.getParent() != null && !job.done) {
|
---|
522 | ///atherer.println("Requeuing: " + origin_node.getFile().getAbsolutePath());
|
---|
523 | job.type = FileJob.DELETE; // You only requeue jobs that are deletes, as directories must be inspected before children, but deleted after.
|
---|
524 | addJob(job, position);
|
---|
525 | }
|
---|
526 | else {
|
---|
527 | DebugStream.println("I've already done this job twice. I refuse to requeue it again!");
|
---|
528 | }
|
---|
529 | }
|
---|
530 | }
|
---|
531 | job = null;
|
---|
532 | source_file = null;
|
---|
533 | target_file = null;
|
---|
534 | origin_node = null;
|
---|
535 |
|
---|
536 | // We only break out of the while loop if we are out of files or the action was cancelled
|
---|
537 | if (cancel_action) {
|
---|
538 | // Empty queue
|
---|
539 | clearJobs();
|
---|
540 | cancel_action = false;
|
---|
541 | }
|
---|
542 | }
|
---|
543 | else { // job == null
|
---|
544 | // Disable stop button
|
---|
545 | if (stop_button != null) {
|
---|
546 | stop_button.setEnabled(false);
|
---|
547 | }
|
---|
548 | synchronized(this) {
|
---|
549 | // Force both workspace and collection trees to refresh
|
---|
550 | if (Gatherer.g_man != null) {
|
---|
551 | Gatherer.g_man.refreshWorkspaceTree(DragTree.COLLECTION_CONTENTS_CHANGED);
|
---|
552 | Gatherer.g_man.refreshCollectionTree(DragTree.COLLECTION_CONTENTS_CHANGED);
|
---|
553 | }
|
---|
554 |
|
---|
555 | // Reset status area
|
---|
556 | file_status.setText(Dictionary.get("FileActions.No_Activity"));
|
---|
557 | progress.reset();
|
---|
558 | progress.setString(Dictionary.get("FileActions.No_Activity"));
|
---|
559 | yes_to_all = false;
|
---|
560 | try {
|
---|
561 | wait();
|
---|
562 | }
|
---|
563 | catch (InterruptedException exception) {}
|
---|
564 | }
|
---|
565 | }
|
---|
566 | }
|
---|
567 | catch (Exception error) {
|
---|
568 | DebugStream.printStackTrace(error);
|
---|
569 | }
|
---|
570 | }
|
---|
571 | }
|
---|
572 |
|
---|
573 |
|
---|
574 | /** Register the button that will be responsible for stopping executing file actions.
|
---|
575 | * @param stop_button a JButton
|
---|
576 | */
|
---|
577 | public void registerStopButton(JButton stop_button) {
|
---|
578 | this.stop_button = stop_button;
|
---|
579 | }
|
---|
580 |
|
---|
581 |
|
---|
582 | synchronized private void clearJobs() {
|
---|
583 | queue.clear();
|
---|
584 | }
|
---|
585 |
|
---|
586 | /** Copy the contents from the source directory to the destination
|
---|
587 | * directory.
|
---|
588 | * @param source The source directory
|
---|
589 | * @param destination The destination directory
|
---|
590 | * @param progress A progress bar to monitor copying progress
|
---|
591 | * @see org.greenstone.gatherer.Gatherer
|
---|
592 | */
|
---|
593 | public void copyDirectoryContents(File source, File destination, LongProgressBar progress)
|
---|
594 | throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, ReadNotPermittedException, UnknownFileErrorException, WriteNotPermittedException
|
---|
595 | {
|
---|
596 | if (!source.isDirectory()) return;
|
---|
597 | // check that dest dirs exist
|
---|
598 | destination.mkdirs();
|
---|
599 |
|
---|
600 | File [] src_files = source.listFiles();
|
---|
601 | if (src_files.length == 0) return; // nothing to copy
|
---|
602 | for (int i=0; i<src_files.length; i++) {
|
---|
603 | File f = src_files[i];
|
---|
604 | String f_name = f.getName();
|
---|
605 | File new_file = new File(destination, f_name);
|
---|
606 | if (f.isDirectory()) {
|
---|
607 | copyDirectoryContents(f, new_file, progress);
|
---|
608 | } else if (f.isFile()) {
|
---|
609 | copyFile(f, new_file, progress);
|
---|
610 | }
|
---|
611 | }
|
---|
612 |
|
---|
613 | }
|
---|
614 |
|
---|
615 | /** Copy a file from the source location to the destination location.
|
---|
616 | * @param source The source File.
|
---|
617 | * @param destination The destination File.
|
---|
618 | * @see org.greenstone.gatherer.Gatherer
|
---|
619 | */
|
---|
620 | public void copyFile(File source, File destination, LongProgressBar progress)
|
---|
621 | throws FileAlreadyExistsException, FileNotFoundException, InsufficientSpaceException, IOException, ReadNotPermittedException, UnknownFileErrorException, WriteNotPermittedException {
|
---|
622 | if(source.isDirectory()) {
|
---|
623 | destination.mkdirs();
|
---|
624 | }
|
---|
625 | else {
|
---|
626 | // Check if the origin file exists.
|
---|
627 | if (!source.exists()) {
|
---|
628 | DebugStream.println("Couldn't find the source file.");
|
---|
629 | throw(new FileNotFoundException());
|
---|
630 | }
|
---|
631 |
|
---|
632 | // Make sure the destination file does not exist.
|
---|
633 | if (destination.exists()) {
|
---|
634 | throw(new FileAlreadyExistsException());
|
---|
635 | }
|
---|
636 |
|
---|
637 | // Open an input stream to the source file
|
---|
638 | FileInputStream f_in = null;
|
---|
639 | try {
|
---|
640 | f_in = new FileInputStream(source);
|
---|
641 | }
|
---|
642 | catch (FileNotFoundException exception) {
|
---|
643 | // A FileNotFoundException translates into a ReadNotPermittedException in this case
|
---|
644 | throw new ReadNotPermittedException(exception.toString());
|
---|
645 | }
|
---|
646 |
|
---|
647 | // Create an necessary directories for the target file
|
---|
648 | File dirs = destination.getParentFile();
|
---|
649 | dirs.mkdirs();
|
---|
650 |
|
---|
651 | // Open an output stream to the target file
|
---|
652 | FileOutputStream f_out = null;
|
---|
653 | try {
|
---|
654 | f_out = new FileOutputStream(destination);
|
---|
655 | }
|
---|
656 | catch (FileNotFoundException exception) {
|
---|
657 | // A FileNotFoundException translates into a WriteNotPermittedException in this case
|
---|
658 | throw new WriteNotPermittedException(exception.toString());
|
---|
659 | }
|
---|
660 |
|
---|
661 | // Copy the file
|
---|
662 | byte data[] = new byte[Utility.BUFFER_SIZE];
|
---|
663 | int data_size = 0;
|
---|
664 | while((data_size = f_in.read(data, 0, Utility.BUFFER_SIZE)) != -1 && !cancel_action) {
|
---|
665 | long destination_size = destination.length();
|
---|
666 | try {
|
---|
667 | f_out.write(data, 0, data_size);
|
---|
668 | }
|
---|
669 | // 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.
|
---|
670 | catch (IOException io_exception) {
|
---|
671 | if(destination_size + (long) data_size > destination.length()) {
|
---|
672 | // Determine the difference (which I guess is in bytes).
|
---|
673 | long difference = (destination_size + (long) data_size) - destination.length();
|
---|
674 | // Transform that into a human readable string.
|
---|
675 | String message = Utility.formatFileLength(difference);
|
---|
676 | throw(new InsufficientSpaceException(message));
|
---|
677 | }
|
---|
678 | else {
|
---|
679 | throw(io_exception);
|
---|
680 | }
|
---|
681 | }
|
---|
682 | if(progress != null) {
|
---|
683 | progress.addValue(data_size);
|
---|
684 | }
|
---|
685 | }
|
---|
686 | // Flush and close the streams to ensure all bytes are written.
|
---|
687 | f_in.close();
|
---|
688 | f_out.close();
|
---|
689 | // We have now, in theory, produced an exact copy of the source file. Check this by comparing sizes.
|
---|
690 | if(!destination.exists() || (!cancel_action && source.length() != destination.length())) {
|
---|
691 | throw(new UnknownFileErrorException());
|
---|
692 | }
|
---|
693 | // If we were cancelled, ensure that none of the destination file exists.
|
---|
694 | if(cancel_action) {
|
---|
695 | destination.delete();
|
---|
696 | }
|
---|
697 | }
|
---|
698 | }
|
---|
699 | }
|
---|