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

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

In uploadFileInternal(), undid introduction of dummy value and cgi-args are once again passed to the constructor of the PostMethod

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