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

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

Three changes: 1. Added method and corresponding Action class to get the Library URL suffix (for the GLI preview URL); 2. isAuthenticationRequired() method that will return false when the cmds to be sent to the gliserver are either get-greenstone-version or get-library-suffix-url; 3. FileNotFoundException handled when trying to connect to gliserver.pl and the wrong url for it is provided (program exits)

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