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

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

Again for ticket 152 (moveable collectdir). If the default GS collectdir is the one active in GLI (but all collections are closed) when exiting GLI, this default GS collectdir is not stored in config.xml (in the User Data location). Instead of the last opened collection or last open collectdir, an empty value is written out in the case of the default GS collectdir. This will allow other GS installations to open in their own collectdir. The benefits do not extend to if a collection in another GS' default collectdir was left open. In that case, the collection path is written out to the config.xml file, and the collectdir that a different GLI loads will be the old GLI's collect dir.

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