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

Last change on this file since 31813 was 31813, checked in by ak19, 7 years ago

Adding shutdownhook for GS2 to ensure the GS2 server is stopped on Ctrl-C. Tested on Linux.

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