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

Last change on this file since 14601 was 14601, checked in by qq6, 17 years ago

added a guide

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