source: trunk/gli/src/org/greenstone/gatherer/Gatherer.java@ 8597

Last change on this file since 8597 was 8597, checked in by mdewsnip, 19 years ago

Made Gatherer.configServer static.

  • Property svn:keywords set to Author Date Id Revision
File size: 36.7 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: John Thompson, Greenstone Digital Library, University of Waikato
9 *
10 * Copyright (C) 1999 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 */
27package org.greenstone.gatherer;
28
29//import com.l2fprod.gui.*;
30//import com.l2fprod.gui.plaf.skin.*;
31//import com.l2fprod.util.*;
32import java.awt.*;
33import java.awt.event.*;
34import java.io.*;
35import java.lang.*;
36import java.net.*;
37import java.util.*;
38import javax.swing.*;
39import javax.swing.plaf.*;
40import javax.swing.text.*;
41import org.greenstone.gatherer.Configuration;
42import org.greenstone.gatherer.GAuthenticator;
43import org.greenstone.gatherer.collection.CollectionManager;
44import org.greenstone.gatherer.feedback.ActionRecorderDialog;
45import org.greenstone.gatherer.file.FileManager;
46import org.greenstone.gatherer.file.FileAssociationManager;
47import org.greenstone.gatherer.gui.GUIManager;
48import org.greenstone.gatherer.gui.Splash;
49import org.greenstone.gatherer.gui.URLField;
50import org.greenstone.gatherer.gui.WarningDialog;
51import org.greenstone.gatherer.util.GSDLSiteConfig;
52import org.greenstone.gatherer.util.StaticStrings;
53import org.greenstone.gatherer.util.Utility;
54// import sun.misc.*;
55
56/** Containing the top-level "core" for the Gatherer, this class is the
57 * common core for the GLI application and applet. It first parses the
58 * command line arguments, preparing to update the configuration as
59 * required. Next it loads several important support classes such as the
60 * Configuration and Dictionary. Finally it creates the other important
61 * managers and sends them on their way.
62 * @author John Thompson, Greenstone Digital Library, University of Waikato
63 * @version 2.3
64 */
65
66// How to catch All Exceptions including those from the AWT Event thread.
67// Step 1: register a handler class in your main()
68//
69// System.setProperty("sun.awt.exception.handler", "YourHandler");
70//
71// Step 2: implement your handler class.
72//
73// public class YourHandler {
74// public void handle(Throwable thrown) {
75// eat the exception without dumping to the console.
76// }
77// }
78
79public class Gatherer
80{
81 static public Hashtable authentications = new Hashtable();
82
83 static final private String SKIN_DEFINITION_FILE = "lib/greenaqua/greenaqua.xml";
84
85 static public boolean always_show_exceptions = true;
86 /** Has the exit flag been set? <i>true</i> if so, <i>false</i> otherwise. */
87 public boolean exit = false;
88 /** The size of the Gatherer window. */
89 public Dimension frame_size = null;
90
91 /** All of the external applications that must exit before we close the Gatherer. */
92 public Vector apps = new Vector();
93 /** A public reference to the FileAssociationManager. */
94 static public FileAssociationManager assoc_man;
95 /** A public reference to the CollectionManager. */
96 static public CollectionManager c_man;
97 /** a reference to the Servlet Configuration is GS3 */
98 static public ServletConfiguration servlet_config;
99 /** A public reference to the Dictionary. */
100 static public Dictionary dictionary;
101 /** A public reference to the FileManager. */
102 static public FileManager f_man;
103 /** A public reference to the GUIManager. */
104 static public GUIManager g_man;
105 static public boolean g_man_built = false;
106
107 /** A static reference to ourselves. */
108 static public Gatherer self;
109 /** We are using the GLI for GS3 */
110 static public boolean GS3 = false;
111
112 static public boolean isGsdlRemote = false;
113 static public String cgiBase = "";
114
115 // feedback stuff
116 /** is the feedback feature enabled? */
117 static public boolean feedback_enabled = true;
118 /** the action recorder dialog */
119 static public ActionRecorderDialog feedback_dialog = null;
120 /** Extra environment information which must be set before shell processes will run properly. Should always be null if the startup script/program has done its job properly. */
121 static public String extra_env[] = null;
122 private GSDLSiteConfig gsdlsite_cfg = null;
123 private ExternalApplication server = null;
124
125 /** Magic to allow Enter to fire the default button. */
126 static {
127 KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
128 Keymap map = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
129 map.removeKeyStrokeBinding(enter);
130 }
131
132 public Gatherer()
133 {
134 this.self = this;
135
136 Utility.initImages(this);
137 }
138
139
140 public GUIManager init(Dimension size, String gsdl_path, String gsdl3_path,
141 String exec_path, boolean debug_enabled, String perl_path,
142 boolean no_load, String open_collection,
143 String site_name, String servlet_path,
144 boolean mirroring_enabled, String wget_version_str,
145 String wget_path)
146 {
147
148 // This will hopefully catch ctrl-c and terminate, and exit gracefully. However it is platform specific, and may not be supported by some JVMs.
149 /** It does, but I get bloody sick of it working when the Gatherer hangs.
150 CTRLCHandler handler = new CTRLCHandler();
151 Signal.handle(new Signal("INT"), handler);
152 Signal.handle(new Signal("TERM"), handler);
153 handler = null;
154 */
155 if (gsdl3_path != null && !gsdl3_path.equals("")) {
156 this.GS3 = true;
157 } else {
158 gsdl3_path = null;
159 }
160 // Create the debug stream only if required.
161 if (debug_enabled) {
162 DebugStream.enableDebugging();
163
164 Calendar now = Calendar.getInstance();
165 String debug_file_path = "debug" + now.get(Calendar.DATE) + "-" + now.get(Calendar.MONTH) + "-" + now.get(Calendar.YEAR) + ".txt";
166
167 // Debug file is created in the GLI directory, unless the GLI is running as an applet
168 if (isGsdlRemote) {
169 debug_file_path = Utility.getGLIUserFolder().toString() + File.separator + debug_file_path;
170 }
171 DebugStream.println("Debug file path: " + debug_file_path);
172 DebugStream.setDebugFile(debug_file_path);
173 DebugStream.print(System.getProperties());
174 }
175 try {
176 // Load Config
177 loadConfig(gsdl_path, gsdl3_path, exec_path, perl_path, mirroring_enabled, site_name);
178
179 // I don't really know what this is for but I've moved it here from Configuration
180 if (isGsdlRemote && Utility.isWindows() && Configuration.perl_path != null) {
181 if (Configuration.perl_path.toLowerCase().endsWith("perl.exe")) {
182 Configuration.perl_path = Configuration.perl_path.substring(0, Configuration.perl_path.length() - "perl.exe".length());
183 }
184 if (Configuration.perl_path.endsWith(File.separator)) {
185 Configuration.perl_path = Configuration.perl_path.substring(0, Configuration.perl_path.length() - File.separator.length());
186 }
187 }
188
189 if (GS3 && Configuration.servlet_path == null) {
190 Configuration.servlet_path = servlet_config.getServletPath(Configuration.site_name);
191 }
192
193 // the feedback dialog has been loaded with a default locale,
194 // now set the user specified one
195 if (feedback_enabled && feedback_dialog != null) {
196 feedback_dialog.setLocale(Configuration.getLocale("general.locale", true));
197 }
198
199 // Read Dictionary
200 dictionary = new Dictionary(Configuration.getLocale("general.locale", true), Configuration.getFont("general.font", true));
201
202
203 if (gsdl_path == null) {
204 missingGSDL();
205 }
206
207 // If we were given a server run it if neccessary.
208 if (!GS3 && Configuration.exec_file != null) {
209 startServerEXE();
210 }
211
212 // Having loaded the configuration (necessary to determine if certain warnings have been disabled) and dictionary, we now check if the necessary path variables have been provided.
213 if (Configuration.exec_file == null && Configuration.exec_address == null) {
214 DebugStream.println("config.exec_file is null");
215 DebugStream.println("config.exec_address is null");
216 missingEXEC();
217 }
218
219 if (Gatherer.isGsdlRemote) {
220 DebugStream.println("Not checking for perl path/exe");
221 }
222 else {
223 // Perl path is a little different as it is perfectly ok to
224 // start the Gatherer without providing a perl path
225 boolean found_perl = false;
226 if (Configuration.perl_path != null) {
227 // See if the file pointed to actually exists
228 File perl_file = new File(Configuration.perl_path);
229 found_perl = perl_file.exists();
230 perl_file = null;
231 }
232 if (Configuration.perl_path == null || !found_perl) {
233 // Run test to see if we can run perl as is.
234 PerlTest perl_test = new PerlTest();
235 if (perl_test.found()) {
236 // If so replace the perl path with the system
237 // default (or null for unix).
238 Configuration.perl_path = perl_test.toString();
239 found_perl = true;
240 }
241 }
242 if (!found_perl) {
243 // Time for an error message.
244 missingPERL();
245 }
246 }
247
248 // also check for wget
249 boolean mirror_workflow = Configuration.get(StaticStrings.WORKFLOW_MIRROR, false);
250 if (mirror_workflow) {
251 wget_version_str = StaticStrings.NO_WGET_STR;
252 // has the user specified a path?
253 if (wget_path != null && !wget_path.equals("")) {
254 File wget_file = new File(wget_path);
255 if (wget_file.exists()) {
256 // we assume its ok if its there
257 wget_version_str = StaticStrings.WGET_STR;
258 }
259 }
260
261 // it hasn't been set by the user so we use the greenstone one
262 if (wget_version_str.equals(StaticStrings.NO_WGET_STR)) {
263 // TODO fix for gs3
264 wget_path = Utility.getWGetPath(gsdl_path);
265 File wget_file = new File(wget_path);
266 if (!wget_file.exists()) {
267 // we give up trying to find one
268 missingWGET();
269 } else {
270 // we have found one
271 wget_version_str = StaticStrings.WGET_STR;
272 }
273 }
274
275 if (wget_version_str.equals(StaticStrings.WGET_STR)) {
276 // we have found one, should we check the version??
277 wget_version_str = testWGetVersion(wget_path);
278 if (wget_version_str.equals(StaticStrings.WGET_OLD_STR)) {
279 oldWGET();
280 }
281 }
282
283 // tell the config the new values
284 Configuration.setWGetPath(wget_path);
285 Configuration.setWGetVersion(wget_version_str);
286 }
287
288 // Set default font
289 setUIFont(Configuration.getFont("general.font", true), Configuration.getFont("general.tooltip_font", true));
290 // Set up proxy
291 setProxy();
292 // Now we set up an Authenticator
293 Authenticator.setDefault(new GAuthenticator());
294
295 assoc_man = new FileAssociationManager();
296 // Create File Manager
297 f_man = new FileManager();
298 // Create Collection Manager
299 c_man = new CollectionManager();
300
301 if (GS3) {
302 if (site_name==null) {
303 site_name = Configuration.site_name;
304 servlet_path = null; // need to reset this
305 }
306 if (servlet_path == null) {
307 servlet_path = Configuration.getServletPath();
308 }
309 }
310
311 // If there was an open collection last session, reopen it.
312 if (open_collection == null) {
313 open_collection = Configuration.getString("general.open_collection", true);
314 }
315 if (!no_load && open_collection.length() > 0) {
316 c_man.loadCollection(open_collection);
317 }
318
319 }
320 catch (Exception exception) {
321 DebugStream.printStackTrace(exception);
322 }
323
324 // Create GUI Manager (last) or else suffer the death of a thousand NPE's
325 g_man = new GUIManager(size);
326
327 return g_man;
328 }
329
330
331
332 public void run(Dimension size, Splash splash, GUIManager g_man)
333 {
334 // Size and place the frame on the screen
335 Rectangle bounds = Configuration.getBounds("general.bounds", true);
336 if (bounds == null) {
337 // Choose a sensible default value
338 bounds = new Rectangle(0, 0, 640, 480);
339 }
340
341 // Ensure width and height are reasonable
342 size = bounds.getSize();
343 if (size.width < 640) {
344 size.width = 640;
345 }
346 else if (size.width > Configuration.screen_size.width) {
347 size.width = Configuration.screen_size.width;
348 }
349 if (size.height < 480) {
350 size.height = 480;
351 }
352 else if (size.height > Configuration.screen_size.height) {
353 size.height = Configuration.screen_size.height;
354 }
355
356 if (splash != null) { splash.toFront(); }
357
358 if (!g_man_built) {
359
360 g_man.display();
361
362 // Place the window in the desired location on the screen, if this is do-able (not under most linux window managers apparently. In fact you're lucky if they listen to any of your screen size requests).
363 g_man.setLocation(bounds.x, bounds.y);
364 g_man.setVisible(true);
365
366 // After the window has been made visible, check that it is in the correct place
367 // sometimes java places a window not in the correct place,
368 // but with an offset. If so, we work out what the offset is
369 // and change the desired location to take that into account
370 Point location = g_man.getLocation();
371 int x_offset = bounds.x - location.x;
372 int y_offset = bounds.y - location.y;
373 // If not, offset the window to move it into the correct location
374 if (x_offset > 0 || y_offset > 0) {
375 ///ystem.err.println("changing the location to "+(bounds.x + x_offset)+" "+ (bounds.y + y_offset));
376 g_man.setLocation(bounds.x + x_offset, bounds.y + y_offset);
377 }
378
379 // The 'after-display' triggers several events which don't occur until after the visual components are actually available on screen. Examples of these would be the various html renderings, as they can't happen offscreen.
380 g_man.afterDisplay();
381 g_man_built = true;
382 }
383 else {
384 g_man.setVisible(true);
385 }
386
387 if (splash != null) {
388 // Hide the splash screen
389 splash.setVisible(false);
390 splash.destroy();
391 splash = null;
392 }
393 }
394
395
396 /** Exits the Gatherer after ensuring that things needing saving are saved.
397 * @see java.io.FileOutputStream
398 * @see java.io.PrintStream
399 * @see java.lang.Exception
400 * @see javax.swing.JOptionPane
401 * @see org.greenstone.gatherer.Configuration
402 * @see org.greenstone.gatherer.collection.CollectionManager
403 * @see org.greenstone.gatherer.gui.GUIManager
404 */
405 public void exit() {
406 exit = true;
407 // If we have an open collection make note of it.
408 Configuration.setString("general.open_collection", true, null);
409 if(c_man.ready()) {
410 ///ystem.err.println("Collection open.");
411 if(c_man.saved()) {
412 ///ystem.err.println("Collection has been recently saved, so I'll remember it for next time.");
413 Configuration.setString("general.open_collection", true, c_man.getCollectionFilename());
414 }
415 c_man.closeCollection();
416 }
417 if(assoc_man != null) {
418 assoc_man.save();
419 assoc_man = null;
420 }
421
422 // Store the current position and size (if reasonable) of the Gatherer for next time
423 Rectangle bounds = g_man.getBounds();
424 Configuration.setBounds("general.bounds", true, bounds);
425
426 // Save configuration.
427 saveConfig();
428
429 // Get the gui to deallocate
430 g_man.setVisible(false);
431 g_man.destroy();
432 g_man_built = false;
433
434
435 // Flush dictionary
436 // dictionary.destroy();
437
438 // Flush debug
439 DebugStream.closeDebugStream();
440
441 // If we started a server, we should try to stop it.
442 if(!GS3 && gsdlsite_cfg != null) {
443 stopServerEXE();
444 }
445
446 if(apps.size() == 0) {
447 if (!Gatherer.isGsdlRemote) {
448 System.exit(0);
449 }
450 }
451 else {
452 JOptionPane.showMessageDialog(g_man, Dictionary.get("General.Outstanding_Processes"), Dictionary.get("General.Outstanding_Processes_Title"), JOptionPane.ERROR_MESSAGE);
453 g_man.setVisible(false);
454 }
455 }
456
457 // Used to send messages to the local library
458 // Warning: this has a lot of potential for nasty race conditions
459 // The response code is returned immediately -- but this does not mean the local
460 // library action has finished!
461 static public void configServer(String command)
462 {
463 try {
464 String raw_url = Configuration.exec_address.toString() + command;
465 URL url = new URL(raw_url);
466 DebugStream.println("Action: " + raw_url);
467 HttpURLConnection library_connection = (HttpURLConnection) url.openConnection();
468 int response_code = library_connection.getResponseCode();
469 if(HttpURLConnection.HTTP_OK <= response_code && response_code < HttpURLConnection.HTTP_MULT_CHOICE) {
470 DebugStream.println("200 - Complete.");
471 }
472 else {
473 DebugStream.println("404 - Failed.");
474 }
475 url = null;
476 }
477 catch (Exception ex) {
478 DebugStream.printStackTrace(ex);
479 }
480 }
481
482 // used to send reload coll messages to the tomcat server
483 static public void configGS3Server(String site, String command) {
484
485 try {
486 // need to add the servlet name to the exec address
487 String raw_url = Configuration.exec_address.toString() + Configuration.getServletPath() + command;
488 URL url = new URL(raw_url);
489 DebugStream.println("Action: " + raw_url);
490 HttpURLConnection library_connection = (HttpURLConnection) url.openConnection();
491 int response_code = library_connection.getResponseCode();
492 if(HttpURLConnection.HTTP_OK <= response_code && response_code < HttpURLConnection.HTTP_MULT_CHOICE) {
493 DebugStream.println("200 - Complete.");
494 }
495 else {
496 DebugStream.println("404 - Failed.");
497 }
498 url = null;
499 }
500 catch (Exception exception) {
501 DebugStream.printStackTrace(exception);
502 }
503 }
504
505 /** Retrieve the metadata directory, as required by any MSMCaller implementation.
506 * @return The currently active collection metadata directory as a <strong>String</strong>.
507 * @see org.greenstone.gatherer.collection.CollectionManager
508 */
509 public String getCollectionMetadata() {
510 if (c_man != null && c_man.ready()) {
511 return c_man.getCollectionMetadata();
512 }
513 return "";
514 }
515
516 /** Used to 'spawn' a new child application when a file is double clicked.
517 * @param file The file to open
518 * @see org.greenstone.gatherer.Gatherer.ExternalApplication
519 */
520 public void spawnApplication(File file) {
521 String [] commands = assoc_man.getCommand(file);
522 if(commands != null) {
523 ExternalApplication app = new ExternalApplication(commands);
524 apps.add(app);
525 app.start();
526 }
527 else {
528 ///ystem.err.println("No open command available.");
529 }
530 }
531
532 /** Used to 'spawn' a new browser application or reset an existing one when the preview button is clicked
533 * @param url The url to open the browser at
534 * @see org.greenstone.gatherer.Gatherer.BrowserApplication
535 */
536 public void spawnBrowser(String url) {
537 String command = assoc_man.getBrowserCommand(url);
538 if (command != null) {
539 BrowserApplication app = new BrowserApplication(command, url);
540 apps.add(app);
541 app.start();
542 }
543 else {
544 ///ystem.err.println("No browser command available.");
545 }
546 }
547
548 /** Prints a warning message about a missing library path, which means the final collection cannot be previewed in the Gatherer.
549 */
550 static public void missingEXEC() {
551 String message_name;
552 if (GS3) {
553 message_name = "warning.MissingEXEC_GS3";
554 } else {
555 message_name = "warning.MissingEXEC";
556 }
557 WarningDialog dialog = new WarningDialog(message_name, "general.exec_address" );
558 dialog.setValueField(new URLField(Configuration.getColor("coloring.editable_foreground", false), Configuration.getColor("coloring.editable_background", false), Configuration.getColor("coloring.error_foreground", false), Configuration.getColor("coloring.error_background", false)));
559 dialog.display();
560 dialog.dispose();
561 dialog = null;
562
563 String library_path_string = Configuration.getString("general.exec_address", true);
564 if (!library_path_string.equals("")) {
565 try {
566 Configuration.exec_address = new URL(library_path_string);
567 }
568 catch (MalformedURLException error) {
569 ///ystem.err.println("Error: Bad address: " + exec_address_string);
570 }
571 }
572 }
573
574 /** Prints a warning message about a missing GSDL path, which although not fatal pretty much ensures nothing will work properly in the Gatherer.
575 */
576 static public void missingGSDL() {
577 WarningDialog dialog = new WarningDialog("warning.MissingGSDL", false);
578 dialog.display();
579 dialog.dispose();
580 dialog = null;
581 }
582
583 /** Prints a warning message about a missing PERL path, which although not fatal pretty much ensures no collection creation/building will work properly in the Gatherer. */
584 static public void missingPERL() {
585 WarningDialog dialog = new WarningDialog("warning.MissingPERL", false);
586 dialog.display();
587 dialog.dispose();
588 dialog = null;
589 }
590
591 /** Prints a warning message about a missing a valid WGet path. not fatal, but mirroring won't work */
592 static public void missingWGET() {
593 WarningDialog dialog = new WarningDialog("warning.MissingWGET", false);
594 dialog.display();
595 dialog.dispose();
596 dialog = null;
597 }
598 /** Prints a warning message about having an old version of WGet. not fatal, but mirroring may not work properly */
599 static public void oldWGET() {
600 WarningDialog dialog = new WarningDialog("warning.OldWGET", false);
601 dialog.display();
602 dialog.dispose();
603 dialog = null;
604 }
605
606
607 /** Sets up the proxy connection by setting JVM Environment flags and creating a new Authenticator.
608 * @see java.lang.Exception
609 * @see java.lang.System
610 * @see java.net.Authenticator
611 * @see org.greenstone.gatherer.Configuration
612 * @see org.greenstone.gatherer.GAuthenticator
613 */
614 static public void setProxy() {
615 try {// Can throw several exceptions
616 if(Configuration.get("general.use_proxy", true)) {
617 System.setProperty("http.proxyType", "4");
618 System.setProperty("http.proxyHost", Configuration.getString("general.proxy_host", true));
619 System.setProperty("http.proxyPort", Configuration.getString("general.proxy_port", true));
620 System.setProperty("http.proxySet", "true");
621 } else {
622 System.setProperty("http.proxySet", "false");
623 }
624 } catch (Exception error) {
625 DebugStream.println("Error in Gatherer.initProxy(): " + error);
626 DebugStream.printStackTrace(error);
627 }
628 }
629
630 /** Set all the default fonts of the program to a choosen font, except the tooltip font which should be some fixed width font.
631 * @param f The default font to use in the Gatherer as a <strong>FontUIResource</strong>.
632 * @param ttf The tooltip font to use also as a <strong>FontUIResource</strong>.
633 * @see java.util.Enumeration
634 * @see javax.swing.UIManager
635 */
636 static private void setUIFont(FontUIResource f, FontUIResource ttf) {
637 // sets the default font for all Swing components.
638 // ex.
639 // setUIFont (new FontUIResource("Serif",Font.ITALIC,12));
640 //
641 Enumeration keys = UIManager.getDefaults().keys();
642 while (keys.hasMoreElements()) {
643 Object key = keys.nextElement();
644 Object value = UIManager.get (key);
645 if (value instanceof FontUIResource)
646 UIManager.put (key, f);
647 }
648 // Now set the tooltip font to some fixed width font
649 UIManager.put("ToolTip.font", ttf);
650 }
651
652 /** Loads the configuration file if one exists. Otherwise it creates a new one. Currently uses serialization.
653 * @param gsdl_path The path to the gsdl directory, gathered from the startup arguments, and presented as a <strong>String</strong>.
654 * @param exec_path The path to the library executable, gathered from the startup arguments, and presented as a <strong>String</strong>.
655 * @param perl_path The path to the PERL compiler as a <strong>String</strong>. Necessary for windows platform versions.
656 * @param mirroring_enabled
657 * @param wget_version_str
658 * @param wget_path
659 * @see java.io.FileInputStream
660 * @see java.io.ObjectInputStream
661 * @see java.lang.Exception
662 * @see org.greenstone.gatherer.Configuration
663 */
664 private void loadConfig(String gsdl_path, String gsdl3_path, String exec_path, String perl_path, boolean mirroring_enabled, String site_name) {
665 try {
666 new Configuration(gsdl_path, gsdl3_path, exec_path, perl_path, mirroring_enabled, site_name);
667 }
668 catch (Exception error) {
669 DebugStream.println(Configuration.CONFIG_XML+" is not a well formed XML document.");
670 DebugStream.printStackTrace(error);
671 }
672 if (GS3) {
673 try {
674 servlet_config = new ServletConfiguration(gsdl3_path);
675 } catch (Exception exception) {
676 DebugStream.printStackTrace(exception);
677 }
678 }
679 }
680
681 /** Causes the general configuration file to export itself to xml. Doesn't effect any remaining collection configuration, as its up to the collection manager to handle them (especially since we have no idea where they are going). */
682 private void saveConfig() {
683 try {
684 Configuration.save();
685 } catch (Exception exception) {
686 DebugStream.printStackTrace(exception);
687 }
688 }
689
690 private void startServerEXE() {
691 if(Configuration.exec_file != null && Configuration.exec_address == null && Utility.isWindows() && !GS3) {
692 // First of all we create a GSDLSiteCFG object and check if a URL is already present, in which case the server is already running.
693 gsdlsite_cfg = new GSDLSiteConfig(Configuration.exec_file);
694 String url = gsdlsite_cfg.getURL();
695 // If its already running then set exec address.
696 if(url != null) {
697 try {
698 Configuration.exec_address = new URL(url);
699 }
700 catch(Exception error) {
701 }
702 }
703 // Otherwise its time to run the server in a spawned process.
704 if(Configuration.exec_address == null && Configuration.exec_file.exists()) {
705 // Configure for immediate entry. Note that this only works if the gsdlsite.cfg file exists.
706 gsdlsite_cfg.set();
707 // Spawn server
708 String command = Configuration.exec_file.getAbsolutePath() + " " + gsdlsite_cfg.getSiteConfigFilename();
709 server = new ExternalApplication(command);
710 server.start();
711 command = null;
712 // Now we have to wait until program has started. We do this by reloading and checking
713 ///ystem.err.print("Waiting until the local library has loaded");
714 try {
715 gsdlsite_cfg.load();
716
717 int try_again = JOptionPane.YES_OPTION;
718 int attempt_count = 0;
719 while(gsdlsite_cfg.getURL() == null && try_again == JOptionPane.YES_OPTION) {
720 ///ystem.err.print(".");
721 if(attempt_count == 60) {
722 attempt_count = 0;
723 try_again = JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("Server.QuitTimeOut"), Dictionary.get("General.Warning"), JOptionPane.YES_NO_OPTION);
724 }
725 else {
726 synchronized(this) {
727 wait(1000); // Wait one second (give or take)
728 }
729 gsdlsite_cfg.load();
730 attempt_count++;
731 }
732 }
733
734 if((url = gsdlsite_cfg.getURL()) != null) {
735 // Ta-da. Now the url should be available.
736 Configuration.exec_address = new URL(url);
737
738 // A quick test involves opening a connection to get the home page for this collection. If this fails then we try changing the url to be localhost.
739 try {
740 DebugStream.println("Try connecting to server on config url: '" + Configuration.exec_address + "'");
741 URLConnection connection = Configuration.exec_address.openConnection();
742 connection.getContent();
743 }
744 catch(IOException bad_url_connection) {
745 try {
746 DebugStream.println("Try connecting to server on local host: '" + gsdlsite_cfg.getLocalHostURL() + "'");
747 Configuration.exec_address = new URL(gsdlsite_cfg.getLocalHostURL ());
748 URLConnection connection = Configuration.exec_address.openConnection();
749 connection.getContent();
750 }
751 catch(IOException worse_url_connection) {
752 DebugStream.println("Can't connect to server on either address.");
753 Configuration.exec_address = null;
754 Configuration.exec_file = null;
755 }
756 }
757 }
758 // Unable to start local library. Show appropriate message.
759 else {
760 missingEXEC();
761 }
762 }
763 catch (Exception exception) {
764 DebugStream.printStackTrace(exception);
765 }
766 }
767 // Can't do a damb thing.
768 }
769 DebugStream.println("Having started server.exe, exec_address is: " + Configuration.exec_address);
770 }
771
772 private void stopServerEXE() {
773 if(server != null && Configuration.exec_address != null) {
774 // See if its already exited for some reason.
775 gsdlsite_cfg.load();
776 if(gsdlsite_cfg.getURL() != null) {
777 // Send the command for it to exit.
778 configServer(GSDLSiteConfig.QUIT_COMMAND);
779 // Wait until it exits.
780 try {
781 gsdlsite_cfg.load();
782 int try_again = JOptionPane.YES_OPTION;
783 int attempt_count = 0;
784 while(gsdlsite_cfg.getURL() != null && try_again == JOptionPane.YES_OPTION) {
785 if(attempt_count == 60) {
786 attempt_count = 0;
787 try_again = JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("Server.QuitTimeOut"), Dictionary.get("General.Warning"), JOptionPane.YES_NO_OPTION);
788 }
789 else {
790 synchronized(this) {
791 wait(1000); // Wait one second (give or take)
792 }
793 gsdlsite_cfg.load();
794 attempt_count++;
795 }
796 }
797 //if(gsdlsite_cfg.getURL() != null) {
798 //JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("Server.QuitManual"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
799 //}
800 }
801 catch (Exception exception) {
802 DebugStream.printStackTrace(exception);
803 }
804 }
805 // Restore the gsdlsite_cfg.
806 if(gsdlsite_cfg != null) {
807 gsdlsite_cfg.restore();
808 }
809 // If the local server is still running then our changed values will get overwritten.
810 if(gsdlsite_cfg.getURL() != null) {
811 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("Server.QuitFailed"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
812 }
813 gsdlsite_cfg = null;
814 server = null;
815 }
816 }
817
818 // TODO fill this in
819 private String testWGetVersion(String wget_path) {
820 return StaticStrings.WGET_STR;
821 }
822
823 /** This private class contains an instance of an external application running within a JVM shell. It is important that this process sits in its own thread, but its more important that when we exit the Gatherer we don't actually System.exit(0) the Gatherer object until the user has volunteerily ended all of these child processes. Otherwise when we quit the Gatherer any changes the users may have made in external programs will be lost and the child processes are automatically deallocated. */
824 private class ExternalApplication
825 extends Thread {
826 private Process process = null;
827 /** The initial command string given to this sub-process. */
828 private String command = null;
829 private String[] commands = null;
830 /** Constructor.
831 * @param command The initial command <strong>String</strong>.
832 */
833 public ExternalApplication(String command) {
834 this.command = command;
835 }
836
837 public ExternalApplication(String[] commands) {
838 this.commands = commands;
839 }
840 /** We start the child process inside a new thread so it doesn't block the rest of Gatherer.
841 * @see java.lang.Exception
842 * @see java.lang.Process
843 * @see java.lang.Runtime
844 * @see java.lang.System
845 * @see java.util.Vector
846 */
847 public void run() {
848 // Call an external process using the args.
849 try {
850 if(commands != null) {
851 StringBuffer whole_command = new StringBuffer();
852 for(int i = 0; i < commands.length; i++) {
853 whole_command.append(commands[i]);
854 whole_command.append(" ");
855 }
856 DebugStream.println("Running " + whole_command.toString());
857 Runtime rt = Runtime.getRuntime();
858 process = rt.exec(commands);
859 process.waitFor();
860 }
861 else {
862 DebugStream.println("Running " + command);
863 Runtime rt = Runtime.getRuntime();
864 process = rt.exec(command);
865 process.waitFor();
866 }
867 }
868 catch (Exception exception) {
869 DebugStream.printStackTrace(exception);
870 }
871 // Remove ourself from Gatherer list of threads.
872 apps.remove(this);
873 // Call exit if we were the last outstanding child process thread.
874 if(apps.size() == 0 && exit == true) {
875 stopServerEXE();
876 System.exit(0);
877 }
878 }
879 public void stopExternalApplication() {
880 if(process != null) {
881 process.destroy();
882 }
883 }
884 }
885 /** This private class contains an instance of an external application running within a JVM shell. It is important that this process sits in its own thread, but its more important that when we exit the Gatherer we don't actually System.exit(0) the Gatherer object until the user has volunteerily ended all of these child processes. Otherwise when we quit the Gatherer any changes the users may have made in external programs will be lost and the child processes are automatically deallocated. */
886 private class BrowserApplication
887 extends Thread {
888 private Process process = null;
889 /** The initial command string given to this sub-process. */
890 private String command = null;
891 private String url = null;
892 private String[] commands = null;
893 /** Constructor.
894 * @param command The initial command <strong>String</strong>.
895 */
896// public BrowserApplication(String command) {
897// this.command = command;
898// }
899
900 public BrowserApplication(String command, String url) {
901 StringTokenizer st = new StringTokenizer(command);
902 int num_tokens = st.countTokens();
903 this.commands = new String [num_tokens];
904 int i=0;
905 while (st.hasMoreTokens()) {
906 commands[i] = st.nextToken();
907 i++;
908 }
909 //this.commands = commands;
910 this.url = url;
911 }
912 /** We start the child process inside a new thread so it doesn't block the rest of Gatherer.
913 * @see java.lang.Exception
914 * @see java.lang.Process
915 * @see java.lang.Runtime
916 * @see java.lang.System
917 * @see java.util.Vector
918 */
919 public void run() {
920 // Call an external process using the args.
921 if(commands == null) {
922 apps.remove(this);
923 return;
924 }
925 try {
926 String prog_name = commands[0];
927 String lower_name = prog_name.toLowerCase();
928 if (lower_name.indexOf("mozilla") != -1 || lower_name.indexOf("netscape") != -1) {
929 DebugStream.println("found mozilla or netscape, trying remote it");
930 // mozilla and netscape, try using a remote command to get things in the same window
931 String [] new_commands = new String[] {prog_name, "-raise", "-remote", "openURL("+url+",new-tab)"};
932 printArray(new_commands);
933
934 Runtime rt = Runtime.getRuntime();
935 process = rt.exec(new_commands);
936 int exitCode = process.waitFor();
937 if (exitCode != 0) { // if Netscape or mozilla was not open
938 DebugStream.println("couldn't do remote, trying original command");
939 printArray(commands);
940 process = rt.exec(commands); // try the original command
941 }
942 } else {
943 // just run what we have been given
944 StringBuffer whole_command = new StringBuffer();
945 for(int i = 0; i < commands.length; i++) {
946 whole_command.append(commands[i]);
947 whole_command.append(" ");
948 }
949 DebugStream.println("Running " + whole_command.toString());
950 Runtime rt = Runtime.getRuntime();
951 process = rt.exec(commands);
952 process.waitFor();
953 }
954 }
955
956 catch (Exception exception) {
957 DebugStream.printStackTrace(exception);
958 }
959 // Remove ourself from Gatherer list of threads.
960 apps.remove(this);
961 // Call exit if we were the last outstanding child process thread.
962 if(apps.size() == 0 && exit == true) {
963 stopServerEXE();
964 System.exit(0);
965 }
966 }
967 public void printArray(String [] array) {
968 for(int i = 0; i < array.length; i++) {
969 DebugStream.print(array[i]+" ");
970 System.err.println(array[i]+" ");
971 }
972 }
973 public void stopBrowserApplication() {
974 if(process != null) {
975 process.destroy();
976 }
977 }
978 }
979
980 /** This class is intented to detect a specific SIGNAL, in this case SIGINT, and exit properly, rather than letting the Gatherer be interrupted which has the potential to leave erroneous lock files. */
981// private class CTRLCHandler
982// implements SignalHandler {
983// /** <i>true</i> if we ignore any other signals we receive, most likely because we are already dealing with one, <i>false</i> otherwise. */
984// private boolean ignore = false;
985// /** The method called by the system to inform us a signal has occured.
986// * @param sig The <strong>Signal</strong> itself.
987// * @see org.greenstone.gatherer.collection.CollectionManager
988// */
989// public void handle(Signal sig) {
990// if(!ignore) {
991// ignore = true;
992// // handle SIGINT
993// System.out.println("Caught Ctrl-C...");
994// if(c_man != null && c_man.ready()) {
995// c_man.closeCollection();
996// }
997// exit();
998// ignore = false;
999// }
1000// }
1001// }
1002
1003 private class PerlTest {
1004
1005 private String[] command = new String[2];
1006
1007 public PerlTest() {
1008 if(Utility.isWindows()) {
1009 command[0] = Utility.PERL_EXECUTABLE_WINDOWS;
1010 }
1011 else {
1012 command[0] = Utility.PERL_EXECUTABLE_UNIX;
1013 }
1014 command[1] = "-version";
1015 }
1016
1017 public boolean found() {
1018 boolean found = false;
1019 try {
1020 Process prcs = Runtime.getRuntime().exec(command);
1021 prcs.waitFor();
1022 found = (prcs.exitValue() == 0);
1023 prcs = null;
1024 }
1025 catch(Exception error) {
1026 }
1027 return found;
1028 }
1029
1030 public String toString() {
1031 return command[0];
1032 }
1033 }
1034}
Note: See TracBrowser for help on using the repository browser.