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

Last change on this file since 14974 was 14974, checked in by davidb, 16 years ago

Changes to GLI to support export into Fedora. New utility called flisvn diff gems/MetadataSetManager.java

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