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

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

modified Download Collection file's ERROR string handling, added method exists(collection, file) to check if a file exists on the server end and to this end added class RemoteGreenstoneServerExistsAction

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