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

Last change on this file since 23662 was 23662, checked in by ak19, 13 years ago

Renamed warning message and title for for NoEncodingSupport

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