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

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

Exit Client GLI (Gatherer.exit()) when user pressed cancel first time in the opening dialog or if the connection was refused, instead of a zillion error dialogs popping up because it tries to (but fails) to do more tasks.

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