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

Last change on this file since 23031 was 23031, checked in by ak19, 14 years ago

More changes to 2. Gatherer.java to allow empty string into config.xml for when the current collect dir is the default collect dir and 2. swapping between user names in applet (no longer loads open collections, because all collections are closed on exiting the applet).

  • Property svn:keywords set to Author Date Id Revision
File size: 56.1 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
29import java.awt.*;
30import java.awt.event.*;
31import java.io.*;
32import java.lang.*;
33import java.net.*;
34import java.util.*;
35import javax.swing.*;
36import javax.swing.plaf.*;
37import javax.swing.text.*;
38
39
40import org.greenstone.gatherer.Configuration;
41import org.greenstone.gatherer.GAuthenticator;
42import org.greenstone.gatherer.FedoraInfo;
43import org.greenstone.gatherer.collection.CollectionManager;
44import org.greenstone.gatherer.feedback.ActionRecorderDialog;
45import org.greenstone.gatherer.feedback.Base64;
46import org.greenstone.gatherer.file.FileManager;
47import org.greenstone.gatherer.file.FileAssociationManager;
48import org.greenstone.gatherer.file.RecycleBin;
49import org.greenstone.gatherer.greenstone.Classifiers;
50import org.greenstone.gatherer.greenstone.LocalGreenstone;
51import org.greenstone.gatherer.greenstone.LocalLibraryServer;
52import org.greenstone.gatherer.greenstone.Plugins;
53import org.greenstone.gatherer.greenstone3.ServletConfiguration;
54import org.greenstone.gatherer.gui.GUIManager;
55import org.greenstone.gatherer.gui.URLField;
56import org.greenstone.gatherer.gui.WarningDialog;
57import org.greenstone.gatherer.gui.FedoraLogin;
58import org.greenstone.gatherer.remote.RemoteGreenstoneServer;
59import org.greenstone.gatherer.util.JarTools;
60import org.greenstone.gatherer.util.StaticStrings;
61import org.greenstone.gatherer.util.Utility;
62
63
64/** Containing the top-level "core" for the Gatherer, this class is the
65 * common core for the GLI application and applet. It first parses the
66 * command line arguments, preparing to update the configuration as
67 * required. Next it loads several important support classes such as the
68 * Configuration and Dictionary. Finally it creates the other important
69 * managers and sends them on their way.
70 * @author John Thompson, Greenstone Digital Library, University of Waikato
71 * @version 2.3
72 */
73public class Gatherer
74{
75 /** The name of the GLI. */
76 static final public String PROGRAM_NAME = "Greenstone Librarian Interface";
77 /** The current version of the GLI.
78 * Note: the gs3-release-maker relies on this variable being declared
79 * in a line which maches this java regex:
80 * ^(.*)String\s*PROGRAM_VERSION\s*=\s*"trunk";
81 * If change the declaration and it no longer matches the regex, please
82 * change the regex in the gs3-release-maker code and in this message
83 */
84
85 static final public String PROGRAM_VERSION = "trunk";
86
87 static private Dimension size = new Dimension(800, 540);
88 static public RemoteGreenstoneServer remoteGreenstoneServer = null;
89
90 /** Has the exit flag been set? */
91 static final public int EXIT_THEN_RESTART= 2;
92 static public boolean exit = false;
93 static public int exit_status = 0;
94
95 static private String gli_directory_path = null;
96 static private String gli_user_directory_path = null;
97
98 static public String client_operating_system = null;
99
100 /** All of the external applications that must exit before we close the Gatherer. */
101 static private Vector apps = new Vector();
102 static private String non_standard_collect_directory_path = null;
103 static public String open_collection_file_path = null;
104 /** A public reference to the FileAssociationManager. */
105 static public FileAssociationManager assoc_man;
106 /** A public reference to the CollectionManager. */
107 static public CollectionManager c_man;
108 /** A public reference to the RecycleBin. */
109 static public RecycleBin recycle_bin;
110 /** a reference to the Servlet Configuration is GS3 */
111 static public ServletConfiguration servlet_config;
112 /** A public reference to the FileManager. */
113 static public FileManager f_man;
114 /** A public reference to the GUIManager. */
115 static public GUIManager g_man = null;
116 static private boolean g_man_built = false;
117
118 /** We are using the GLI for GS3 */
119 static public boolean GS3 = false;
120
121 static public boolean isApplet = false;
122 static public boolean isGsdlRemote = false;
123 static public boolean isLocalLibrary = false;
124
125 /* TODO: If we're using local GLI, collections are built locally. If we're using client-GLI
126 * and it contains a gs2build folder in it, then localBuild will also be true (if this is not
127 * turned off in Preferences). If we're remote and this is turned off in Prefs, build remotely. */
128 /*static public boolean buildingLocally = true;*/
129 /** If we're using local GLI, we can always download. If we're using client-GLI, we can only
130 * download if we have a gs2build folder inside it. And if we don't turn off downloadEnabling
131 * in the preferences.
132 */
133 static public boolean isDownloadEnabled = true;
134
135 // feedback stuff
136 /** is the feedback feature enabled? */
137 static public boolean feedback_enabled = true;
138 /** the action recorder dialog */
139 static public ActionRecorderDialog feedback_dialog = null;
140
141 // Refresh reasons
142 static public final int COLLECTION_OPENED = 0;
143 static public final int COLLECTION_CLOSED = 1;
144 static public final int COLLECTION_REBUILT = 2;
145 static public final int PREFERENCES_CHANGED = 3;
146
147 //////kk added////////
148 static public String cgiBase="";
149 /////////////////
150
151 /** Magic to allow Enter to fire the default button. */
152 static {
153 KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
154 Keymap map = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
155 map.removeKeyStrokeBinding(enter);
156 }
157
158 static private URL default_gliserver_url=null;
159
160 public Gatherer(String[] args)
161 {
162 // Display the version to make error reports a lot more useful
163 System.err.println("Version: " + PROGRAM_VERSION + "\n");
164
165 JarTools.initialise(this);
166
167 GetOpt go = new GetOpt(args);
168
169 // Remember the GSDLOS value
170 client_operating_system = go.client_operating_system;
171
172 // If feedback is enabled, set up the recorder dialog
173 if (go.feedback_enabled) {
174 // Use the default locale for now - this will be changed by the Gatherer run method
175 feedback_enabled = true;
176 feedback_dialog = new ActionRecorderDialog(Locale.getDefault());
177 }
178
179 // Are we using a remote Greenstone?
180 if (go.use_remote_greenstone) {
181 isGsdlRemote = true;
182
183 // We don't have a local Greenstone!
184 go.gsdl3_path=null;
185 go.gsdl3_src_path=null;
186
187 // Don't set go.gsdl_path to null, since gdsl_path may still be set
188 // if we have a client-gli containing gs2build folder.
189 // However, keep track of whether we can download.
190 if(go.gsdl_path == null) {
191 isDownloadEnabled = false;
192 }
193
194 // We have to use our own collect directory since we can't use the Greenstone one
195 setCollectDirectoryPath(getGLIUserDirectoryPath() + "collect" + File.separator);
196 }
197 // We have a local Greenstone. OR we have a gs2build folder inside
198 // the client-GLI folder (with which the Download panel becomes enabled)
199 if(isDownloadEnabled) {
200 LocalGreenstone.setDirectoryPath(go.gsdl_path);
201 }
202
203 // Users may specify a non-standard collect directory (eg. when running one GLI in a network environment)
204 if (go.collect_directory_path != null) {
205 setCollectDirectoryPath(go.collect_directory_path);
206 }
207
208 // More special code for running with a remote Greenstone
209 if (isGsdlRemote) {
210 if (go.fedora_info.isActive()) {
211 Configuration.TEMPLATE_CONFIG_XML = "xml/" + Configuration.FEDORA_CONFIG_PREFIX + "configRemote.xml";
212 }
213 else {
214 Configuration.TEMPLATE_CONFIG_XML = "xml/configRemote.xml";
215 }
216
217 Configuration.CONFIG_XML = "configRemote.xml";
218
219 File collect_directory = new File(Gatherer.getCollectDirectoryPath());
220 if (!collect_directory.exists() && !collect_directory.mkdir()) {
221 System.err.println("Warning: Unable to make directory: " + collect_directory);
222 }
223 }
224 else {
225 if (go.fedora_info.isActive()) {
226 Configuration.TEMPLATE_CONFIG_XML = "xml/" + Configuration.FEDORA_CONFIG_PREFIX + Configuration.CONFIG_XML;
227 }
228 // else, the CONFIG_XML uses the default config file, which is for the local GS server
229 }
230
231 init(go.gsdl_path, go.gsdl3_path, go.gsdl3_src_path,
232 go.fedora_info,
233 go.local_library_path, go.library_url_string,
234 go.gliserver_url_string, go.debug, go.perl_path, go.no_load, go.filename, go.site_name,
235 go.servlet_path);
236 }
237
238
239 public void init(String gsdl_path, String gsdl3_path, String gsdl3_src_path,
240 FedoraInfo fedora_info,
241 String local_library_path,
242 String library_url_string, String gliserver_url_string, boolean debug_enabled,
243 String perl_path, boolean no_load, String open_collection,
244 String site_name, String servlet_path)
245 {
246 if (gsdl3_path != null && !gsdl3_path.equals("")) {
247 this.GS3 = true;
248 } else {
249 gsdl3_path = null;
250 gsdl3_src_path = null;
251 }
252
253 // Create the debug stream if required
254 if (debug_enabled) {
255 DebugStream.enableDebugging();
256
257 Calendar now = Calendar.getInstance();
258 String debug_file_path = "debug" + now.get(Calendar.DATE) + "-" + now.get(Calendar.MONTH) + "-" + now.get(Calendar.YEAR) + ".txt";
259
260 // Debug file is created in the user's GLI directory
261 debug_file_path = getGLIUserDirectoryPath() + debug_file_path;
262 DebugStream.println("Debug file path: " + debug_file_path);
263 DebugStream.setDebugFile(debug_file_path);
264 DebugStream.print(System.getProperties());
265 }
266
267 // Delete plugins.dat and classifiers.dat files from previous versions of the GLI (no longer used)
268 File plugins_dat_file = new File(Gatherer.getGLIUserDirectoryPath() + "plugins.dat");
269 if (plugins_dat_file.exists()) {
270 System.err.println("Deleting plugins.dat file...");
271 Utility.delete(plugins_dat_file);
272 }
273 File classifiers_dat_file = new File(Gatherer.getGLIUserDirectoryPath() + "classifiers.dat");
274 if (classifiers_dat_file.exists()) {
275 System.err.println("Deleting classifiers.dat file...");
276 Utility.delete(classifiers_dat_file);
277 }
278
279 try {
280 // Load GLI config file
281 new Configuration(getGLIUserDirectoryPath(), gsdl_path, gsdl3_path, gsdl3_src_path, site_name,
282 fedora_info);
283
284 // Check we know where Perl is
285 Configuration.perl_path = perl_path;
286 if (isGsdlRemote && !isDownloadEnabled && Utility.isWindows() && Configuration.perl_path != null) {
287 if (Configuration.perl_path.toLowerCase().endsWith("perl.exe")) {
288 Configuration.perl_path = Configuration.perl_path.substring(0, Configuration.perl_path.length() - "perl.exe".length());
289 }
290 if (Configuration.perl_path.endsWith(File.separator)) {
291 Configuration.perl_path = Configuration.perl_path.substring(0, Configuration.perl_path.length() - File.separator.length());
292 }
293 }
294
295 // the feedback dialog has been loaded with a default locale,
296 // now set the user specified one
297 if (feedback_enabled && feedback_dialog != null) {
298 feedback_dialog.setLocale(Configuration.getLocale("general.locale", true));
299 }
300
301 // Read Dictionary
302 new Dictionary(Configuration.getLocale("general.locale", true), Configuration.getFont("general.font", true));
303
304 // check that we are using Sun Java
305 String java_vendor = System.getProperty("java.vendor");
306 if (!java_vendor.equals("Sun Microsystems Inc.")) {
307 System.err.println(Dictionary.get("General.NotSunJava", java_vendor));
308 }
309
310 // Unless we're using remote building, we need to know where the local Greenstone is
311 if (!isGsdlRemote && gsdl_path == null) {
312 missingGSDL();
313 }
314
315 if (fedora_info.isActive()) {
316 popupFedoraInfo();
317 }
318
319
320 open_collection_file_path = open_collection;
321 if (open_collection_file_path == null) {
322 open_collection_file_path = Configuration.getString(
323 "general.open_collection"+Configuration.gliPropertyNameSuffix(), true);
324 }
325 if (no_load || (isGsdlRemote && open_collection_file_path.equals(""))) {
326 open_collection_file_path = null;
327 // collectDirectoryHasChanged(); // make sure gsdlsite.cfg's collecthome defaults to GS' collect
328 }
329
330 // If opening a collection outside the standard GS collect folder, need
331 // to open the non-standard collect folder that the collection resides in
332 if (!isGsdlRemote
333 && open_collection_file_path != null
334 && !open_collection_file_path.startsWith(getDefaultGSCollectDirectoryPath(true)))
335 {
336 File collectFolder = null;
337
338 if(!open_collection_file_path.equals("")) {
339
340 if(!open_collection_file_path.endsWith("gli.col")) { // then it's a collect folder
341 collectFolder = new File(open_collection_file_path);
342 } else {
343 // the filepath is a gli.col file. To get the collect folder: the 1st level
344 // up is collection folder, 2 two levels up is the containing collect folder
345 collectFolder = new File(open_collection_file_path).getParentFile().getParentFile();
346 }
347
348 // Need to deal with colgroups as well: while there's an etc/collect.cfg in the current
349 // collectFolder, move one level up
350 String cfg_file = (Gatherer.GS3)? Utility.CONFIG_GS3_FILE : Utility.CONFIG_FILE;
351 if(new File(collectFolder.getAbsolutePath()+File.separator+cfg_file).exists()) { // colgroup
352 collectFolder = collectFolder.getParentFile();
353 }
354 }
355
356 if(collectFolder == null || !collectFolder.exists()) {
357 // if GLI config file specified no collectDir (open_collection_file_path is "")
358 // OR if dealing with a local server but the collectdir no longer exists,
359 // use the default greenstone collect directory, and write that to affected files
360
361 String defaultColDir = getDefaultGSCollectDirectoryPath(false); // no file separator at end
362 open_collection_file_path = defaultColDir;
363
364 setCollectDirectoryPath(defaultColDir); // will ensure the required file separator at end
365
366 Configuration.setString("general.open_collection"+Configuration.gliPropertyNameSuffix(),
367 true, "");
368
369 if(Gatherer.GS3) { // GS2's gsdlsite.cfg was taken care of when LocalLibraryServer was started up
370 // (LocalLibraryServer would also already have set glisite.cfg to the correct collecthome)
371 String gsdlsitecfg = Configuration.gsdl3_path + File.separator
372 + "WEB-INF" + File.separator + "cgi" + File.separator + "gsdl3site.cfg";
373 Utility.updatePropertyConfigFile(gsdlsitecfg, "collecthome", defaultColDir); // no file separator
374 // if gsdlsite.cfg does not exist (if using server.exe for instance), the above method will just return
375 }
376 } else { // remote GS, or collect dir exists (all config files will already be set since last GLI session)
377 if(collectFolder == null) {
378 setCollectDirectoryPath(getDefaultGSCollectDirectoryPath(false)); // no file separator at end
379 } else {
380 setCollectDirectoryPath(collectFolder.getAbsolutePath()); // now set this as the current collect folder
381 }
382 }
383 }
384
385 // Finally, we're ready to find out the version of the remote Greenstone server
386 if(isGsdlRemote) {
387 // instantiate the RemoteGreenstoneServer object first
388 remoteGreenstoneServer = new RemoteGreenstoneServer();
389
390 // Set up proxy
391 setProxy();
392 // Now we set up an Authenticator
393 Authenticator.setDefault(new GAuthenticator());
394
395 int greenstoneVersion = 2;
396 requestGLIServerURL();
397 gliserver_url_string = Configuration.gliserver_url.toString();
398
399 greenstoneVersion = remoteGreenstoneServer.getGreenstoneVersion();
400 // Display the version to make error reports a lot more useful
401 System.err.println("Remote Greenstone server version: " + greenstoneVersion);
402 if(greenstoneVersion == -1) { // remote server not running
403 Gatherer.exit();
404 }
405 if(greenstoneVersion >= 3) {
406 this.GS3 = true;
407 Configuration.prepareForGS3();
408 }
409
410 if(fedora_info.isActive()) {
411 // when GS server is remote, FEDORA_HOME resides on the remote server side,
412 // but we know the library URL from user-provided information
413 library_url_string = fedora_info.getLibraryURL();
414 } else {
415 library_url_string = remoteGreenstoneServer.getLibraryURL(Configuration.gliserver_url.toString());
416 }
417 // write it into the config file
418 Configuration.setString("general.library_url", true, library_url_string);
419 }
420 else { // local greenstone: Start up the local library server, if that's what we want
421 if (!GS3) {
422 isLocalLibrary = LocalLibraryServer.start(gsdl_path, local_library_path);
423 }
424 // else web library: GS server is local, but doesn't use the webserver included with GS2
425 }
426
427 // The "-library_url" option overwrites anything in the config files
428 if (library_url_string != null && library_url_string.length() > 0) {
429 try {
430 System.err.println("Setting library_url to " + library_url_string + "...");
431 Configuration.library_url = new URL(library_url_string);
432 }
433 catch (MalformedURLException error) {
434 DebugStream.printStackTrace(error);
435 }
436 }
437
438
439 // Check that we now know the Greenstone library URL, since we need this for previewing collections
440 // It is not necessary if an independent GSI was launched and the user hasn't pressed Enter Library yet
441 DebugStream.println("Configuration.library_url = " + Configuration.library_url);
442 if (Configuration.library_url == null) {
443 if(isLocalLibrary) {
444 if(!LocalLibraryServer.isURLPending()) {
445 missingEXEC();
446 }
447 // else LocalLibraryServer is expecting a URL soon, so don't need to display the dialog
448 } else { // GS2 webLibrary or GS3 or remote Greenstone
449 missingEXEC();
450 }
451 }
452
453 // The "-gliserver_url" option overwrites anything in the config files
454 if (gliserver_url_string != null && gliserver_url_string.length() > 0) {
455 try {
456 System.err.println("Setting gliserver_url to " + gliserver_url_string + "...");
457 Configuration.gliserver_url = new URL(gliserver_url_string);
458 }
459 catch (MalformedURLException error) {
460 DebugStream.printStackTrace(error);
461 }
462 }
463
464 // If we're using a remote Greenstone we need to know where the gliserver script is
465 DebugStream.println("Configuration.gliserver_url = " + Configuration.gliserver_url);
466
467 if (GS3) {
468 // Load Greenstone 3 servlet configuration
469 if (isGsdlRemote){
470 servlet_config = new ServletConfiguration(Configuration.gli_user_directory_path);
471 }else{
472 servlet_config= new ServletConfiguration(gsdl3_path);
473 }
474 }
475
476 if (GS3 && Configuration.servlet_path == null) {
477 Configuration.servlet_path = servlet_config.getServletPath(Configuration.site_name);
478 }
479
480 // ensure that a directory called 'cache' exists in the GLI user directory
481 File user_cache_dir = new File(Gatherer.getGLIUserCacheDirectoryPath());
482 System.err.println("User cache dir: " + Gatherer.getGLIUserCacheDirectoryPath());
483 if (!user_cache_dir.exists() && !user_cache_dir.mkdir()) {
484 System.err.println("Warning: Unable to make directory: " + user_cache_dir);
485 }
486
487 // Check for ImageMagick
488 if (Gatherer.isGsdlRemote) {
489 DebugStream.println("Not checking for ImageMagick.");
490 }
491 else if (!(new ImageMagickTest()).found()) {
492 // Time for a warning message
493 missingImageMagick();
494 }
495
496 if (Gatherer.isGsdlRemote) {
497 DebugStream.println("Not checking for perl path/exe");
498 }
499 else {
500 // Perl path is a little different as it is perfectly ok to
501 // start the GLI without providing a perl path
502 boolean found_perl = false;
503 if (Configuration.perl_path != null) {
504 // See if the file pointed to actually exists
505 File perl_file = new File(Configuration.perl_path);
506 found_perl = perl_file.exists();
507 perl_file = null;
508 }
509 if (Configuration.perl_path == null || !found_perl) {
510 // Run test to see if we can run perl as is.
511 PerlTest perl_test = new PerlTest();
512 if (perl_test.found()) {
513 // If so replace the perl path with the system
514 // default (or null for unix).
515 Configuration.perl_path = perl_test.toString();
516 found_perl = true;
517 }
518 }
519 if (!found_perl) {
520 // Time for an error message.
521 missingPERL();
522 }
523 }
524
525 // Set the default font for all Swing components.
526 FontUIResource default_font = Configuration.getFont("general.font", true);
527 Enumeration keys = UIManager.getDefaults().keys();
528 while (keys.hasMoreElements()) {
529 Object key = keys.nextElement();
530 Object value = UIManager.get(key);
531 if (value instanceof FontUIResource) {
532 UIManager.put(key, default_font);
533 }
534 }
535
536 // At this point (which is where this code originally used to be), we can set up the proxy for the
537 // non-remote case. The remote Greenstone server would already have setup its proxy when required.
538 if(!isGsdlRemote) {
539 setProxy();
540 // Now we set up an Authenticator
541 Authenticator.setDefault(new GAuthenticator());
542 }
543 assoc_man = new FileAssociationManager();
544 // Create File Manager
545 f_man = new FileManager();
546 // Create Collection Manager
547 c_man = new CollectionManager();
548 // Create Recycle Bin
549 recycle_bin = new RecycleBin();
550
551 if (GS3) {
552 if (site_name==null) {
553 site_name = Configuration.site_name;
554 servlet_path = null; // need to reset this
555 }
556 if (servlet_path == null) {
557 servlet_path = Configuration.getServletPath();
558 }
559 }
560
561
562 } catch (Exception exception) {
563 DebugStream.printStackTrace(exception);
564 }
565
566
567 // Create GUI Manager (last) or else suffer the death of a thousand NPE's
568 g_man = new GUIManager(size);
569
570 // Get a list of the core Greenstone classifiers and plugins
571 Classifiers.loadClassifiersList(null);
572 Plugins.loadPluginsList(null);
573
574 // If using a remote Greenstone we need to download the collection configurations now
575 if (Gatherer.isGsdlRemote) {
576 if (remoteGreenstoneServer.downloadCollectionConfigurations().equals("")) {
577 // !! Something went wrong downloading the collection configurations
578 System.err.println("Error: Could not download collection configurations.");
579 if(!Gatherer.isApplet) { // don't close the browser if it is an applet!
580 System.exit(0);
581 }
582 }
583 }
584 }
585
586
587 /** Returns the correct version of the (local or remote) Greenstone server if init() has already been called. */
588 public static int serverVersionNumber() {
589 return GS3 ? 3 : 2;
590 }
591
592 /** Returns "Server: version number" if init() has already been called. */
593 public static String getServerVersionAsString() {
594 return "Server: v" + serverVersionNumber();
595 }
596
597 public void openGUI()
598 {
599 // Size and place the frame on the screen
600 Rectangle bounds = Configuration.getBounds("general.bounds", true);
601 if (bounds == null) {
602 // Choose a sensible default value
603 bounds = new Rectangle(0, 0, 640, 480);
604 }
605
606 // Ensure width and height are reasonable
607 size = bounds.getSize();
608 if (size.width < 640) {
609 size.width = 640;
610 }
611 else if (size.width > Configuration.screen_size.width && Configuration.screen_size.width > 0) {
612 size.width = Configuration.screen_size.width;
613 }
614 if (size.height < 480) {
615 size.height = 480;
616 }
617 else if (size.height > Configuration.screen_size.height && Configuration.screen_size.height > 0) {
618 size.height = Configuration.screen_size.height;
619 }
620
621 if (!g_man_built) {
622
623 g_man.display();
624
625 // 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).
626 g_man.setLocation(bounds.x, bounds.y);
627 g_man.setVisible(true);
628
629 // After the window has been made visible, check that it is in the correct place
630 // sometimes java places a window not in the correct place,
631 // but with an offset. If so, we work out what the offset is
632 // and change the desired location to take that into account
633 Point location = g_man.getLocation();
634 int x_offset = bounds.x - location.x;
635 int y_offset = bounds.y - location.y;
636 // If not, offset the window to move it into the correct location
637 if (x_offset > 0 || y_offset > 0) {
638 ///ystem.err.println("changing the location to "+(bounds.x + x_offset)+" "+ (bounds.y + y_offset));
639 g_man.setLocation(bounds.x + x_offset, bounds.y + y_offset);
640 }
641
642 // 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.
643 g_man.afterDisplay();
644 g_man_built = true;
645 }
646 else {
647 g_man.setVisible(true);
648 }
649
650 // Get a list of the core Greenstone classifiers and plugins
651 /*Classifiers.loadClassifiersList(null);
652 Plugins.loadPluginsList(null);
653
654 // If using a remote Greenstone we need to download the collection configurations now
655 if (Gatherer.isGsdlRemote) {
656 if (remoteGreenstoneServer.downloadCollectionConfigurations().equals("")) {
657 // !! Something went wrong downloading the collection configurations
658 System.err.println("Error: Could not download collection configurations.");
659 System.exit(0);
660 }
661 }*/
662
663 // If there was a collection left open last time, reopen it
664 if (open_collection_file_path == null || new File(Gatherer.open_collection_file_path).isDirectory()) {
665
666 //the menu bar items, file and edit, are disabled from the moment of their creation. if there is no left-over collection from the last session, enable them; otherwise it is untill the collection finishes loading, will they be enabled in collectionManager.java
667 setMenuBarEnabled(true);
668 } else {
669
670 // If there was a collection left open last time, reopen it
671 c_man.openCollectionFromLastTime();
672 }
673 }
674
675 public static void setMenuBarEnabled(boolean enabled) {
676 g_man.menu_bar.file.setEnabled(enabled);
677 g_man.menu_bar.edit.setEnabled(enabled);
678 }
679
680 /** Exits the Gatherer after ensuring that things needing saving are saved.
681 * @see java.io.FileOutputStream
682 * @see java.io.PrintStream
683 * @see java.lang.Exception
684 * @see javax.swing.JOptionPane
685 * @see org.greenstone.gatherer.Configuration
686 * @see org.greenstone.gatherer.collection.CollectionManager
687 * @see org.greenstone.gatherer.gui.GUIManager
688 */
689 static public void exit(int new_exit_status)
690 {
691 DebugStream.println("In Gatherer.exit()...");
692 exit = true;
693 if (new_exit_status != 0) {
694 // default exit_status is already 0
695 // only remember a new exit status if it is non-trivial
696 exit_status = new_exit_status;
697 }
698
699 // Save the file associations
700 if (assoc_man != null) {
701 assoc_man.save();
702 assoc_man = null;
703 }
704
705 // Get the gui to deallocate
706 if(g_man != null) {
707 g_man.destroy();
708 g_man_built = false;
709 }
710
711 // Flush debug
712 DebugStream.closeDebugStream();
713
714 // If we started a server, we should try to stop it.
715 if (LocalLibraryServer.isRunning() == true) {
716 LocalLibraryServer.stop();
717 }
718
719 // If we're using a remote Greenstone server we need to make sure that all jobs have completed first
720 if (isGsdlRemote) {
721 remoteGreenstoneServer.exit();
722 }
723
724 // Make sure we haven't started up any processes that are still running
725 if (apps.size() == 0) {
726 // If we're running as an applet we don't actually quit (just hide the main GLI window)
727 if (!Gatherer.isApplet) {
728 // This is the end...
729 System.exit(exit_status);
730 }
731 }
732 else {
733 JOptionPane.showMessageDialog(g_man, Dictionary.get("General.Outstanding_Processes"), Dictionary.get("General.Outstanding_Processes_Title"), JOptionPane.ERROR_MESSAGE);
734 g_man.setVisible(false);
735 }
736 }
737
738 static public void exit()
739 {
740 exit(0);
741 }
742
743 /** Returns the path of the current collect directory. */
744 static public String getCollectDirectoryPath()
745 {
746 if (non_standard_collect_directory_path != null) {
747 return non_standard_collect_directory_path;
748 }
749
750 return getDefaultGSCollectDirectoryPath(true); // file separator appended
751
752 }
753
754 /** Returns the path of the Greenstone "collect" directory. */
755 static public String getDefaultGSCollectDirectoryPath(boolean appendSeparator) {
756 String colDir;
757 if (GS3) {
758 colDir = getSitesDirectoryPath() + Configuration.site_name + File.separator + "collect";
759 }
760 else {
761 colDir = Configuration.gsdl_path + "collect";
762 }
763
764 if(appendSeparator) {
765 colDir += File.separator;
766 }
767 return colDir;
768 }
769
770 /** Returns the path of the GLI directory. */
771 static public String getGLIDirectoryPath()
772 {
773 return gli_directory_path;
774 }
775
776
777 /** Returns the path of the GLI "metadata" directory. */
778 static public String getGLIMetadataDirectoryPath()
779 {
780 return getGLIDirectoryPath() + "metadata" + File.separator;
781 }
782
783
784 /** Returns the path of the GLI user directory. */
785 static public String getGLIUserDirectoryPath()
786 {
787 return gli_user_directory_path;
788 }
789
790
791 /** Returns the path of the GLI user "cache" directory. */
792 static public String getGLIUserCacheDirectoryPath()
793 {
794 return getGLIUserDirectoryPath() + "cache" + File.separator;
795 }
796
797
798 /** Returns the path of the GLI user "log" directory. */
799 static public String getGLIUserLogDirectoryPath()
800 {
801 return getGLIUserDirectoryPath() + "log" + File.separator;
802 }
803
804
805 static public String getSitesDirectoryPath()
806 {
807 return Configuration.gsdl3_path + "sites" + File.separator;
808 }
809
810
811 static public void setCollectDirectoryPath(String collect_directory_path)
812 {
813 non_standard_collect_directory_path = collect_directory_path;
814 if (!non_standard_collect_directory_path.endsWith(File.separator)) {
815 non_standard_collect_directory_path = non_standard_collect_directory_path + File.separator;
816 }
817 }
818
819
820 static public void setGLIDirectoryPath(String gli_directory_path_arg)
821 {
822 gli_directory_path = gli_directory_path_arg;
823 }
824
825
826 static public void setGLIUserDirectoryPath(String gli_user_directory_path_arg)
827 {
828 gli_user_directory_path = gli_user_directory_path_arg;
829
830 // Ensure the GLI user directory exists
831 File gli_user_directory = new File(gli_user_directory_path);
832 if (!gli_user_directory.exists() && !gli_user_directory.mkdirs()) {
833 System.err.println("Error: Unable to make directory: " + gli_user_directory);
834 }
835 }
836
837
838 public static void collectDirectoryHasChanged(
839 String oldCollectPath, String newCollectPath, final Component container)
840 {
841 if(oldCollectPath.equals(newCollectPath)) {
842 return; // nothing to be done
843 }
844
845 // Will use a busy cursor if the process of changing the collect directory takes more
846 // than half a second/500ms. See http://www.catalysoft.com/articles/busyCursor.html
847 Cursor originalCursor = container.getCursor();
848 java.util.TimerTask timerTask = new java.util.TimerTask() {
849 public void run() {
850 // set the cursor on the container:
851 container.setCursor(new Cursor(Cursor.WAIT_CURSOR));
852 }
853 };
854 java.util.Timer timer = new java.util.Timer();
855
856 try {
857 timer.schedule(timerTask, 500);
858
859 // first save any open collection in the old location, then close it
860 if(Gatherer.c_man.getCollection() != null) {
861 Gatherer.g_man.saveThenCloseCurrentCollection(); // close the current collection first
862 }
863
864 // change to new collect path
865 if(newCollectPath.equals(getDefaultGSCollectDirectoryPath(true))) {
866 Configuration.setString("general.open_collection"+Configuration.gliPropertyNameSuffix(),
867 true, "");
868 } else {
869 Configuration.setString("general.open_collection"+Configuration.gliPropertyNameSuffix(),
870 true, newCollectPath);
871 }
872 Gatherer.setCollectDirectoryPath(newCollectPath);
873
874
875 // refresh the Documents in Greenstone Collections
876 //WorkspaceTreeModel.refreshGreenstoneCollectionsNode();
877 Gatherer.g_man.refreshWorkspaceTreeGreenstoneCollections();
878
879 // The web server needs to be told where a new (non-standard) collecthome home is.
880 // The web server reads collecthome from cgi-bin/gsdlsite.cfg, where the property
881 // collecthome can be specified if a non-standard collecthome is to be used. If no
882 // such property is specified in the file, then it assumes the standard GS collecthome.
883 // This method does nothing for a remote Greenstone.
884 if(Gatherer.isGsdlRemote) {
885 return;
886 }
887
888 String gsdlsitecfg = "";
889 if(Gatherer.GS3) { // web/WEB-INF/cgi/gsdl3site.cfg
890 gsdlsitecfg = Configuration.gsdl3_path + File.separator + "WEB-INF"
891 + File.separator + "cgi" + File.separator + "gsdl3site.cfg";
892 } else { // cgi-bin/gsdlsite.cfg
893 gsdlsitecfg = Configuration.gsdl_path + File.separator
894 + "cgi-bin" + File.separator + "gsdlsite.cfg";
895 }
896
897 // non-destructive update of gsdl(3)site.cfg (comments preserved)
898 String collectDir = Gatherer.getCollectDirectoryPath();
899 //collectDir = "\"" + collectDir.substring(0, collectDir.length()-1) + "\""; // remove file separator at end
900 collectDir = collectDir.substring(0, collectDir.length()-1); // remove file separator at end
901 Utility.updatePropertyConfigFile(gsdlsitecfg, "collecthome", collectDir);
902 // if gsdlsite.cfg does not exist (if using server.exe for instance), the above method will just return
903
904 if(!Gatherer.GS3 && Gatherer.isLocalLibrary) {
905 // for Images in the collection to work, the apache web server
906 // configuration's COLLECTHOME should be updated on collectdir change.
907 // Does nothing for server.exe at the moment
908
909 LocalLibraryServer.reconfigure();
910 }
911 } finally { // Note try-finally section without catch:
912 // "Java's finally clause is guaranteed to be executed even when
913 // an exception is thrown and not caught in the current scope."
914 // See http://www.catalysoft.com/articles/busyCursor.html
915 // the following code fragment is guaranteed to restore the original
916 // cursor now the custom actionPerformed() processing is complete, regardless
917 // of whether the processing method terminates normally or throws an exception
918 // and regardedless of where in the call stack the exception is caught.
919
920 timer.cancel();
921 container.setCursor(originalCursor);
922 }
923 }
924
925
926 static public void refresh(int refresh_reason)
927 {
928 if (g_man != null) {
929
930 g_man.refresh(refresh_reason, c_man.ready());
931 }
932
933 // Now is a good time to force a garbage collect
934 System.gc();
935 }
936
937
938 // used to send reload coll messages to the tomcat server
939 static public void configGS3Server(String site, String command) {
940 if (Configuration.library_url == null){
941 System.out.println("Error: you have not provided the Greenstone Library address.");
942 return;
943
944 }
945
946 try {
947 // need to add the servlet name to the exec address
948 String raw_url = Configuration.library_url.toString() + Configuration.getServletPath() + command;
949 URL url = new URL(raw_url);
950 DebugStream.println("Action: " + raw_url);
951 HttpURLConnection library_connection = (HttpURLConnection) url.openConnection();
952 int response_code = library_connection.getResponseCode();
953 if(HttpURLConnection.HTTP_OK <= response_code && response_code < HttpURLConnection.HTTP_MULT_CHOICE) {
954 DebugStream.println("200 - Complete.");
955 }
956 else {
957 DebugStream.println("404 - Failed.");
958 }
959 url = null;
960 }
961 catch(java.net.ConnectException connectException) {
962 JOptionPane.showMessageDialog(g_man, Dictionary.get("Preferences.Connection.Library_Path_Connection_Failure", Configuration.library_url.toString()), Dictionary.get("General.Warning"), JOptionPane.WARNING_MESSAGE);
963 DebugStream.println(connectException.getMessage());
964 }
965 catch (Exception exception) {
966 DebugStream.printStackTrace(exception);
967 }
968 }
969
970
971 /** Used to 'spawn' a new child application when a file is double clicked.
972 * @param file The file to open
973 * @see org.greenstone.gatherer.Gatherer.ExternalApplication
974 */
975 static public void spawnApplication(File file) {
976 String [] commands = assoc_man.getCommand(file);
977 if(commands != null) {
978 ExternalApplication app = new ExternalApplication(commands);
979 apps.add(app);
980 app.start();
981 }
982 else {
983 ///ystem.err.println("No open command available.");
984 }
985 }
986
987
988 static public void spawnApplication(String command)
989 {
990 ExternalApplication app = new ExternalApplication(command);
991 apps.add(app);
992 app.start();
993 }
994
995 static public void spawnApplication(String command, String ID)
996 {
997 ExternalApplication app = new ExternalApplication(command, ID);
998 apps.add(app);
999 app.start();
1000 }
1001
1002 static public void spawnApplication(String[] commands, String ID)
1003 {
1004 ExternalApplication app = new ExternalApplication(commands, ID);
1005 apps.add(app);
1006 app.start();
1007 }
1008
1009 static public void terminateApplication(String ID) {
1010 for(int i = 0; i < apps.size(); i++) {
1011 ExternalApplication app = (ExternalApplication)apps.get(i);
1012 if(app.getID() != null && app.getID().equals(ID)) {
1013 app.stopExternalApplication();
1014 apps.remove(app);
1015 }
1016 }
1017 }
1018
1019
1020 /** Used to 'spawn' a new browser application or reset an existing one when the preview button is clicked
1021 * @param url The url to open the browser at
1022 * @see org.greenstone.gatherer.Gatherer.BrowserApplication
1023 */
1024 static public void spawnBrowser(String url) {
1025 String command = assoc_man.getBrowserCommand(url);
1026 if (command != null) {
1027 BrowserApplication app = new BrowserApplication(command, url);
1028 apps.add(app);
1029 app.start();
1030 }
1031 else {
1032 ///ystem.err.println("No browser command available.");
1033 }
1034 }
1035
1036
1037 /** Prints a warning message about a missing library path, which means the final collection cannot be previewed in the Gatherer.
1038 */
1039 static public void missingEXEC() {
1040 WarningDialog dialog;
1041 String configPropertyName = "general.library_url"+Configuration.gliPropertyNameSuffix();
1042
1043 if (GS3) {
1044 // Warning dialog with no cancel button and no "turn off warning" checkbox
1045 dialog = new WarningDialog("warning.MissingEXEC", Dictionary.get("MissingEXEC_GS3.Title"), Dictionary.get("MissingEXEC_GS3.Message"), configPropertyName, false, false);
1046 } else { // local case
1047 dialog = new WarningDialog("warning.MissingEXEC", Dictionary.get("MissingEXEC.Title"), Dictionary.get("MissingEXEC.Message"), configPropertyName, false);
1048 }
1049
1050 JTextField field = new URLField.Text(Configuration.getColor("coloring.editable_foreground", false), Configuration.getColor("coloring.editable_background", false));
1051
1052 // Set the default library URL to the tomcat server and port number
1053 // specified in the build.properties located in the gsdl3_src_path
1054 if (GS3) {
1055 String host = "localhost";
1056 String port = "8080";
1057
1058 File buildPropsFile = new File(Configuration.gsdl3_src_path + File.separator + "build.properties");
1059 if(buildPropsFile.exists()) {
1060 Properties props = new Properties();
1061 try{
1062 props.load(new FileInputStream(buildPropsFile));
1063 host = props.getProperty("tomcat.server", host);
1064 port = props.getProperty("tomcat.port", port);
1065 }catch(Exception e){
1066 DebugStream.println("Could not load build.properties file");
1067 System.err.println("Could not load build.properties file");
1068 }
1069 props = null;
1070 }
1071 String defaultURL = "http://"+host+":"+port+"/"+"greenstone3";
1072 field.setText(defaultURL);
1073 field.selectAll();
1074 }
1075 dialog.setValueField(field);
1076 dialog.display();
1077 dialog.dispose();
1078 dialog = null;
1079
1080 String library_url_string = Configuration.getString(configPropertyName, true);
1081 if (!library_url_string.equals("")) {
1082 try {
1083 // WarningDialog does not allow invalid URLs, so the following is ignored:
1084 // make sure the URL the user provided contains the http:// prefix
1085 // and then save the corrected URL
1086 if(!library_url_string.startsWith("http://")
1087 && !library_url_string.startsWith("https://")) {
1088 library_url_string = "http://"+library_url_string;
1089 Configuration.setString(configPropertyName, true, configPropertyName);
1090 }
1091 Configuration.library_url = new URL(library_url_string);
1092 }
1093 catch (MalformedURLException exception) {
1094 DebugStream.printStackTrace(exception);
1095 }
1096 }
1097 }
1098
1099
1100
1101 /** Prints a warning message about a missing library path, which means the final collection cannot be previewed in the Gatherer.
1102 */
1103 static private void popupFedoraInfo() {
1104
1105 FedoraLogin dialog = new FedoraLogin("Fedora Login", false);
1106
1107 if (Configuration.library_url == null) {
1108
1109 String library_url_string = dialog.getLibraryURL();
1110 if (!library_url_string.equals("")) {
1111 try {
1112 Configuration.library_url = new URL(library_url_string);
1113 }
1114 catch (MalformedURLException exception) {
1115 DebugStream.printStackTrace(exception);
1116 }
1117 }
1118 }
1119
1120 boolean showLogin = true;
1121 do {
1122 if(!dialog.loginRequested()) { // user pressed cancel to exit the FedoraLogin dialog
1123 System.exit(0);
1124 } else {
1125 showLogin = dialog.loginRequested();
1126 String hostname = dialog.getHostname();
1127 String port = dialog.getPort();
1128 String username = dialog.getUsername();
1129 String password = dialog.getPassword();
1130 String protocol = dialog.getProtocol();
1131
1132 Configuration.fedora_info.setHostname(hostname);
1133 Configuration.fedora_info.setPort(port);
1134 Configuration.fedora_info.setUsername(username);
1135 Configuration.fedora_info.setPassword(password);
1136 Configuration.fedora_info.setProtocol(protocol);
1137
1138 String ping_url_str = protocol + "://" + hostname + ":" + port + "/fedora";
1139 String login_str = username + ":" + password;
1140
1141 String login_encoding = Base64.encodeBytes(login_str.getBytes());
1142
1143 try {
1144 URL ping_url = new URL(ping_url_str);
1145 URLConnection uc = ping_url.openConnection();
1146 uc.setRequestProperty ("Authorization", "Basic " + login_encoding);
1147 // Attempt to access some content ...
1148 InputStream content = (InputStream)uc.getInputStream();
1149
1150 // if no exception occurred in the above, we would have come here:
1151 showLogin = false;
1152 dialog.dispose();
1153 }
1154 catch (Exception exception) {
1155 // TODO: move into dictionary
1156 String[] errorMessage = {"Failed to connect to the Fedora server.", "It might not be running, or",
1157 "incorrect username and/or password."};
1158 dialog.setErrorMessage(errorMessage);
1159 //DebugStream.printStackTrace(exception);
1160 // exception occurred, show the dialog again (do this after printing to
1161 // debugStream, else the above does not get done for some reason).
1162 dialog.setVisible(true);
1163 }
1164 }
1165 } while(showLogin);
1166
1167 dialog = null; // no more need of the dialog
1168
1169 // Now we are connected.
1170 }
1171
1172
1173
1174 static private void requestGLIServerURL()
1175 {
1176 WarningDialog dialog;
1177 String[] defaultURLs = {
1178 "http://localhost:8080/greenstone3/cgi-bin/gliserver.pl",
1179 "http://localhost:8080/gsdl/cgi-bin/gliserver.pl"
1180 };
1181
1182 // Warning dialog with no cancel button and no "turn off warning" checkbox
1183 // (since user-input of the gliserver script is mandatory)
1184 dialog = new WarningDialog("warning.MissingGLIServer", Dictionary.get("MissingGLIServer.Title"), Dictionary.get("MissingGLIServer.Message"), "general.gliserver_url", false, false);
1185
1186 dialog.setValueField(new URLField.DropDown(Configuration.getColor("coloring.editable_foreground", false),
1187 Configuration.getColor("coloring.editable_background", false),
1188 defaultURLs, "general.gliserver_url",
1189 "general.open_collection"+Configuration.gliPropertyNameSuffix(),
1190 "gliserver.pl"));
1191
1192 if (Gatherer.default_gliserver_url!=null){
1193 dialog.setValueField(Gatherer.default_gliserver_url.toString());
1194 }
1195
1196 // A WarningDialog cannot always be made to respond (let alone to exit the program) on close. We
1197 // handle the response of this particular WarningDialog here: a URL for gliserver.pl is a crucial
1198 // piece of user-provided data. Therefore, if no URL was entered for gliserver.pl, it'll exit safely.
1199 dialog.addWindowListener(new WindowAdapter() {
1200 public void windowClosing(WindowEvent e) {
1201 Gatherer.exit();
1202 }
1203 });
1204
1205 dialog.display();
1206 dialog.dispose();
1207 dialog = null;
1208
1209
1210 String gliserver_url_string = Configuration.getString("general.gliserver_url", true);
1211 if (!gliserver_url_string.equals("")) {
1212 try {
1213 Configuration.gliserver_url = new URL(gliserver_url_string);
1214 Configuration.setString("general.gliserver_url", true, gliserver_url_string);
1215 }
1216 catch (MalformedURLException exception) {
1217 DebugStream.printStackTrace(exception);
1218 }
1219 }
1220 }
1221
1222
1223 /** Prints a warning message about a missing GSDL path, which although not fatal pretty much ensures nothing will work properly in the GLI.
1224 */
1225 static private void missingGSDL() {
1226 WarningDialog dialog = new WarningDialog("warning.MissingGSDL", Dictionary.get("MissingGSDL.Title"), Dictionary.get("MissingGSDL.Message"), null, false);
1227 dialog.display();
1228 dialog.dispose();
1229 dialog = null;
1230 }
1231
1232 /** Prints a warning message about missing a valid ImageMagick path, which although not fatal means building image collections won't work */
1233 static private void missingImageMagick() {
1234 WarningDialog dialog = new WarningDialog("warning.MissingImageMagick", Dictionary.get("MissingImageMagick.Title"), Dictionary.get("MissingImageMagick.Message"), null, false);
1235 dialog.display();
1236 dialog.dispose();
1237 dialog = null;
1238 }
1239
1240 /** Prints a warning message about missing a valid PERL path, which although not fatal pretty much ensures no collection creation/building will work properly in the GLI. */
1241 static private void missingPERL() {
1242 WarningDialog dialog = new WarningDialog("warning.MissingPERL", Dictionary.get("MissingPERL.Title"), Dictionary.get("MissingPERL.Message"), null, false);
1243 dialog.display();
1244 dialog.dispose();
1245 dialog = null;
1246 }
1247
1248
1249 /** Sets up the proxy connection by setting JVM Environment flags and creating a new Authenticator.
1250 * @see java.lang.Exception
1251 * @see java.lang.System
1252 * @see java.net.Authenticator
1253 * @see org.greenstone.gatherer.Configuration
1254 * @see org.greenstone.gatherer.GAuthenticator
1255 */
1256 static public void setProxy() {
1257 try {// Can throw several exceptions
1258 if(Configuration.get("general.use_proxy", true)) {
1259 System.setProperty("http.proxyType", "4");
1260 System.setProperty("http.proxyHost", Configuration.getString("general.proxy_host", true));
1261 System.setProperty("http.proxyPort", Configuration.getString("general.proxy_port", true));
1262 System.setProperty("http.proxySet", "true");
1263 } else {
1264 System.setProperty("http.proxyHost", "");
1265 System.setProperty("http.proxyPort", "");
1266 System.setProperty("http.proxySet", "false");
1267 }
1268 } catch (Exception error) {
1269 DebugStream.println("Error in Gatherer.initProxy(): " + error);
1270 DebugStream.printStackTrace(error);
1271 }
1272 }
1273
1274
1275 /** 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. */
1276 static private class ExternalApplication
1277 extends Thread {
1278 private Process process = null;
1279 /** The initial command string given to this sub-process. */
1280 private String command = null;
1281 private String[] commands = null;
1282
1283 private String ID = null;
1284
1285 /** Constructor.
1286 * @param command The initial command <strong>String</strong>.
1287 */
1288 public ExternalApplication(String command) {
1289 this.command = command;
1290 }
1291
1292 public ExternalApplication(String[] commands) {
1293 this.commands = commands;
1294 }
1295
1296 public ExternalApplication(String command, String ID) {
1297 this.command = command;
1298 this.ID = ID;
1299 }
1300
1301 public ExternalApplication(String[] commands, String ID) {
1302 this.commands = commands;
1303 this.ID = ID;
1304 }
1305
1306 public String getID() {
1307 return ID;
1308 }
1309
1310 /** We start the child process inside a new thread so it doesn't block the rest of Gatherer.
1311 * @see java.lang.Exception
1312 * @see java.lang.Process
1313 * @see java.lang.Runtime
1314 * @see java.lang.System
1315 * @see java.util.Vector
1316 */
1317 public void run() {
1318 // Call an external process using the args.
1319 try {
1320 if(commands != null) {
1321 StringBuffer whole_command = new StringBuffer();
1322 for(int i = 0; i < commands.length; i++) {
1323 whole_command.append(commands[i]);
1324 whole_command.append(" ");
1325 }
1326 DebugStream.println("Running " + whole_command.toString());
1327 Runtime rt = Runtime.getRuntime();
1328 process = rt.exec(commands);
1329 process.waitFor();
1330 }
1331 else {
1332 DebugStream.println("Running " + command);
1333 Runtime rt = Runtime.getRuntime();
1334 process = rt.exec(command);
1335 process.waitFor();
1336 }
1337 }
1338 catch (Exception exception) {
1339 DebugStream.printStackTrace(exception);
1340 }
1341 // Remove ourself from Gatherer list of threads.
1342 apps.remove(this);
1343 // Call exit if we were the last outstanding child process thread.
1344 if (apps.size() == 0 && exit == true) {
1345 // In my opinion (DB) there is no need to exit here,
1346 // the 'run' method ending naturally brings this
1347 // thread to an end. In fact it is potentially
1348 // dangerous to exit here, as the main thread in the
1349 // Gatherer class may be stopped prematurely. As it so
1350 // happens the point at which the ExternalApplication thread
1351 // is asked to stop (Back in the main Gatherer thread) is after
1352 // various configuration files have been saved.
1353 //
1354 // A similar argument holds for BrowserApplication thread below.
1355 System.exit(exit_status);
1356 }
1357 }
1358 public void stopExternalApplication() {
1359 if(process != null) {
1360 process.destroy();
1361 }
1362 }
1363 }
1364 /** 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. */
1365 static private class BrowserApplication
1366 extends Thread {
1367 private Process process = null;
1368 /** The initial command string given to this sub-process. */
1369 private String command = null;
1370 private String url = null;
1371 private String[] commands = null;
1372
1373 public BrowserApplication(String command, String url) {
1374 StringTokenizer st = new StringTokenizer(command);
1375 int num_tokens = st.countTokens();
1376 this.commands = new String [num_tokens];
1377 int i=0;
1378 while (st.hasMoreTokens()) {
1379 commands[i] = st.nextToken();
1380 i++;
1381 }
1382 //this.commands = commands;
1383 this.url = url;
1384 }
1385 /** We start the child process inside a new thread so it doesn't block the rest of Gatherer.
1386 * @see java.lang.Exception
1387 * @see java.lang.Process
1388 * @see java.lang.Runtime
1389 * @see java.lang.System
1390 * @see java.util.Vector
1391 */
1392 public void run() {
1393 // Call an external process using the args.
1394 if(commands == null) {
1395 apps.remove(this);
1396 return;
1397 }
1398 try {
1399 String prog_name = commands[0];
1400 String lower_name = prog_name.toLowerCase();
1401 if (lower_name.indexOf("mozilla") != -1 || lower_name.indexOf("netscape") != -1) {
1402 DebugStream.println("found mozilla or netscape, trying remote it");
1403 // mozilla and netscape, try using a remote command to get things in the same window
1404 String [] new_commands = new String[] {prog_name, "-raise", "-remote", "openURL("+url+",new-tab)"};
1405 printArray(new_commands);
1406
1407 Runtime rt = Runtime.getRuntime();
1408 process = rt.exec(new_commands);
1409 int exitCode = process.waitFor();
1410 if (exitCode != 0) { // if Netscape or mozilla was not open
1411 DebugStream.println("couldn't do remote, trying original command");
1412 printArray(commands);
1413 process = rt.exec(commands); // try the original command
1414 }
1415 } else {
1416 // just run what we have been given
1417 StringBuffer whole_command = new StringBuffer();
1418 for(int i = 0; i < commands.length; i++) {
1419 whole_command.append(commands[i]);
1420 whole_command.append(" ");
1421 }
1422 DebugStream.println("Running " + whole_command.toString());
1423 Runtime rt = Runtime.getRuntime();
1424 process = rt.exec(commands);
1425 process.waitFor();
1426 }
1427 }
1428
1429 catch (Exception exception) {
1430 DebugStream.printStackTrace(exception);
1431 }
1432 // Remove ourself from Gatherer list of threads.
1433 apps.remove(this);
1434 // Call exit if we were the last outstanding child process thread.
1435 if (apps.size() == 0 && exit == true) {
1436 System.exit(exit_status);
1437 }
1438 }
1439 public void printArray(String [] array) {
1440 for(int i = 0; i < array.length; i++) {
1441 DebugStream.print(array[i]+" ");
1442 System.err.println(array[i]+" ");
1443 }
1444 }
1445 public void stopBrowserApplication() {
1446 if(process != null) {
1447 process.destroy();
1448 }
1449 }
1450 }
1451
1452
1453 private class ImageMagickTest
1454 {
1455 public boolean found()
1456 {
1457 try {
1458 String[] command = new String[2];
1459 command[0] = (Utility.isWindows() ? "identify.exe" : "identify");
1460 command[1] = "-version";
1461 Process image_magick_process = Runtime.getRuntime().exec(command);
1462 image_magick_process.waitFor();
1463
1464 //new way of detection of ImageMagick
1465 InputStreamReader isr = new InputStreamReader(image_magick_process.getInputStream());
1466
1467 BufferedReader br = new BufferedReader(isr);
1468 // Capture the standard output stream and seach for two particular occurances: Version and ImageMagick.
1469
1470 String line = br.readLine();
1471 if (line == null) {
1472 return false;
1473 }
1474 String lc_line = line.toLowerCase();
1475 if (lc_line.indexOf("version") != -1 || lc_line.indexOf("imagemagick") != -1) {
1476 return true;
1477 } else {
1478 return false;
1479 }
1480
1481 //return (image_magick_process.exitValue() == 0);
1482 }
1483 catch (IOException exception) {
1484 return false;
1485 }
1486 catch (InterruptedException exception) {
1487 return false;
1488 }
1489 }
1490 }
1491
1492
1493 private class PerlTest
1494 {
1495 private String[] command = new String[2];
1496
1497 public PerlTest()
1498 {
1499 command[0] = (Utility.isWindows() ? Utility.PERL_EXECUTABLE_WINDOWS : Utility.PERL_EXECUTABLE_UNIX);
1500 command[1] = "-version";
1501 }
1502
1503 public boolean found()
1504 {
1505 try {
1506 Process perl_process = Runtime.getRuntime().exec(command);
1507 perl_process.waitFor();
1508 return (perl_process.exitValue() == 0);
1509 }
1510 catch (Exception exception) {
1511 return false;
1512 }
1513 }
1514
1515 public String toString() {
1516 return command[0];
1517 }
1518 }
1519}
Note: See TracBrowser for help on using the repository browser.