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

Last change on this file since 16371 was 16371, checked in by ak19, 16 years ago

RemoteGreenstoneServer Authentication method no longer prefills fedora authentication information into Greenstone remot collection authentication fields. The two are different.

  • Property svn:keywords set to Author Date Id Revision
File size: 57.0 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 java.io.ByteArrayOutputStream;
36import org.greenstone.gatherer.Configuration;
37import org.greenstone.gatherer.DebugStream;
38import org.greenstone.gatherer.Dictionary;
39import org.greenstone.gatherer.FedoraInfo;
40import org.greenstone.gatherer.GAuthenticator;
41import org.greenstone.gatherer.Gatherer;
42import org.greenstone.gatherer.collection.CollectionManager;
43import org.greenstone.gatherer.shell.GShell;
44import org.greenstone.gatherer.util.UnzipTools;
45import org.greenstone.gatherer.util.Utility;
46import org.apache.commons.httpclient.HttpClient;
47import org.apache.commons.httpclient.methods.PostMethod;
48import org.apache.commons.httpclient.methods.GetMethod;
49import org.apache.commons.httpclient.HttpException;
50import org.apache.commons.httpclient.methods.multipart.FilePart;
51import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
52import org.apache.commons.httpclient.methods.multipart.Part;
53import org.apache.commons.httpclient.methods.multipart.*;
54import org.apache.commons.httpclient.params.*;
55import org.apache.commons.httpclient.HttpStatus;
56
57
58public class RemoteGreenstoneServer
59{
60 // ----------------------------------------------------------------------------------------------------
61 // PUBLIC LAYER
62 // ----------------------------------------------------------------------------------------------------
63
64
65 static public String deleteCollection(String collection_name)
66 {
67 return performAction(new RemoteGreenstoneServerDeleteCollectionAction(collection_name));
68 }
69
70
71 static public String deleteCollectionFile(String collection_name, File collection_file)
72 {
73 return performAction(new RemoteGreenstoneServerDeleteCollectionFileAction(collection_name, collection_file));
74 }
75
76
77 static public String downloadCollection(String collection_name)
78 {
79 return performAction(new RemoteGreenstoneServerDownloadCollectionAction(collection_name));
80 }
81
82
83 static public String downloadCollectionArchives(String collection_name)
84 {
85 return performAction(new RemoteGreenstoneServerDownloadCollectionArchivesAction(collection_name));
86 }
87
88
89 static public String downloadCollectionConfigurations()
90 {
91 return performAction(new RemoteGreenstoneServerDownloadCollectionConfigurationsAction());
92 }
93
94
95 static public String downloadCollectionFile(String collection_name, File collection_file)
96 {
97 return performAction(new RemoteGreenstoneServerDownloadCollectionFileAction(collection_name, collection_file));
98 }
99
100 // get web.xml from the server -- for a remote gli of GS3
101 static public String downloadWebXMLFile()
102 {
103 return performAction(new RemoteGreenstoneServerDownloadWebXMLFileAction());
104 }
105
106 static public String getScriptOptions(String script_name, String script_arguments)
107 {
108 return performAction(new RemoteGreenstoneServerGetScriptOptionsAction(script_name, script_arguments));
109 }
110
111 //get all available site names from the server -- for a remote gli of GS3
112 static public String getSiteNames()
113 {
114 return performAction(new RemoteGreenstoneServerGetSiteNamesAction());
115 }
116
117 static public String moveCollectionFile(String collection_name, File source_collection_file, File target_collection_file)
118 {
119 return performAction(new RemoteGreenstoneServerMoveCollectionFileAction(collection_name, source_collection_file, target_collection_file));
120 }
121
122
123 static public String newCollectionDirectory(String collection_name, File new_collection_directory)
124 {
125 return performAction(new RemoteGreenstoneServerNewCollectionDirectoryAction(collection_name, new_collection_directory));
126 }
127
128
129 static public String runScript(String collection_name, String script_name, String script_arguments, GShell shell)
130 {
131 return performAction(new RemoteGreenstoneServerRunScriptAction(collection_name, script_name, script_arguments, shell));
132 }
133
134
135 static public String uploadCollectionFile(String collection_name, File collection_file)
136 {
137 return performAction(new RemoteGreenstoneServerUploadCollectionFilesAction(collection_name, new File[] { collection_file }));
138 }
139
140
141 static public String uploadCollectionFiles(String collection_name, File[] collection_files)
142 {
143 return performAction(new RemoteGreenstoneServerUploadCollectionFilesAction(collection_name, collection_files));
144 }
145
146
147 static public String uploadFilesIntoCollection(String collection_name, File[] source_files, File target_collection_directory)
148 {
149 return performAction(new RemoteGreenstoneServerUploadFilesIntoCollectionAction(collection_name, source_files, target_collection_directory));
150 }
151
152 static public boolean exists(String collection_name, File collection_file)
153 {
154 String result = performAction(new RemoteGreenstoneServerExistsAction(collection_name, collection_file));
155 if(result.indexOf("exists") != -1) {
156 return true;
157 }
158 else if(result.indexOf("does not exist") != -1) {
159 return false;
160 }
161 return false;
162 }
163
164 static public int getGreenstoneVersion()
165 {
166 // returns message "Greenstone version is: <version number of the Greenstone remote server>"
167 String result = performAction(new RemoteGreenstoneServerVersionAction());
168 int index = result.indexOf(":");
169 if(index != -1) {
170 result = result.substring(index+1).trim(); // skip the space after colon, must remove surrounding spaces
171 }
172 int greenstoneVersion = Integer.parseInt(result);
173 return greenstoneVersion;
174 }
175
176 /** For constructing the preview command (the library URL) with */
177 static public String getLibraryURL(String serverHomeURL)
178 {
179 // returns message "Greenstone library URL suffix is: <e.g. /greenstone3/library or /gsdl/cgi-bin/library>"
180 String libSuffix = performAction(new RemoteGreenstoneServerLibraryURLSuffixAction());
181 int index = libSuffix.indexOf(":");
182 if(index != -1) {
183 libSuffix = libSuffix.substring(index+1).trim(); // skip the space after colon and remove surrounding spaces
184 }
185
186 // serverHomeURL is of the form, http://domain/other/stuff. We want the prefix upto & including domain
187 // and prepend that to the libraryURLSuffix
188 index = -1;
189 for(int i = 0; i < 3; i++) {
190 index = serverHomeURL.indexOf("/", index+1);
191 if(index == -1) { // shouldn't happen, but if it does, we'll be in an infinite loop
192 break;
193 }
194 }
195 serverHomeURL = serverHomeURL.substring(0, index);
196 return serverHomeURL + libSuffix;
197 }
198
199 // ----------------------------------------------------------------------------------------------------
200
201
202 static public void exit()
203 {
204 System.err.println("Exiting, number of jobs on queue: " + remote_greenstone_server_action_queue.size());
205
206 // If there are still jobs on the queue we must wait for the jobs to finish
207 while (remote_greenstone_server_action_queue.size() > 0) {
208 synchronized (remote_greenstone_server_action_queue) {
209 try {
210 DebugStream.println("Waiting for queue to become empty...");
211 remote_greenstone_server_action_queue.wait(500);
212 }
213 catch (InterruptedException exception) {}
214 }
215 }
216 }
217
218
219 // ----------------------------------------------------------------------------------------------------
220 // QUEUE LAYER
221 // ----------------------------------------------------------------------------------------------------
222
223
224 /** Returns null if we cannot wait for the action to finish, "" if the action failed, or the action output. */
225 static private String performAction(RemoteGreenstoneServerAction remote_greenstone_server_action)
226 {
227 // Add the action to the queue
228 remote_greenstone_server_action_queue.addAction(remote_greenstone_server_action);
229
230 // If we're running in the GUI thread we must return immediately
231 // We cannot wait for the action to complete because this will block any GUI updates
232 if (SwingUtilities.isEventDispatchThread()) {
233 System.err.println("WARNING: In event dispatch thread, returning immediately...");
234 return null;
235 }
236
237 // Otherwise wait until the action is processed
238 while (!remote_greenstone_server_action.processed) {
239 synchronized (remote_greenstone_server_action) {
240 try {
241 DebugStream.println("Waiting for action to complete...");
242 remote_greenstone_server_action.wait(500);
243 }
244 catch (InterruptedException exception) {}
245 }
246 }
247
248 // Return "" if the action failed
249 if (!remote_greenstone_server_action.processed_successfully) {
250 return "";
251 }
252 // Otherwise return the action output
253 return remote_greenstone_server_action.action_output;
254 }
255
256
257 static private RemoteGreenstoneServerActionQueue remote_greenstone_server_action_queue = new RemoteGreenstoneServerActionQueue();
258
259
260 static private class RemoteGreenstoneServerActionQueue
261 extends Thread
262 {
263 /** The queue of waiting jobs. */
264 private ArrayList queue = null;
265
266
267 public RemoteGreenstoneServerActionQueue()
268 {
269 if (Gatherer.isGsdlRemote) {
270 queue = new ArrayList();
271 start();
272 }
273 }
274
275
276 synchronized public void addAction(RemoteGreenstoneServerAction remote_greenstone_server_action)
277 {
278 queue.add(remote_greenstone_server_action);
279 notifyAll();
280 }
281
282
283 public int size()
284 {
285 return queue.size();
286 }
287
288
289 public void run()
290 {
291 boolean exit = false;
292 while (true) {
293 // If there are jobs on the queue, get the next in line and process it
294 if (queue.size() > 0) {
295 RemoteGreenstoneServerAction remote_greenstone_server_action = (RemoteGreenstoneServerAction) queue.get(0);
296
297 try {
298 remote_greenstone_server_action.perform();
299
300 // No exceptions were thrown, so the action was successful
301 remote_greenstone_server_action.processed_successfully = true;
302 }
303 catch (RemoteGreenstoneServerActionCancelledException exception) {
304 remote_greenstone_server_action.processed_successfully = false;
305 exit = true;
306 }
307 catch(java.net.ConnectException exception) {
308 if(exception.getMessage().equals("Connection refused")) {
309 exit = true;
310 } else {
311 DebugStream.printStackTrace(exception);
312 }
313 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", exception.getMessage()), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
314 remote_greenstone_server_action.processed_successfully = false;
315 }
316 catch (FileNotFoundException exception) {
317 // FileNotFoundException happens when there's no GS server at the user-provided
318 // url (the address of gliserver.pl is wrong).
319 exit = true;
320 DebugStream.printStackTrace(exception);
321 JOptionPane.showMessageDialog(Gatherer.g_man,
322 Dictionary.get("RemoteGreenstoneServer.Error",
323 "No gliserver.pl found. " + exception.getMessage()),
324 Dictionary.get("RemoteGreenstoneServer.Error_Title"),
325 JOptionPane.ERROR_MESSAGE);
326 remote_greenstone_server_action.processed_successfully = false;
327 }
328 catch (Exception exception) {
329 DebugStream.printStackTrace(exception);
330 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", exception.getMessage()), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
331 remote_greenstone_server_action.processed_successfully = false;
332 }
333
334 // We're done with this action, for better or worse
335 remote_greenstone_server_action.processed = true;
336 queue.remove(0);
337 }
338
339 // Otherwise the queue is empty
340 else {
341 progress_bar.setAction(null);
342
343 // Wait until we are notify()ed by addAction that there is a new job on the queue
344 synchronized (this) {
345 try {
346 wait();
347 }
348 catch (InterruptedException exception) { }
349 }
350 }
351
352 // stop the gazillion annoying error messages when the connection was simply
353 // refused or when the user pressed Cancel in the opening dialog, by exitting
354 // cleanly in one go.
355 if(exit == true) {
356 Gatherer.exit();
357 }
358 }
359 }
360 }
361
362
363 // ----------------------------------------------------------------------------------------------------
364 // PROGRESS BAR
365 // ----------------------------------------------------------------------------------------------------
366
367
368 static private RemoteGreenstoneServerProgressBar progress_bar = new RemoteGreenstoneServerProgressBar();
369
370
371 static private class RemoteGreenstoneServerProgressBar
372 extends JProgressBar
373 {
374 public RemoteGreenstoneServerProgressBar()
375 {
376 setBackground(Configuration.getColor("coloring.collection_tree_background", false));
377 setForeground(Configuration.getColor("coloring.collection_tree_foreground", false));
378 setString(Dictionary.get("FileActions.No_Activity"));
379 setStringPainted(true);
380 }
381
382
383 public void setAction(String action)
384 {
385 if (action != null) {
386 DebugStream.println(action);
387 }
388
389 // We cannot call this from the GUI thread otherwise the progress bar won't start
390 if (SwingUtilities.isEventDispatchThread()) {
391 System.err.println("ERROR: RemoteGreenstoneServerProgressBar.setAction() called from event dispatch thread!");
392 return;
393 }
394
395 // Set the string on the progress bar, and start or stop it
396 if (action == null) {
397 setString(Dictionary.get("FileActions.No_Activity"));
398 setIndeterminate(false);
399 }
400 else {
401 setString(action);
402 setIndeterminate(true);
403 }
404 }
405 }
406
407
408 static public RemoteGreenstoneServerProgressBar getProgressBar()
409 {
410 return progress_bar;
411 }
412
413
414 // ----------------------------------------------------------------------------------------------------
415 // ACTIONS
416 // ----------------------------------------------------------------------------------------------------
417
418
419 static private abstract class RemoteGreenstoneServerAction
420 {
421 public String action_output = null;
422 public boolean processed = false;
423 public boolean processed_successfully;
424
425 abstract public void perform()
426 throws Exception;
427 }
428
429
430 static private class RemoteGreenstoneServerActionCancelledException
431 extends Exception
432 {
433 }
434
435
436 /**
437 * --------------------------------------------------------------------------------------------
438 * DELETE COLLECTION
439 * --------------------------------------------------------------------------------------------
440 */
441 static private class RemoteGreenstoneServerDeleteCollectionAction
442 extends RemoteGreenstoneServerAction
443 {
444 private String collection_name;
445
446 public RemoteGreenstoneServerDeleteCollectionAction(String collection_name)
447 {
448 this.collection_name = collection_name;
449 }
450
451 public void perform()
452 throws Exception
453 {
454 progress_bar.setAction("Deleting collection " + collection_name + "...");
455
456 String delete_collection_command = "cmd=delete-collection";
457 delete_collection_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
458 action_output = sendCommandToServer(delete_collection_command, null);
459 }
460 }
461
462
463 /**
464 * --------------------------------------------------------------------------------------------
465 * DELETE COLLECTION FILE
466 * --------------------------------------------------------------------------------------------
467 */
468 static private class RemoteGreenstoneServerDeleteCollectionFileAction
469 extends RemoteGreenstoneServerAction
470 {
471 private String collection_name;
472 private File collection_file;
473
474 public RemoteGreenstoneServerDeleteCollectionFileAction(String collection_name, File collection_file)
475 {
476 this.collection_name = collection_name;
477 this.collection_file = collection_file;
478 }
479
480 public void perform()
481 throws Exception
482 {
483 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
484 String collection_file_relative_path = getPathRelativeToDirectory(collection_file, collection_directory_path);
485 collection_file_relative_path = collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
486 progress_bar.setAction("Deleting collection file " + collection_file_relative_path + "...");
487
488 String delete_collection_file_command = "cmd=delete-collection-file";
489 delete_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
490 delete_collection_file_command += "&file=" + URLEncoder.encode(collection_file_relative_path, "UTF-8");
491 action_output = sendCommandToServer(delete_collection_file_command, null);
492 }
493 }
494
495
496 /**
497 * --------------------------------------------------------------------------------------------
498 * DOWNLOAD COLLECTION
499 * --------------------------------------------------------------------------------------------
500 */
501 static private class RemoteGreenstoneServerDownloadCollectionAction
502 extends RemoteGreenstoneServerAction
503 {
504 private String collection_name;
505
506 public RemoteGreenstoneServerDownloadCollectionAction(String collection_name)
507 {
508 this.collection_name = collection_name;
509 }
510
511 public void perform()
512 throws Exception
513 {
514 progress_bar.setAction("Downloading remote collection " + collection_name + "...");
515
516 String download_collection_command = "cmd=download-collection";
517 download_collection_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
518 String zip_file_path = Gatherer.getCollectDirectoryPath() + collection_name + ".zip";
519 action_output = downloadFile(download_collection_command, zip_file_path);
520
521 // Delete the existing (local) collection directory
522 Utility.delete(new File(CollectionManager.getCollectionDirectoryPath(collection_name)));
523
524 // Unzip the collection just downloaded
525 UnzipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
526 }
527 }
528
529
530 /**
531 * --------------------------------------------------------------------------------------------
532 * DOWNLOAD COLLECTION ARCHIVES
533 * --------------------------------------------------------------------------------------------
534 */
535 static private class RemoteGreenstoneServerDownloadCollectionArchivesAction
536 extends RemoteGreenstoneServerAction
537 {
538 private String collection_name;
539
540 public RemoteGreenstoneServerDownloadCollectionArchivesAction(String collection_name)
541 {
542 this.collection_name = collection_name;
543 }
544
545 public void perform()
546 throws Exception
547 {
548 progress_bar.setAction("Downloading collection archives for " + collection_name + "...");
549
550 String download_collection_archives_command = "cmd=download-collection-archives";
551 download_collection_archives_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
552 String zip_file_path = Gatherer.getCollectDirectoryPath() + collection_name + "-archives.zip";
553 action_output = downloadFile(download_collection_archives_command, zip_file_path);
554
555 // Delete the existing (local) collection archives
556 Utility.delete(new File(CollectionManager.getLoadedCollectionArchivesDirectoryPath()));
557
558 // Unzip the collection archives just downloaded
559 UnzipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
560 }
561 }
562
563
564 /**
565 * --------------------------------------------------------------------------------------------
566 * DOWNLOAD COLLECTION CONFIGURATIONS
567 * --------------------------------------------------------------------------------------------
568 */
569 static private class RemoteGreenstoneServerDownloadCollectionConfigurationsAction
570 extends RemoteGreenstoneServerAction
571 {
572 public RemoteGreenstoneServerDownloadCollectionConfigurationsAction()
573 {
574 }
575
576 public void perform()
577 throws Exception
578 {
579 progress_bar.setAction("Downloading collection configurations...");
580
581 // Delete the existing (local) collect directory
582 Utility.delete(new File(Gatherer.getCollectDirectoryPath()));
583 new File(Gatherer.getCollectDirectoryPath()).mkdirs();
584
585 String download_collection_configurations_command = "cmd=download-collection-configurations";
586 String zip_file_path = Gatherer.getCollectDirectoryPath() + "collections.zip";
587 action_output = downloadFile(download_collection_configurations_command, zip_file_path);
588
589 // Unzip the collection configurations just downloaded
590 UnzipTools.unzipFile(zip_file_path, Gatherer.getCollectDirectoryPath());
591 }
592 }
593
594 /**
595 * --------------------------------------------------------------------------------------------
596 * DISCOVERING WHAT VERSION THE REMOTE GREENSTONE SERVER IS (2 or 3)
597 * --------------------------------------------------------------------------------------------
598 */
599
600 static private class RemoteGreenstoneServerVersionAction
601 extends RemoteGreenstoneServerAction
602 {
603 public void perform()
604 throws Exception
605 {
606 action_output = sendCommandToServer("cmd=greenstone-server-version", null);
607 }
608 }
609
610 static private class RemoteGreenstoneServerLibraryURLSuffixAction
611 extends RemoteGreenstoneServerAction
612 {
613 public void perform()
614 throws Exception
615 {
616 action_output = sendCommandToServer("cmd=get-library-url-suffix", null);
617 }
618 }
619
620 /**
621 * --------------------------------------------------------------------------------------------
622 * CHECKING IF A FILE/FOLDER EXISTS ON SERVER SIDE
623 * --------------------------------------------------------------------------------------------
624 */
625 static private class RemoteGreenstoneServerExistsAction
626 extends RemoteGreenstoneServerAction
627 {
628 private String collection_name;
629 private File collection_file;
630
631 public RemoteGreenstoneServerExistsAction(String collection_name, File collection_file)
632 {
633 this.collection_name = collection_name;
634 this.collection_file = collection_file;
635 }
636
637 public void perform()
638 throws Exception
639 {
640 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
641 String collection_file_relative_path = getPathRelativeToDirectory(collection_file, collection_directory_path);
642 collection_file_relative_path = collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
643 File file = new File(collection_directory_path, collection_file_relative_path);
644
645 String file_exists_command = "cmd=file-exists";
646 file_exists_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
647 file_exists_command += "&file=" + URLEncoder.encode(collection_file_relative_path, "UTF-8");
648 // returns either "File <filename> exists" or "File <filename> does not exist"
649 // for the file/folder collection_file
650 action_output = sendCommandToServer(file_exists_command, null);
651 }
652 }
653
654
655 /**
656 * --------------------------------------------------------------------------------------------
657 * DOWNLOAD COLLECTION FILE
658 * --------------------------------------------------------------------------------------------
659 */
660 static private class RemoteGreenstoneServerDownloadCollectionFileAction
661 extends RemoteGreenstoneServerAction
662 {
663 private String collection_name;
664 private File collection_file;
665
666 public RemoteGreenstoneServerDownloadCollectionFileAction(String collection_name, File collection_file)
667 {
668 this.collection_name = collection_name;
669 this.collection_file = collection_file;
670 }
671
672 public void perform()
673 throws Exception
674 {
675 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
676 String collection_file_relative_path = getPathRelativeToDirectory(collection_file, collection_directory_path);
677 collection_file_relative_path = collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
678 progress_bar.setAction("Downloading collection file " + collection_file_relative_path + "...");
679
680 String download_collection_file_command = "cmd=download-collection-file";
681 download_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
682 download_collection_file_command += "&file=" + URLEncoder.encode(collection_file_relative_path, "UTF-8");
683 String zip_file_name = collection_name + "-" + collection_file.getName() + ".zip";
684 String zip_file_path = collection_directory_path + zip_file_name;
685 action_output = downloadFile(download_collection_file_command, zip_file_path);
686
687 // Unzip the collection file just downloaded
688 UnzipTools.unzipFile(zip_file_path, collection_directory_path);
689 }
690 }
691
692 /**
693 * --------------------------------------------------------------------------------------------
694 * DOWNLOAD web.xml FILE --for a remote GS3
695 * --------------------------------------------------------------------------------------------
696 */
697 static private class RemoteGreenstoneServerDownloadWebXMLFileAction
698 extends RemoteGreenstoneServerAction
699 {
700 public RemoteGreenstoneServerDownloadWebXMLFileAction()
701 {}
702
703 public void perform()
704 throws Exception
705 {
706 String web_xml_directory_path=(Configuration.gli_user_directory_path);
707 String download_web_xml_file_command = "cmd=download-web-xml-file";
708 download_web_xml_file_command += "&file=" + URLEncoder.encode("web.xml", "UTF-8");
709 String zip_file_name = "web-xml.zip";
710 String zip_file_path = web_xml_directory_path + zip_file_name;
711 action_output = downloadFile(download_web_xml_file_command, zip_file_path);
712
713 // Unzip the web.xml file just downloaded
714 UnzipTools.unzipFile(zip_file_path,web_xml_directory_path);
715 }
716 }
717
718 /**
719 * --------------------------------------------------------------------------------------------
720 * GET SCRIPT OPTIONS
721 * --------------------------------------------------------------------------------------------
722 */
723 static private class RemoteGreenstoneServerGetScriptOptionsAction
724 extends RemoteGreenstoneServerAction
725 {
726 private String script_name;
727 private String script_arguments;
728
729 public RemoteGreenstoneServerGetScriptOptionsAction(String script_name, String script_arguments)
730 {
731 this.script_name = script_name;
732 this.script_arguments = script_arguments;
733 }
734
735 public void perform()
736 throws Exception
737 {
738 progress_bar.setAction("Getting options for " + script_name + "...");
739
740 String get_script_options_command = "cmd=get-script-options";
741 get_script_options_command += "&script=" + script_name;
742 get_script_options_command += "&xml=";
743 get_script_options_command += "&language=" + Configuration.getLanguage();
744 get_script_options_command += script_arguments;
745 action_output = sendCommandToServer(get_script_options_command, null);
746 }
747 }
748
749 /**
750 * --------------------------------------------------------------------------------------------
751 * GET ALL NAMES OF SITES // for a remote GS3
752 * --------------------------------------------------------------------------------------------
753 */
754 static private class RemoteGreenstoneServerGetSiteNamesAction
755 extends RemoteGreenstoneServerAction
756 {
757 public RemoteGreenstoneServerGetSiteNamesAction()
758 {}
759
760 public void perform()
761 throws Exception
762 {
763 progress_bar.setAction("Getting names of sites ...");
764
765 String get_script_options_command = "cmd=get-site-names";
766 action_output = sendCommandToServer(get_script_options_command, null);
767 }
768 }
769
770 /**
771 * --------------------------------------------------------------------------------------------
772 * MOVE COLLECTION FILE
773 * --------------------------------------------------------------------------------------------
774 */
775 static private class RemoteGreenstoneServerMoveCollectionFileAction
776 extends RemoteGreenstoneServerAction
777 {
778 private String collection_name;
779 private File source_collection_file;
780 private File target_collection_file;
781
782 public RemoteGreenstoneServerMoveCollectionFileAction(String collection_name, File source_collection_file, File target_collection_file)
783 {
784 this.collection_name = collection_name;
785 this.source_collection_file = source_collection_file;
786 this.target_collection_file = target_collection_file;
787 }
788
789 public void perform()
790 throws Exception
791 {
792 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
793 String source_collection_file_relative_path = getPathRelativeToDirectory(source_collection_file, collection_directory_path);
794 source_collection_file_relative_path = source_collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
795 String target_collection_file_relative_path = getPathRelativeToDirectory(target_collection_file, collection_directory_path);
796 target_collection_file_relative_path = target_collection_file_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
797 progress_bar.setAction("Moving file " + source_collection_file_relative_path + " -> " + target_collection_file_relative_path + "...");
798
799 String move_collection_file_command = "cmd=move-collection-file";
800 move_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
801 move_collection_file_command += "&source=" + URLEncoder.encode(source_collection_file_relative_path, "UTF-8");
802 move_collection_file_command += "&target=" + URLEncoder.encode(target_collection_file_relative_path, "UTF-8");
803 action_output = sendCommandToServer(move_collection_file_command, null);
804 }
805 }
806
807
808 /**
809 * --------------------------------------------------------------------------------------------
810 * NEW COLLECTION DIRECTORY
811 * --------------------------------------------------------------------------------------------
812 */
813 static private class RemoteGreenstoneServerNewCollectionDirectoryAction
814 extends RemoteGreenstoneServerAction
815 {
816 private String collection_name;
817 private File new_collection_directory;
818
819 public RemoteGreenstoneServerNewCollectionDirectoryAction(String collection_name, File new_collection_directory)
820 {
821 this.collection_name = collection_name;
822 this.new_collection_directory = new_collection_directory;
823 }
824
825 public void perform()
826 throws Exception
827 {
828 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
829 String new_collection_directory_relative_path = getPathRelativeToDirectory(new_collection_directory, collection_directory_path);
830 new_collection_directory_relative_path = new_collection_directory_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
831 progress_bar.setAction("Creating new directory " + new_collection_directory_relative_path + "...");
832
833 String new_collection_directory_command = "cmd=new-collection-directory";
834 new_collection_directory_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
835 new_collection_directory_command += "&directory=" + URLEncoder.encode(new_collection_directory_relative_path, "UTF-8");
836 action_output = sendCommandToServer(new_collection_directory_command, null);
837 }
838 }
839
840
841 /**
842 * --------------------------------------------------------------------------------------------
843 * RUN SCRIPT
844 * --------------------------------------------------------------------------------------------
845 */
846 static private class RemoteGreenstoneServerRunScriptAction
847 extends RemoteGreenstoneServerAction
848 {
849 private String collection_name;
850 private String script_name;
851 private String script_arguments;
852 private GShell shell;
853
854 public RemoteGreenstoneServerRunScriptAction(String collection_name, String script_name, String script_arguments, GShell shell)
855 {
856 this.collection_name = collection_name;
857 this.script_name = script_name;
858 this.script_arguments = script_arguments;
859 this.shell = shell;
860 }
861
862 public void perform()
863 throws Exception
864 {
865 progress_bar.setAction("Running " + script_name + "...");
866
867 String run_script_command = "cmd=run-script";
868 run_script_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
869 run_script_command += "&script=" + script_name;
870 run_script_command += "&language=" + Configuration.getLanguage();
871 run_script_command += script_arguments;
872 action_output = sendCommandToServer(run_script_command, shell);
873 }
874 }
875
876
877 /**
878 * --------------------------------------------------------------------------------------------
879 * UPLOAD COLLECTION FILE
880 * --------------------------------------------------------------------------------------------
881 */
882 static private class RemoteGreenstoneServerUploadCollectionFilesAction
883 extends RemoteGreenstoneServerAction
884 {
885 private String collection_name;
886 private File[] collection_files;
887
888
889 public RemoteGreenstoneServerUploadCollectionFilesAction(String collection_name, File[] collection_files)
890 {
891 this.collection_name = collection_name;
892 this.collection_files = collection_files;
893 }
894
895
896 public void perform()
897 throws Exception
898 {
899 progress_bar.setAction("Uploading collection files...");
900
901 // Determine the file paths relative to the collection directory
902 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
903 String[] collection_file_relative_paths = new String[collection_files.length];
904 for (int i = 0; i < collection_files.length; i++) {
905 collection_file_relative_paths[i] = getPathRelativeToDirectory(collection_files[i], collection_directory_path);
906 }
907
908 // Zip up the files to send to the server
909 String zip_file_name = collection_name + "-" + System.currentTimeMillis() + ".zip";
910 String zip_file_path = collection_directory_path + zip_file_name;
911 ZipTools.zipFiles(zip_file_path, collection_directory_path, collection_file_relative_paths);
912
913 // Upload the zip file
914 String upload_collection_file_command = "cmd=upload-collection-file";
915 upload_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
916 upload_collection_file_command += "&file=" + URLEncoder.encode(zip_file_name, "UTF-8");
917 upload_collection_file_command += "&directory=";
918 upload_collection_file_command += "&zip=true";
919 action_output = uploadFile(upload_collection_file_command, zip_file_path);
920 }
921 }
922
923
924 /**
925 * --------------------------------------------------------------------------------------------
926 * UPLOAD FILES INTO COLLECTION
927 * --------------------------------------------------------------------------------------------
928 */
929 static private class RemoteGreenstoneServerUploadFilesIntoCollectionAction
930 extends RemoteGreenstoneServerAction
931 {
932 private String collection_name;
933 private File[] source_files;
934 private File target_collection_directory;
935
936
937 public RemoteGreenstoneServerUploadFilesIntoCollectionAction(String collection_name, File[] source_files, File target_collection_directory)
938 {
939 this.collection_name = collection_name;
940 this.source_files = source_files;
941 this.target_collection_directory = target_collection_directory;
942 }
943
944
945 public void perform()
946 throws Exception
947 {
948 String collection_directory_path = CollectionManager.getCollectionDirectoryPath(collection_name);
949 String target_collection_directory_relative_path = getPathRelativeToDirectory(target_collection_directory, collection_directory_path);
950 target_collection_directory_relative_path = target_collection_directory_relative_path.replaceAll((Utility.isWindows() ? "\\\\" : "\\/"), "|");
951 progress_bar.setAction("Uploading files into collection...");
952
953 String zip_file_name = collection_name + "-" + System.currentTimeMillis() + ".zip";
954 String zip_file_path = Gatherer.getCollectDirectoryPath() + zip_file_name;
955 DebugStream.println("Zip file path: " + zip_file_path);
956
957 String base_directory_path = source_files[0].getParentFile().getAbsolutePath();
958 DebugStream.println("Base directory path: " + base_directory_path);
959 String[] source_file_relative_paths = new String[source_files.length];
960 for (int i = 0; i < source_files.length; i++) {
961 DebugStream.println("Source file path: " + source_files[i]);
962 source_file_relative_paths[i] = getPathRelativeToDirectory(source_files[i], base_directory_path);
963 }
964
965 ZipTools.zipFiles(zip_file_path, base_directory_path, source_file_relative_paths);
966
967 String upload_collection_file_command = "cmd=upload-collection-file";
968 upload_collection_file_command += "&c=" + URLEncoder.encode(collection_name, "UTF-8");
969 upload_collection_file_command += "&file=" + URLEncoder.encode(zip_file_name, "UTF-8");
970 upload_collection_file_command += "&directory=" + URLEncoder.encode(target_collection_directory_relative_path, "UTF-8");
971 upload_collection_file_command += "&zip=true";
972 action_output = uploadFile(upload_collection_file_command, zip_file_path);
973 }
974 }
975
976
977 // ----------------------------------------------------------------------------------------------------
978 // AUTHENTICATION LAYER
979 // ----------------------------------------------------------------------------------------------------
980
981
982 static private PasswordAuthentication remote_greenstone_server_authentication = null;
983 // static private PasswordAuthentication remote_greenstone_server_authentication = new PasswordAuthentication(System.getProperty("user.name"), new char[] { });
984
985 static public void set_remote_greenstone_server_authentication_to_null(){
986 remote_greenstone_server_authentication = null;
987 }
988
989 static private class RemoteGreenstoneServerAuthenticateTask
990 extends Thread
991 {
992 public void run()
993 {
994 remote_greenstone_server_authentication = new RemoteGreenstoneServerAuthenticator().getAuthentication();
995 }
996
997
998 static private class RemoteGreenstoneServerAuthenticator
999 extends GAuthenticator
1000 {
1001 public PasswordAuthentication getAuthentication(String username, String password)
1002 {
1003 return getPasswordAuthentication(username,password);
1004 }
1005
1006 public PasswordAuthentication getAuthentication()
1007 {
1008 return getPasswordAuthentication();
1009 }
1010
1011 protected String getMessageString()
1012 {
1013 if (Gatherer.GS3){
1014 return (Dictionary.get("RemoteGreenstoneServer.Authentication_Message_gs3") + " " + Configuration.site_name);
1015 }
1016 return Dictionary.get("RemoteGreenstoneServer.Authentication_Message");
1017 }
1018 }
1019 }
1020
1021
1022 static private void authenticateUser()
1023 throws RemoteGreenstoneServerActionCancelledException
1024 {
1025 // If we don't have any authentication information then ask for it now
1026 if (remote_greenstone_server_authentication == null) {
1027 try {
1028 // We have to do this on the GUI thread
1029 SwingUtilities.invokeAndWait(new RemoteGreenstoneServerAuthenticateTask());
1030 }
1031 catch (Exception exception) {
1032 DebugStream.printStackTrace(exception);
1033 }
1034
1035 // If it is still null then the user has cancelled the authentication, so the action is cancelled
1036 if (remote_greenstone_server_authentication == null) {
1037 throw new RemoteGreenstoneServerActionCancelledException();
1038 }
1039 }
1040 }
1041
1042
1043 static public String getUsername()
1044 {
1045 if (remote_greenstone_server_authentication != null) {
1046 return remote_greenstone_server_authentication.getUserName();
1047 }
1048
1049 return null;
1050 }
1051
1052
1053 // ----------------------------------------------------------------------------------------------------
1054 // REQUEST LAYER
1055 // ----------------------------------------------------------------------------------------------------
1056
1057
1058 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
1059 static private String downloadFile(String gliserver_args, String file_path)
1060 throws Exception
1061 {
1062 while (true) {
1063 // Check that Configuration.gliserver_url is set
1064 if (Configuration.gliserver_url == null) {
1065 throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
1066 }
1067
1068 // Ask for authentication information (if necessary), then perform the action
1069 authenticateUser();
1070 String gliserver_url_string = Configuration.gliserver_url.toString();
1071 String command_output = downloadFileInternal(gliserver_url_string, gliserver_args, file_path);
1072
1073 // Check the first line to see if authentication has failed; if so, go around the loop again
1074 if (command_output.startsWith("ERROR: Authentication failed:")) {
1075 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
1076 remote_greenstone_server_authentication = null;
1077 continue;
1078 }
1079 // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
1080 else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
1081 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) {
1082 // The user has decided to cancel the action
1083 throw new RemoteGreenstoneServerActionCancelledException();
1084 }
1085
1086 // The user has decided to steal the lock... rerun the command with "&steal_lock="
1087 gliserver_args += "&steal_lock=";
1088 continue;
1089 }
1090 // Handle other types of errors by throwing an exception
1091 else if (command_output.startsWith("ERROR: ")) {
1092 throw new Exception(command_output.substring("ERROR: ".length()));
1093 }
1094
1095 // There were no exceptions thrown so the action must have succeeded
1096 return command_output;
1097 }
1098 }
1099
1100 /** Returns true or false depending on whether authentication is required for the cmd
1101 * string embedded in the given gliserver_args. No authentication is required for either
1102 * of the commands greenstone-server-version and get-library-url-suffix. */
1103 static private boolean isAuthenticationRequired(String gliserver_args) {
1104 return ((gliserver_args.indexOf("greenstone-server-version") == -1)
1105 && (gliserver_args.indexOf("get-library-url-suffix") == -1));
1106 }
1107
1108
1109 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
1110 static private String sendCommandToServer(String gliserver_args, GShell shell)
1111 throws Exception
1112 {
1113 while (true) {
1114
1115 // Check that Configuration.gliserver_url is set
1116 if (Configuration.gliserver_url == null) {
1117 throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
1118 }
1119
1120 // Ask for authentication information (if necessary), then perform the action
1121 if(isAuthenticationRequired(gliserver_args)) {
1122 authenticateUser();
1123 }
1124 String gliserver_url_string = Configuration.gliserver_url.toString();
1125 String command_output = sendCommandToServerInternal(gliserver_url_string, gliserver_args, shell);
1126
1127 // Check the first line to see if authentication has failed; if so, go around the loop again
1128 if (command_output.startsWith("ERROR: Authentication failed:")) {
1129 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
1130 remote_greenstone_server_authentication = null;
1131 continue;
1132 }
1133 // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
1134 else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
1135 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) {
1136 // The user has decided to cancel the action
1137 throw new RemoteGreenstoneServerActionCancelledException();
1138 }
1139
1140 // The user has decided to steal the lock... rerun the command with "&steal_lock="
1141 gliserver_args += "&steal_lock=";
1142 continue;
1143 }
1144 // Handle other types of errors by throwing an exception
1145 else if (command_output.startsWith("ERROR: ")) {
1146 throw new Exception(command_output.substring("ERROR: ".length()));
1147 } else if (command_output.indexOf("ERROR: ") != -1) { // check if ERROR occurs anywhere else in the output
1148 throw new Exception(command_output);
1149 }
1150
1151
1152 // There were no exceptions thrown so the action must have succeeded
1153 return command_output;
1154 }
1155 }
1156
1157
1158 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
1159 static private String uploadFile(String gliserver_args, String file_path)
1160 throws Exception
1161 {
1162 while (true) {
1163 // Check that Configuration.gliserver_url is set
1164 if (Configuration.gliserver_url == null) {
1165 throw new Exception("Empty gliserver URL: please set this in Preferences before continuing.");
1166 }
1167
1168 // Ask for authentication information (if necessary), then perform the action
1169 authenticateUser();
1170 String gliserver_url_string = Configuration.gliserver_url.toString();
1171 String command_output = uploadFileInternal(gliserver_url_string, gliserver_args, file_path);
1172 // System.err.println("Command output: " + command_output);
1173
1174 // Check the first line to see if authentication has failed; if so, go around the loop again
1175 if (command_output.startsWith("ERROR: Authentication failed:")) {
1176 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("RemoteGreenstoneServer.Error", command_output.substring("ERROR: ".length())), Dictionary.get("RemoteGreenstoneServer.Error_Title"), JOptionPane.ERROR_MESSAGE);
1177 remote_greenstone_server_authentication = null;
1178 continue;
1179 }
1180 // Check if the collection is locked by someone else; if so, see if the user wants to steal the lock
1181 else if (command_output.startsWith("ERROR: Collection is locked by: ")) {
1182 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) {
1183 // The user has decided to cancel the action
1184 throw new RemoteGreenstoneServerActionCancelledException();
1185 }
1186
1187 // The user has decided to steal the lock... rerun the command with "&steal_lock="
1188 gliserver_args += "&steal_lock=";
1189 continue;
1190 }
1191 // Handle other types of errors by throwing an exception
1192 else if (command_output.startsWith("ERROR: ")) {
1193 throw new Exception(command_output.substring("ERROR: ".length()));
1194 }
1195
1196 // There were no exceptions thrown so the action must have succeeded
1197 return command_output;
1198 }
1199 }
1200
1201
1202 // ----------------------------------------------------------------------------------------------------
1203 // NETWORK LAYER
1204 // ----------------------------------------------------------------------------------------------------
1205
1206
1207 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
1208 static private String downloadFileInternal(String download_cgi, String cgi_args, String file_path)
1209 throws Exception
1210 {
1211 DebugStream.println("gliserver URL: " + download_cgi);
1212 System.err.println("gliserver args: " + cgi_args);
1213
1214 // Add username and password, and a timestamp
1215 cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
1216 cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
1217 cgi_args += "&ts=" + System.currentTimeMillis();
1218 if (Gatherer.GS3){
1219 cgi_args += "&site=" + Configuration.site_name;
1220 }
1221
1222 URL download_url = new URL(download_cgi);
1223 URLConnection dl_connection = download_url.openConnection();
1224 dl_connection.setDoOutput(true);
1225 OutputStream dl_os = dl_connection.getOutputStream();
1226
1227 PrintWriter dl_out = new PrintWriter(dl_os);
1228 dl_out.println(cgi_args);
1229 dl_out.close();
1230
1231 // Download result from running cgi script
1232 InputStream dl_is = dl_connection.getInputStream();
1233 BufferedInputStream dl_bis = new BufferedInputStream(dl_is);
1234 DataInputStream dl_dbis = new DataInputStream(dl_bis);
1235
1236 String first_line = "";
1237 byte[] buf = new byte[1024];
1238 int len = dl_dbis.read(buf);
1239 if (len >= 0) {
1240 String first_chunk = new String(buf, 0, len);
1241 // first_line = first_chunk.substring(0, ((first_chunk.indexOf("\n") != -1) ? first_chunk.indexOf("\n") : len));
1242 first_line = first_chunk.substring(0, ((first_chunk.indexOf("\n") != -1) ? first_chunk.indexOf("\n") : ((first_chunk.length()<len) ? first_chunk.length():len)));
1243 // Save the data to file
1244 FileOutputStream zip_fos = new FileOutputStream(file_path);
1245 BufferedOutputStream zip_bfos = new BufferedOutputStream(zip_fos);
1246
1247 while (len >= 0) {
1248 zip_bfos.write(buf, 0, len);
1249 len = dl_dbis.read(buf);
1250 }
1251
1252 zip_bfos.close();
1253 zip_fos.close();
1254 }
1255
1256 dl_dbis.close();
1257 dl_bis.close();
1258 dl_is.close();
1259 return first_line;
1260 }
1261
1262
1263 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
1264 static private String sendCommandToServerInternal(String gliserver_url_string, String cgi_args, GShell shell)
1265 throws Exception
1266 {
1267 DebugStream.println("gliserver URL: " + gliserver_url_string);
1268 System.err.println("gliserver args: " + cgi_args);
1269
1270 // Add username and password, and a timestamp
1271 if(isAuthenticationRequired(cgi_args)) {
1272 cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
1273 cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
1274 }
1275 cgi_args += "&ts=" + System.currentTimeMillis();
1276 if (Gatherer.GS3){
1277 cgi_args += "&site=" + Configuration.site_name;
1278 }
1279
1280 URL gliserver_url = new URL(gliserver_url_string + "?" + cgi_args);
1281 URLConnection gliserver_connection = gliserver_url.openConnection();
1282
1283 // Read the output of the command from the server, and return it
1284 StringBuffer command_output_buffer = new StringBuffer(2048);
1285 InputStream gliserver_is = gliserver_connection.getInputStream();
1286 BufferedReader gliserver_in = new BufferedReader(new InputStreamReader(gliserver_is, "UTF-8"));
1287 String gliserver_output_line = gliserver_in.readLine();
1288 while (gliserver_output_line != null) {
1289 if (shell != null) {
1290 shell.fireMessage(gliserver_output_line);
1291 if (shell.hasSignalledStop()) {
1292 throw new RemoteGreenstoneServerActionCancelledException();
1293 }
1294 }
1295 command_output_buffer.append(gliserver_output_line + "\n");
1296 gliserver_output_line = gliserver_in.readLine();
1297 }
1298 gliserver_in.close();
1299
1300 return command_output_buffer.toString();
1301 }
1302
1303
1304 /** Returns the command output if the action completed, throws some kind of exception otherwise. */
1305 static private String uploadFileInternal(String upload_cgi, String cgi_args, String file_path)
1306 throws Exception
1307 {
1308 System.err.println("gliserver URL: " + upload_cgi);
1309 System.err.println("gliserver args: " + cgi_args);
1310
1311 //For a remote GS3
1312 //GS3 is running on Tomcat, and Tomcat requires a connection timeout to be set up at the client
1313 //side while uploading files. As HttpURLConnection couldn't set the connection timeout, HttpClient.jar
1314 //from Jakarta is applied to solve this problem only for uploading files.
1315 if (Gatherer.GS3) {
1316
1317 // Setup the POST method
1318 PostMethod httppost = new PostMethod(upload_cgi+"?"+cgi_args); // cgi_args: QUERY_STRING on perl server side
1319
1320 // construct the multipartrequest form
1321 String[] cgi_array=cgi_args.split("&");// get parameter-value pairs from cgi_args string
1322 Part[] parts=new Part[cgi_array.length+5];
1323
1324 // The FilePart: consisting of the (cgi-arg) name and (optional) filename in the Content-Disposition
1325 // of the POST request Header (see CGI.pm), and the actual zip file itself. It uses the defaults:
1326 // Content-Type: application/octet-stream; charset=ISO-8859-1,Content-Transfer-Encoding: binary
1327 parts[0]= new FilePart("uploaded_file", "zipFile", new File(file_path));
1328
1329 parts[1]= new StringPart("un", remote_greenstone_server_authentication.getUserName());
1330 parts[2]= new StringPart("pw", new String(remote_greenstone_server_authentication.getPassword()));
1331 parts[3]= new StringPart("ts", String.valueOf(System.currentTimeMillis()));
1332 parts[4]= new StringPart("site", Configuration.site_name);
1333 // find all parameters of cgi-args and add them into Part[]
1334 for (int i=0; i<cgi_array.length;i++){
1335 parts[5+i]=new StringPart(cgi_array[i].substring(0,cgi_array[i].indexOf("=")),cgi_array[i].substring(cgi_array[i].indexOf("=")+1,cgi_array[i].length()));
1336 }
1337
1338 // set MultipartRequestEntity on the POST method
1339 httppost.setRequestEntity(new MultipartRequestEntity(parts, httppost.getParams()));
1340
1341 // See file gli/request.txt for the multipart request that's been generated:
1342 //httppost.getRequestEntity().writeRequest(new FileOutputStream("request.txt", true)); // true: appends
1343
1344 //set up the HttpClient connection
1345 HttpClient client=new HttpClient();
1346 client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
1347 client.getParams().setConnectionManagerTimeout(200000); //set the connection timeout
1348 // get the output of the command from the server
1349 String command_output = "";
1350 try{
1351 client.executeMethod(httppost);
1352 if (httppost.getStatusCode() == HttpStatus.SC_OK) {
1353 command_output = httppost.getStatusLine().toString();
1354 } else {
1355 command_output = httppost.getStatusLine().toString();
1356 System.out.println("Unexpected failure: " + httppost.getStatusLine().toString());
1357 }
1358 }catch(IOException e){
1359 e.printStackTrace();
1360 }finally{
1361 httppost.releaseConnection();
1362 }
1363 return command_output;
1364 }
1365
1366 //For a remote GS2
1367 // Add username and password, and a timestamp
1368 cgi_args += "&un=" + remote_greenstone_server_authentication.getUserName();
1369 cgi_args += "&pw=" + new String(remote_greenstone_server_authentication.getPassword());
1370 cgi_args += "&ts=" + System.currentTimeMillis();
1371
1372 // Open a HTTP connection to the URL
1373 URL url = new URL(upload_cgi);
1374 HttpURLConnection gliserver_connection = (HttpURLConnection) url.openConnection();
1375
1376 gliserver_connection.setDoInput(true); // Allow Inputs
1377 gliserver_connection.setDoOutput(true); // Allow Outputs
1378 gliserver_connection.setUseCaches(false); // Don't use a cached copy.
1379
1380 gliserver_connection.setRequestProperty("Connection", "Keep-Alive");
1381
1382 // Send zip file to server
1383 File file = new File(file_path);
1384 FileInputStream fileInputStream = new FileInputStream(file);
1385
1386 // Add file size argument, because IIS 6 needs a lot of help
1387 int file_size = fileInputStream.available();
1388 cgi_args += "&fs=" + file_size;
1389
1390 DataOutputStream dos = new DataOutputStream(gliserver_connection.getOutputStream());
1391 dos.writeBytes(cgi_args + "\n");
1392
1393 // create a buffer of maximum size
1394 final int maxBufferSize = 1024;
1395 int bytesAvailable = file_size;
1396 int bufferSize = Math.min(bytesAvailable, maxBufferSize);
1397 byte[] buffer = new byte[bufferSize];
1398
1399 // read file and write it into form...
1400 // !! This uses a lot of memory when the file being uploaded is big -- Java seems to need to keep
1401 // the entire file in the DataOutputStream? (Use Runtime.getRuntime().totalMemory() to see)
1402 int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
1403 while (bytesRead > 0) {
1404 dos.write(buffer, 0, bytesRead);
1405 bytesAvailable = fileInputStream.available();
1406 bufferSize = Math.min(bytesAvailable, maxBufferSize);
1407 bytesRead = fileInputStream.read(buffer, 0, bufferSize);
1408 }
1409
1410 // close streams
1411 fileInputStream.close();
1412 dos.flush();
1413 dos.close();
1414
1415 // Read the output of the command from the server, and return it
1416 String command_output = "";
1417 InputStream gliserver_is = gliserver_connection.getInputStream();
1418 BufferedReader gliserver_in = new BufferedReader(new InputStreamReader(gliserver_is, "UTF-8"));
1419 String gliserver_output_line = gliserver_in.readLine();
1420 while (gliserver_output_line != null) {
1421 command_output += gliserver_output_line + "\n";
1422 gliserver_output_line = gliserver_in.readLine();
1423 }
1424 gliserver_in.close();
1425
1426 return command_output;
1427 }
1428
1429
1430 // ----------------------------------------------------------------------------------------------------
1431 // UTILITIES
1432 // ----------------------------------------------------------------------------------------------------
1433
1434
1435 static public String getPathRelativeToDirectory(File file, String directory_path)
1436 {
1437 String file_path = file.getAbsolutePath();
1438 if (!file_path.startsWith(directory_path)) {
1439 System.err.println("ERROR: File path " + file_path + " is not a child of " + directory_path);
1440 return file_path;
1441 }
1442
1443 String relative_file_path = file_path.substring(directory_path.length());
1444 if (relative_file_path.startsWith(File.separator)) {
1445 relative_file_path = relative_file_path.substring(File.separator.length());
1446 }
1447 return relative_file_path;
1448 }
1449}
Note: See TracBrowser for help on using the repository browser.