source: trunk/gli/src/org/greenstone/gatherer/remote/RemoteGreenstoneServer.java@ 13591

Last change on this file since 13591 was 13591, checked in by mdewsnip, 17 years ago

Tidied up all the CollectionManager functions for getting loaded collection paths, and made them static, as part of making CollectionManager fully static.

  • Property svn:keywords set to Author Date Id Revision
File size: 44.4 KB
Line 
1/**
2 *#########################################################################
3 *
4 * A component of the Gatherer application, part of the Greenstone digital
5 * library suite from the New Zealand Digital Library Project at the
6 * University of Waikato, New Zealand.
7 *
8 * Author: Michael Dewsnip, NZDL Project, University of Waikato
9 *
10 * Copyright (C) 2005 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
28package org.greenstone.gatherer.remote;
29
30import java.io.*;
31import java.net.*;
32import java.util.*;
33import java.util.zip.*;
34import javax.swing.*;
35import org.greenstone.gatherer.Configuration;
36import org.greenstone.gatherer.DebugStream;
37import org.greenstone.gatherer.Dictionary;
38import org.greenstone.gatherer.GAuthenticator;
39import org.greenstone.gatherer.Gatherer;
40import org.greenstone.gatherer.collection.CollectionManager;
41import org.greenstone.gatherer.shell.GShell;
42import org.greenstone.gatherer.util.UnzipTools;
43import org.greenstone.gatherer.util.Utility;
44
45
46public class RemoteGreenstoneServer
47{
48 // ----------------------------------------------------------------------------------------------------
49 // PUBLIC LAYER
50 // ----------------------------------------------------------------------------------------------------
51
52
53 static public String deleteCollection(String collection_name)
54 {
55 return performAction(new RemoteGreenstoneServerDeleteCollectionAction(collection_name));
56 }
57
58
59 static public String deleteCollectionFile(String collection_name, File collection_file)
60 {
61 return performAction(new RemoteGreenstoneServerDeleteCollectionFileAction(collection_name, collection_file));
62 }
63
64
65 static public String downloadCollection(String collection_name)
66 {
67 return performAction(new RemoteGreenstoneServerDownloadCollectionAction(collection_name));
68 }
69
70
71 static public String downloadCollectionArchives(String collection_name)
72 {
73 return performAction(new RemoteGreenstoneServerDownloadCollectionArchivesAction(collection_name));
74 }
75
76
77 static public String downloadCollectionConfigurations()
78 {
79 return performAction(new RemoteGreenstoneServerDownloadCollectionConfigurationsAction());
80 }
81
82
83 static public String downloadCollectionFile(String collection_name, File collection_file)
84 {
85 return performAction(new RemoteGreenstoneServerDownloadCollectionFileAction(collection_name, collection_file));
86 }
87
88
89 static public String getScriptOptions(String script_name, String script_arguments)
90 {
91 return performAction(new RemoteGreenstoneServerGetScriptOptionsAction(script_name, script_arguments));
92 }
93
94
95 static public String moveCollectionFile(String collection_name, File source_collection_file, File target_collection_file)
96 {
97 return performAction(new RemoteGreenstoneServerMoveCollectionFileAction(collection_name, source_collection_file, target_collection_file));
98 }
99
100
101 static public String newCollectionDirectory(String collection_name, File new_collection_directory)
102 {
103 return performAction(new RemoteGreenstoneServerNewCollectionDirectoryAction(collection_name, new_collection_directory));
104 }
105
106
107 static public String runScript(String collection_name, String script_name, String script_arguments, GShell shell)
108 {
109 return performAction(new RemoteGreenstoneServerRunScriptAction(collection_name, script_name, script_arguments, shell));
110 }
111
112
113 static public String uploadCollectionFile(String collection_name, File collection_file)
114 {
115 return performAction(new RemoteGreenstoneServerUploadCollectionFilesAction(collection_name, new File[] { collection_file }));
116 }
117
118
119 static public String uploadCollectionFiles(String collection_name, File[] collection_files)
120 {
121 return performAction(new RemoteGreenstoneServerUploadCollectionFilesAction(collection_name, collection_files));
122 }
123
124
125 static public String uploadFilesIntoCollection(String collection_name, File[] source_files, File target_collection_directory)
126 {
127 return performAction(new RemoteGreenstoneServerUploadFilesIntoCollectionAction(collection_name, source_files, target_collection_directory));
128 }
129
130
131 // ----------------------------------------------------------------------------------------------------
132
133
134 static public void exit()
135 {
136 System.err.println("Exiting, number of jobs on queue: " + remote_greenstone_server_action_queue.size());
137
138 // If there are still jobs on the queue we must wait for the jobs to finish
139 while (remote_greenstone_server_action_queue.size() > 0) {
140 synchronized (remote_greenstone_server_action_queue) {
141 try {
142 DebugStream.println("Waiting for queue to become empty...");
143 remote_greenstone_server_action_queue.wait(500);
144 }
145 catch (InterruptedException exception) {}
146 }
147 }
148 }
149
150
151 // ----------------------------------------------------------------------------------------------------
152 // QUEUE LAYER
153 // ----------------------------------------------------------------------------------------------------
154
155
156 /** Returns null if we cannot wait for the action to finish, "" if the action failed, or the action output. */
157 static private String performAction(RemoteGreenstoneServerAction remote_greenstone_server_action)
158 {
159 // Add the action to the queue
160 remote_greenstone_server_action_queue.addAction(remote_greenstone_server_action);
161
162 // If we're running in the GUI thread we must return immediately
163 // We cannot wait for the action to complete because this will block any GUI updates
164 if (SwingUtilities.isEventDispatchThread()) {
165 System.err.println("WARNING: In event dispatch thread, returning immediately...");
166 return null;
167 }
168
169 // Otherwise wait until the action is processed
170 while (!remote_greenstone_server_action.processed) {
171 synchronized (remote_greenstone_server_action) {
172 try {
173 DebugStream.println("Waiting for action to complete...");
174 remote_greenstone_server_action.wait(500);
175 }
176 catch (InterruptedException exception) {}
177 }
178 }
179
180 // Return "" if the action failed
181 if (!remote_greenstone_server_action.processed_successfully) {
182 return "";
183 }
184 // Otherwise return the action output
185 return remote_greenstone_server_action.action_output;
186 }
187
188
189 static private RemoteGreenstoneServerActionQueue remote_greenstone_server_action_queue = new RemoteGreenstoneServerActionQueue();
190
191
192 static private class RemoteGreenstoneServerActionQueue
193 extends Thread
194 {
195 /** The queue of waiting jobs. */
196 private ArrayList queue = null;
197
198
199 public RemoteGreenstoneServerActionQueue()
200 {
201 if (Gatherer.isGsdlRemote) {
202 queue = new ArrayList();
203 start();
204 }
205 }
206
207
208 synchronized public void addAction(RemoteGreenstoneServerAction remote_greenstone_server_action)
209 {
210 queue.add(remote_greenstone_server_action);
211 notifyAll();
212 }
213
214
215 public int size()
216 {
217 return queue.size();
218 }
219
220
221 public void run()
222 {
223 while (true) {
224 // If there are jobs on the queue, get the next in line and process it
225 if (queue.size() > 0) {
226 RemoteGreenstoneServerAction remote_greenstone_server_action = (RemoteGreenstoneServerAction) queue.get(0);
227
228 try {
229 remote_greenstone_server_action.perform();
230
231 // No exceptions were thrown, so the action was successful
232 remote_greenstone_server_action.processed_successfully = true;
233 }
234 catch (RemoteGreenstoneServerActionCancelledException exception) {
235 remote_greenstone_server_action.processed_successfully = false;
236 }
237 catch (Exception exception) {
238 DebugStream.printStackTrace(exception);
239 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", exception.getMessage()), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
240 remote_greenstone_server_action.processed_successfully = false;
241 }
242
243 // We're done with this action, for better or worse
244 remote_greenstone_server_action.processed = true;
245 queue.remove(0);
246 }
247
248 // Otherwise the queue is empty
249 else {
250 progress_bar.setAction(null);
251
252 // Wait until we are notify()ed by addAction that there is a new job on the queue
253 synchronized (this) {
254 try {
255 wait();
256 }
257 catch (InterruptedException exception) { }
258 }
259 }
260 }
261 }
262 }
263
264
265 // ----------------------------------------------------------------------------------------------------
266 // PROGRESS BAR
267 // ----------------------------------------------------------------------------------------------------
268
269
270 static private RemoteGreenstoneServerProgressBar progress_bar = new RemoteGreenstoneServerProgressBar();
271
272
273 static private class RemoteGreenstoneServerProgressBar
274 extends JProgressBar
275 {
276 public RemoteGreenstoneServerProgressBar()
277 {
278 setBackground(Configuration.getColor("coloring.collection_tree_background", false));
279 setForeground(Configuration.getColor("coloring.collection_tree_foreground", false));
280 setString(Dictionary.get("FileActions.No_Activity"));
281 setStringPainted(true);
282 }
283
284
285 public void setAction(String action)
286 {
287 if (action != null) {
288 DebugStream.println(action);
289 }
290
291 // We cannot call this from the GUI thread otherwise the progress bar won't start
292 if (SwingUtilities.isEventDispatchThread()) {
293 System.err.println("ERROR: RemoteGreenstoneServerProgressBar.setAction() called from event dispatch thread!");
294 return;
295 }
296
297 // Set the string on the progress bar, and start or stop it
298 if (action == null) {
299 setString(Dictionary.get("FileActions.No_Activity"));
300 setIndeterminate(false);
301 }
302 else {
303 setString(action);
304 setIndeterminate(true);
305 }
306 }
307 }
308
309
310 static public RemoteGreenstoneServerProgressBar getProgressBar()
311 {
312 return progress_bar;
313 }
314
315
316 // ----------------------------------------------------------------------------------------------------
317 // ACTIONS
318 // ----------------------------------------------------------------------------------------------------
319
320
321 static private abstract class RemoteGreenstoneServerAction
322 {
323 public String action_output = null;
324 public boolean processed = false;
325 public boolean processed_successfully;
326
327 abstract public void perform()
328 throws Exception;
329 }
330
331
332 static private class RemoteGreenstoneServerActionCancelledException
333 extends Exception
334 {
335 }
336
337
338 /**
339 * --------------------------------------------------------------------------------------------
340 * DELETE COLLECTION
341 * --------------------------------------------------------------------------------------------
342 */
343 static private class RemoteGreenstoneServerDeleteCollectionAction
344 extends RemoteGreenstoneServerAction
345 {
346 private String collection_name;
347
348 public RemoteGreenstoneServerDeleteCollectionAction(String collection_name)
349 {
350 this.collection_name = collection_name;
351 }
352
353 public void perform()
354 throws Exception
355 {
356 progress_bar.setAction("Deleting collection " + collection_name + "...");
357
358 String delete_collection_command = "cmd=delete-collection";
359 delete_collection_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
360 action_output = sendCommandToServer(delete_collection_command, null);
361 }
362 }
363
364
365 /**
366 * --------------------------------------------------------------------------------------------
367 * DELETE COLLECTION FILE
368 * --------------------------------------------------------------------------------------------
369 */
370 static private class RemoteGreenstoneServerDeleteCollectionFileAction
371 extends RemoteGreenstoneServerAction
372 {
373 private String collection_name;
374 private File collection_file;
375
376 public RemoteGreenstoneServerDeleteCollectionFileAction(String collection_name, File collection_file)
377 {
378 this.collection_name = collection_name;
379 this.collection_file = collection_file;
380 }
381
382 public void perform()
383 throws Exception
384 {
385 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
386 String collection_file_relative_path = getPathRelativeToDirectory(collection_file, collection_directory_path);
387 collection_file_relative_path = collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
388 progress_bar.setAction("Deleting collection file " + collection_file_relative_path + "...");
389
390 String delete_collection_file_command = "cmd=delete-collection-file";
391 delete_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
392 delete_collection_file_command += "&file=" + URLEncoder.encode(collection_file_relative_path, "UTF-8");
393 action_output = sendCommandToServer(delete_collection_file_command, null);
394 }
395 }
396
397
398 /**
399 * --------------------------------------------------------------------------------------------
400 * DOWNLOAD COLLECTION
401 * --------------------------------------------------------------------------------------------
402 */
403 static private class RemoteGreenstoneServerDownloadCollectionAction
404 extends RemoteGreenstoneServerAction
405 {
406 private String collection_name;
407
408 public RemoteGreenstoneServerDownloadCollectionAction(String collection_name)
409 {
410 this.collection_name = collection_name;
411 }
412
413 public void perform()
414 throws Exception
415 {
416 progress_bar.setAction("Downloading remote collection " + collection_name + "...");
417
418 String download_collection_command = "cmd=download-collection";
419 download_collection_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
420 String zip_file_path = Gatherer.getCollectDirectoryPath() + collection_name + ".zip";
421 action_output = downloadFile(download_collection_command, zip_file_path);
422
423 // Delete the existing (local) collection
424 Gatherer.c_man.deleteCollection(collection_name);
425
426 // Unzip the collection just downloaded
427 UnzipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
428 }
429 }
430
431
432 /**
433 * --------------------------------------------------------------------------------------------
434 * DOWNLOAD COLLECTION ARCHIVES
435 * --------------------------------------------------------------------------------------------
436 */
437 static private class RemoteGreenstoneServerDownloadCollectionArchivesAction
438 extends RemoteGreenstoneServerAction
439 {
440 private String collection_name;
441
442 public RemoteGreenstoneServerDownloadCollectionArchivesAction(String collection_name)
443 {
444 this.collection_name = collection_name;
445 }
446
447 public void perform()
448 throws Exception
449 {
450 progress_bar.setAction("Downloading collection archives for " + collection_name + "...");
451
452 String download_collection_archives_command = "cmd=download-collection-archives";
453 download_collection_archives_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
454 String zip_file_path = Gatherer.getCollectDirectoryPath() + collection_name + "-archives.zip";
455 action_output = downloadFile(download_collection_archives_command, zip_file_path);
456
457 // Delete the existing (local) collection archives
458 Utility.delete(new File(CollectionManager.getLoadedCollectionArchivesDirectoryPath()));
459
460 // Unzip the collection archives just downloaded
461 UnzipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
462 }
463 }
464
465
466 /**
467 * --------------------------------------------------------------------------------------------
468 * DOWNLOAD COLLECTION CONFIGURATIONS
469 * --------------------------------------------------------------------------------------------
470 */
471 static private class RemoteGreenstoneServerDownloadCollectionConfigurationsAction
472 extends RemoteGreenstoneServerAction
473 {
474 public RemoteGreenstoneServerDownloadCollectionConfigurationsAction()
475 {
476 }
477
478 public void perform()
479 throws Exception
480 {
481 progress_bar.setAction("Downloading collection configurations...");
482
483 // Delete the existing (local) collect directory
484 Utility.delete(new File(Gatherer.getCollectDirectoryPath()));
485 new File(Gatherer.getCollectDirectoryPath()).mkdirs();
486
487 String download_collection_configurations_command = "cmd=download-collection-configurations";
488 String zip_file_path = Gatherer.getCollectDirectoryPath() + "collections.zip";
489 action_output = downloadFile(download_collection_configurations_command, zip_file_path);
490
491 // Unzip the collection configurations just downloaded
492 UnzipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
493 }
494 }
495
496
497 /**
498 * --------------------------------------------------------------------------------------------
499 * DOWNLOAD COLLECTION FILE
500 * --------------------------------------------------------------------------------------------
501 */
502 static private class RemoteGreenstoneServerDownloadCollectionFileAction
503 extends RemoteGreenstoneServerAction
504 {
505 private String collection_name;
506 private File collection_file;
507
508 public RemoteGreenstoneServerDownloadCollectionFileAction(String collection_name, File collection_file)
509 {
510 this.collection_name = collection_name;
511 this.collection_file = collection_file;
512 }
513
514 public void perform()
515 throws Exception
516 {
517 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
518 String collection_file_relative_path = getPathRelativeToDirectory(collection_file, collection_directory_path);
519 collection_file_relative_path = collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
520 progress_bar.setAction("Downloading collection file " + collection_file_relative_path + "...");
521
522 String download_collection_file_command = "cmd=download-collection-file";
523 download_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
524 download_collection_file_command += "&file=" + URLEncoder.encode(collection_file_relative_path, "UTF-8");
525 String zip_file_name = collection_name + "-" + collection_file.getName() + ".zip";
526 String zip_file_path = collection_directory_path + zip_file_name;
527 action_output = downloadFile(download_collection_file_command, zip_file_path);
528
529 // Unzip the collection file just downloaded
530 UnzipTools.unzipFile(zip_file_path, collection_directory_path);
531 }
532 }
533
534
535 /**
536 * --------------------------------------------------------------------------------------------
537 * GET SCRIPT OPTIONS
538 * --------------------------------------------------------------------------------------------
539 */
540 static private class RemoteGreenstoneServerGetScriptOptionsAction
541 extends RemoteGreenstoneServerAction
542 {
543 private String script_name;
544 private String script_arguments;
545
546 public RemoteGreenstoneServerGetScriptOptionsAction(String script_name, String script_arguments)
547 {
548 this.script_name = script_name;
549 this.script_arguments = script_arguments;
550 }
551
552 public void perform()
553 throws Exception
554 {
555 progress_bar.setAction("Getting options for " + script_name + "...");
556
557 String get_script_options_command = "cmd=get-script-options";
558 get_script_options_command += "&script=" + script_name;
559 get_script_options_command += "&xml=";
560 get_script_options_command += "&language=" + Configuration.getLanguage();
561 get_script_options_command += script_arguments;
562 action_output = sendCommandToServer(get_script_options_command, null);
563 }
564 }
565
566
567 /**
568 * --------------------------------------------------------------------------------------------
569 * MOVE COLLECTION FILE
570 * --------------------------------------------------------------------------------------------
571 */
572 static private class RemoteGreenstoneServerMoveCollectionFileAction
573 extends RemoteGreenstoneServerAction
574 {
575 private String collection_name;
576 private File source_collection_file;
577 private File target_collection_file;
578
579 public RemoteGreenstoneServerMoveCollectionFileAction(String collection_name, File source_collection_file, File target_collection_file)
580 {
581 this.collection_name = collection_name;
582 this.source_collection_file = source_collection_file;
583 this.target_collection_file = target_collection_file;
584 }
585
586 public void perform()
587 throws Exception
588 {
589 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
590 String source_collection_file_relative_path = getPathRelativeToDirectory(source_collection_file, collection_directory_path);
591 source_collection_file_relative_path = source_collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
592 String target_collection_file_relative_path = getPathRelativeToDirectory(target_collection_file, collection_directory_path);
593 target_collection_file_relative_path = target_collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
594 progress_bar.setAction("Moving file " + source_collection_file_relative_path + " -> " + target_collection_file_relative_path + "...");
595
596 String move_collection_file_command = "cmd=move-collection-file";
597 move_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
598 move_collection_file_command += "&source=" + URLEncoder.encode(source_collection_file_relative_path, "UTF-8");
599 move_collection_file_command += "&target=" + URLEncoder.encode(target_collection_file_relative_path, "UTF-8");
600 action_output = sendCommandToServer(move_collection_file_command, null);
601 }
602 }
603
604
605 /**
606 * --------------------------------------------------------------------------------------------
607 * NEW COLLECTION DIRECTORY
608 * --------------------------------------------------------------------------------------------
609 */
610 static private class RemoteGreenstoneServerNewCollectionDirectoryAction
611 extends RemoteGreenstoneServerAction
612 {
613 private String collection_name;
614 private File new_collection_directory;
615
616 public RemoteGreenstoneServerNewCollectionDirectoryAction(String collection_name, File new_collection_directory)
617 {
618 this.collection_name = collection_name;
619 this.new_collection_directory = new_collection_directory;
620 }
621
622 public void perform()
623 throws Exception
624 {
625 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
626 String new_collection_directory_relative_path = getPathRelativeToDirectory(new_collection_directory, collection_directory_path);
627 new_collection_directory_relative_path = new_collection_directory_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
628 progress_bar.setAction("Creating new directory " + new_collection_directory_relative_path + "...");
629
630 String new_collection_directory_command = "cmd=new-collection-directory";
631 new_collection_directory_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
632 new_collection_directory_command += "&directory=" + URLEncoder.encode(new_collection_directory_relative_path, "UTF-8");
633 action_output = sendCommandToServer(new_collection_directory_command, null);
634 }
635 }
636
637
638 /**
639 * --------------------------------------------------------------------------------------------
640 * RUN SCRIPT
641 * --------------------------------------------------------------------------------------------
642 */
643 static private class RemoteGreenstoneServerRunScriptAction
644 extends RemoteGreenstoneServerAction
645 {
646 private String collection_name;
647 private String script_name;
648 private String script_arguments;
649 private GShell shell;
650
651 public RemoteGreenstoneServerRunScriptAction(String collection_name, String script_name, String script_arguments, GShell shell)
652 {
653 this.collection_name = collection_name;
654 this.script_name = script_name;
655 this.script_arguments = script_arguments;
656 this.shell = shell;
657 }
658
659 public void perform()
660 throws Exception
661 {
662 progress_bar.setAction("Running " + script_name + "...");
663
664 String run_script_command = "cmd=run-script";
665 run_script_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
666 run_script_command += "&script=" + script_name;
667 run_script_command += "&language=" + Configuration.getLanguage();
668 run_script_command += script_arguments;
669 action_output = sendCommandToServer(run_script_command, shell);
670 }
671 }
672
673
674 /**
675 * --------------------------------------------------------------------------------------------
676 * UPLOAD COLLECTION FILE
677 * --------------------------------------------------------------------------------------------
678 */
679 static private class RemoteGreenstoneServerUploadCollectionFilesAction
680 extends RemoteGreenstoneServerAction
681 {
682 private String collection_name;
683 private File[] collection_files;
684
685
686 public RemoteGreenstoneServerUploadCollectionFilesAction(String collection_name, File[] collection_files)
687 {
688 this.collection_name = collection_name;
689 this.collection_files = collection_files;
690 }
691
692
693 public void perform()
694 throws Exception
695 {
696 progress_bar.setAction("Uploading collection files...");
697
698 // Determine the file paths relative to the collection directory
699 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
700 String[] collection_file_relative_paths = new String[collection_files.length];
701 for (int i = 0; i < collection_files.length; i++) {
702 collection_file_relative_paths[i] = getPathRelativeToDirectory(collection_files[i], collection_directory_path);
703 }
704
705 // Zip up the files to send to the server
706 String zip_file_name = collection_name + "-" + System.currentTimeMillis() + ".zip";
707 String zip_file_path = collection_directory_path + zip_file_name;
708 ZipTools.zipFiles(zip_file_path, collection_directory_path, collection_file_relative_paths);
709
710 // Upload the zip file
711 String upload_collection_file_command = "cmd=upload-collection-file";
712 upload_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
713 upload_collection_file_command += "&file=" + URLEncoder.encode(zip_file_name, "UTF-8");
714 upload_collection_file_command += "&directory=";
715 upload_collection_file_command += "&zip=true";
716 action_output = uploadFile(upload_collection_file_command, zip_file_path);
717 }
718 }
719
720
721 /**
722 * --------------------------------------------------------------------------------------------
723 * UPLOAD FILES INTO COLLECTION
724 * --------------------------------------------------------------------------------------------
725 */
726 static private class RemoteGreenstoneServerUploadFilesIntoCollectionAction
727 extends RemoteGreenstoneServerAction
728 {
729 private String collection_name;
730 private File[] source_files;
731 private File target_collection_directory;
732
733
734 public RemoteGreenstoneServerUploadFilesIntoCollectionAction(String collection_name, File[] source_files, File target_collection_directory)
735 {
736 this.collection_name = collection_name;
737 this.source_files = source_files;
738 this.target_collection_directory = target_collection_directory;
739 }
740
741
742 public void perform()
743 throws Exception
744 {
745 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
746 String target_collection_directory_relative_path = getPathRelativeToDirectory(target_collection_directory, collection_directory_path);
747 target_collection_directory_relative_path = target_collection_directory_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
748 progress_bar.setAction("Uploading files into collection...");
749
750 String zip_file_name = collection_name + "-" + System.currentTimeMillis() + ".zip";
751 String zip_file_path = Gatherer.getCollectDirectoryPath() + zip_file_name;
752 DebugStream.println("Zip file path: " + zip_file_path);
753
754 String base_directory_path = source_files[0].getParentFile().getAbsolutePath();
755 DebugStream.println("Base directory path: " + base_directory_path);
756 String[] source_file_relative_paths = new String[source_files.length];
757 for (int i = 0; i < source_files.length; i++) {
758 DebugStream.println("Source file path: " + source_files[i]);
759 source_file_relative_paths[i] = getPathRelativeToDirectory(source_files[i], base_directory_path);
760 }
761
762 ZipTools.zipFiles(zip_file_path, base_directory_path, source_file_relative_paths);
763
764 String upload_collection_file_command = "cmd=upload-collection-file";
765 upload_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
766 upload_collection_file_command += "&file=" + URLEncoder.encode(zip_file_name, "UTF-8");
767 upload_collection_file_command += "&directory=" + URLEncoder.encode(target_collection_directory_relative_path, "UTF-8");
768 upload_collection_file_command += "&zip=true";
769 action_output = uploadFile(upload_collection_file_command, zip_file_path);
770 }
771 }
772
773
774 // ----------------------------------------------------------------------------------------------------
775 // AUTHENTICATION LAYER
776 // ----------------------------------------------------------------------------------------------------
777
778
779 static private PasswordAuthentication remote_greenstone_server_authentication = null;
780 // static private PasswordAuthentication remote_greenstone_server_authentication = new PasswordAuthentication(System.getProperty("user.name"), new char[] { });
781
782
783 static private class RemoteGreenstoneServerAuthenticateTask
784 extends Thread
785 {
786 public void run()
787 {
788 remote_greenstone_server_authentication = new RemoteGreenstoneServerAuthenticator().getAuthentication();
789 }
790
791
792 static private class RemoteGreenstoneServerAuthenticator
793 extends GAuthenticator
794 {
795 public PasswordAuthentication getAuthentication()
796 {
797 return getPasswordAuthentication();
798 }
799
800 protected String getMessageString()
801 {
802 return Dictionary.get("RemoteGreenstoneServer.Authentication_Message");
803 }
804 }
805 }
806
807
808 static private void authenticateUser()
809 throws RemoteGreenstoneServerActionCancelledException
810 {
811 // If we don't have any authentication information then ask for it now
812 if (remote_greenstone_server_authentication == null) {
813 try {
814 // We have to do this on the GUI thread
815 SwingUtilities.invokeAndWait(new RemoteGreenstoneServerAuthenticateTask());
816 }
817 catch (Exception exception) {
818 DebugStream.printStackTrace(exception);
819 }
820
821 // If it is still null then the user has cancelled the authentication, so the action is cancelled
822 if (remote_greenstone_server_authentication == null) {
823 throw new RemoteGreenstoneServerActionCancelledException();
824 }
825 }
826 }
827
828
829 static public String getUsername()
830 {
831 if (remote_greenstone_server_authentication != null) {
832 return remote_greenstone_server_authentication.getUserName();
833 }
834
835 return null;
836 }
837
838
839 // ----------------------------------------------------------------------------------------------------
840 // REQUEST LAYER
841 // ----------------------------------------------------------------------------------------------------
842
843
844 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
845 static private String downloadFile(String gliserver_args, String file_path)
846 throws Exception
847 {
848 while (true) {
849 // Check that Configuration.gliserver_url is set
850 if (Configuration.gliserver_url == null) {
851 throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
852 }
853
854 // Ask for authentication information (if necessary), then perform the action
855 authenticateUser();
856 String gliserver_url_string = Configuration.gliserver_url.toString();
857 String command_output = downloadFileInternal(gliserver_url_string, gliserver_args, file_path);
858
859 // Check the first line to see if authentication has failed; if so, go around the loop again
860 if (command_output.startsWith("ERROR: Authentication failed:")) {
861 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
862 remote_greenstone_server_authentication = null;
863 continue;
864 }
865 // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
866 else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
867 if (JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Steal_Lock_Message", command_output.substring("ERROR: Collection is locked by: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
868 // The user has decided to cancel the action
869 throw new RemoteGreenstoneServerActionCancelledException();
870 }
871
872 // The user has decided to steal the lock... rerun the command with "&steal_lock="
873 gliserver_args += "&steal_lock=";
874 continue;
875 }
876 // Handle other types of errors by throwing an exception
877 else if (command_output.startsWith("ERROR: ")) {
878 throw new Exception(command_output.substring("ERROR: ".length()));
879 }
880
881 // There were no exceptions thrown so the action must have succeeded
882 return command_output;
883 }
884 }
885
886
887 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
888 static private String sendCommandToServer(String gliserver_args, GShell shell)
889 throws Exception
890 {
891 while (true) {
892 // Check that Configuration.gliserver_url is set
893 if (Configuration.gliserver_url == null) {
894 throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
895 }
896
897 // Ask for authentication information (if necessary), then perform the action
898 authenticateUser();
899 String gliserver_url_string = Configuration.gliserver_url.toString();
900 String command_output = sendCommandToServerInternal(gliserver_url_string, gliserver_args, shell);
901 // System.err.println("Command output: " + command_output);
902
903 // Check the first line to see if authentication has failed; if so, go around the loop again
904 if (command_output.startsWith("ERROR: Authentication failed:")) {
905 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
906 remote_greenstone_server_authentication = null;
907 continue;
908 }
909 // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
910 else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
911 if (JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Steal_Lock_Message", command_output.substring("ERROR: Collection is locked by: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
912 // The user has decided to cancel the action
913 throw new RemoteGreenstoneServerActionCancelledException();
914 }
915
916 // The user has decided to steal the lock... rerun the command with "&steal_lock="
917 gliserver_args += "&steal_lock=";
918 continue;
919 }
920 // Handle other types of errors by throwing an exception
921 else if (command_output.startsWith("ERROR: ")) {
922 throw new Exception(command_output.substring("ERROR: ".length()));
923 }
924
925 // There were no exceptions thrown so the action must have succeeded
926 return command_output;
927 }
928 }
929
930
931 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
932 static private String uploadFile(String gliserver_args, String file_path)
933 throws Exception
934 {
935 while (true) {
936 // Check that Configuration.gliserver_url is set
937 if (Configuration.gliserver_url == null) {
938 throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
939 }
940
941 // Ask for authentication information (if necessary), then perform the action
942 authenticateUser();
943 String gliserver_url_string = Configuration.gliserver_url.toString();
944 String command_output = uploadFileInternal(gliserver_url_string, gliserver_args, file_path);
945 // System.err.println("Command output: " + command_output);
946
947 // Check the first line to see if authentication has failed; if so, go around the loop again
948 if (command_output.startsWith("ERROR: Authentication failed:")) {
949 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
950 remote_greenstone_server_authentication = null;
951 continue;
952 }
953 // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
954 else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
955 if (JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Steal_Lock_Message", command_output.substring("ERROR: Collection is locked by: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
956 // The user has decided to cancel the action
957 throw new RemoteGreenstoneServerActionCancelledException();
958 }
959
960 // The user has decided to steal the lock... rerun the command with "&steal_lock="
961 gliserver_args += "&steal_lock=";
962 continue;
963 }
964 // Handle other types of errors by throwing an exception
965 else if (command_output.startsWith("ERROR: ")) {
966 throw new Exception(command_output.substring("ERROR: ".length()));
967 }
968
969 // There were no exceptions thrown so the action must have succeeded
970 return command_output;
971 }
972 }
973
974
975 // ----------------------------------------------------------------------------------------------------
976 // NETWORK LAYER
977 // ----------------------------------------------------------------------------------------------------
978
979
980 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
981 static private String downloadFileInternal(String download_cgi, String cgi_args, String file_path)
982 throws Exception
983 {
984 DebugStream.println("gliserver URL: " + download_cgi);
985 System.err.println("gliserver args: " + cgi_args);
986
987 // Add username and password
988 cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
989 cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
990
991 URL download_url = new URL(download_cgi);
992 URLConnection dl_connection = download_url.openConnection();
993 dl_connection.setDoOutput(true);
994 OutputStream dl_os = dl_connection.getOutputStream();
995
996 PrintWriter dl_out = new PrintWriter(dl_os);
997 dl_out.println(cgi_args);
998 dl_out.close();
999
1000 // Download result from running cgi script
1001 InputStream dl_is = dl_connection.getInputStream();
1002 BufferedInputStream dl_bis = new BufferedInputStream(dl_is);
1003 DataInputStream dl_dbis = new DataInputStream(dl_bis);
1004
1005 String first_line = "";
1006 byte[] buf = new byte[1024];
1007 int len = dl_dbis.read(buf);
1008 if (len >= 0) {
1009 String first_chunk = new String(buf, 0, len);
1010 first_line = first_chunk.substring(0, ((first_chunk.indexOf("\n") != -1) ? first_chunk.indexOf("\n") : len));
1011
1012 // Save the data to file
1013 FileOutputStream zip_fos = new FileOutputStream(file_path);
1014 BufferedOutputStream zip_bfos = new BufferedOutputStream(zip_fos);
1015
1016 while (len >= 0) {
1017 zip_bfos.write(buf, 0, len);
1018 len = dl_dbis.read(buf);
1019 }
1020
1021 zip_bfos.close();
1022 zip_fos.close();
1023 }
1024
1025 dl_dbis.close();
1026 dl_bis.close();
1027 dl_is.close();
1028 return first_line;
1029 }
1030
1031
1032 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
1033 static private String sendCommandToServerInternal(String gliserver_url_string, String cgi_args, GShell shell)
1034 throws Exception
1035 {
1036 DebugStream.println("gliserver URL: " + gliserver_url_string);
1037 System.err.println("gliserver args: " + cgi_args);
1038
1039 // Add username and password
1040 cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
1041 cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
1042
1043 URL gliserver_url = new URL(gliserver_url_string + "?" + cgi_args);
1044 URLConnection gliserver_connection = gliserver_url.openConnection();
1045
1046 // Read the output of the command from the server, and return it
1047 StringBuffer command_output_buffer = new StringBuffer(2048);
1048 InputStream gliserver_is = gliserver_connection.getInputStream();
1049 BufferedReader gliserver_in = new BufferedReader(new InputStreamReader(gliserver_is, "UTF-8"));
1050 String gliserver_output_line = gliserver_in.readLine();
1051 while (gliserver_output_line != null) {
1052 if (shell != null) {
1053 shell.fireMessage(gliserver_output_line);
1054 if (shell.hasSignalledStop()) {
1055 throw new RemoteGreenstoneServerActionCancelledException();
1056 }
1057 }
1058 command_output_buffer.append(gliserver_output_line + "\n");
1059 gliserver_output_line = gliserver_in.readLine();
1060 }
1061 gliserver_in.close();
1062
1063 return command_output_buffer.toString();
1064 }
1065
1066
1067 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
1068 static private String uploadFileInternal(String upload_cgi, String cgi_args, String file_path)
1069 throws Exception
1070 {
1071 DebugStream.println("gliserver URL: " + upload_cgi);
1072 System.err.println("gliserver args: " + cgi_args);
1073
1074 // Add username and password
1075 cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
1076 cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
1077
1078 // Open a HTTP connection to the URL
1079 URL url = new URL(upload_cgi);
1080 HttpURLConnection gliserver_connection = (HttpURLConnection) url.openConnection();
1081
1082 gliserver_connection.setDoInput(true); // Allow Inputs
1083 gliserver_connection.setDoOutput(true); // Allow Outputs
1084 gliserver_connection.setUseCaches(false); // Don't use a cached copy.
1085
1086 gliserver_connection.setRequestProperty("Connection", "Keep-Alive");
1087
1088 DataOutputStream dos = new DataOutputStream(gliserver_connection.getOutputStream());
1089 dos.writeBytes(cgi_args + "\n");
1090
1091 // Send zip file to server
1092 File file = new File(file_path);
1093 FileInputStream fileInputStream = new FileInputStream(file);
1094
1095 // create a buffer of maximum size
1096 final int maxBufferSize = 1024;
1097 int bytesAvailable = fileInputStream.available();
1098 int bufferSize = Math.min(bytesAvailable, maxBufferSize);
1099 byte[] buffer = new byte[bufferSize];
1100
1101 // read file and write it into form...
1102 // !! This uses a lot of memory when the file being uploaded is big -- Java seems to need to keep
1103 // the entire file in the DataOutputStream? (Use Runtime.getRuntime().totalMemory() to see)
1104 int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
1105 while (bytesRead > 0) {
1106 dos.write(buffer, 0, bufferSize);
1107 bytesAvailable = fileInputStream.available();
1108 bufferSize = Math.min(bytesAvailable, maxBufferSize);
1109 bytesRead = fileInputStream.read(buffer, 0, bufferSize);
1110 }
1111
1112 // close streams
1113 fileInputStream.close();
1114 dos.flush();
1115 dos.close();
1116
1117 // Read the output of the command from the server, and return it
1118 String command_output = "";
1119 InputStream gliserver_is = gliserver_connection.getInputStream();
1120 BufferedReader gliserver_in = new BufferedReader(new InputStreamReader(gliserver_is, "UTF-8"));
1121 String gliserver_output_line = gliserver_in.readLine();
1122 while (gliserver_output_line != null) {
1123 command_output += gliserver_output_line + "\n";
1124 gliserver_output_line = gliserver_in.readLine();
1125 }
1126 gliserver_in.close();
1127
1128 return command_output;
1129 }
1130
1131
1132 // ----------------------------------------------------------------------------------------------------
1133 // UTILITIES
1134 // ----------------------------------------------------------------------------------------------------
1135
1136
1137 static public String getPathRelativeToDirectory(File file, String directory_path)
1138 {
1139 String file_path = file.getAbsolutePath();
1140 if (!file_path.startsWith(directory_path)) {
1141 System.err.println("ERROR: File path " + file_path + " is not a child of " + directory_path);
1142 return file_path;
1143 }
1144
1145 String relative_file_path = file_path.substring(directory_path.length());
1146 if (relative_file_path.startsWith(File.separator)) {
1147 relative_file_path = relative_file_path.substring(File.separator.length());
1148 }
1149 return relative_file_path;
1150 }
1151}
Note: See TracBrowser for help on using the repository browser.