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

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

For ticket 152 (moveable collectdir): busy cursor when changing a collectdir takes some time to finish.

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