source: debug-testing/gli-ctrlC-issue/Gatherer.java

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

Creating a folder to add files that are in a convenient state for debugging problems we haven't resolved yet. And adding files for debugging the issue of launching GLI from DOS, but Ctrl-C being ineffective until you exit GLI, which is when the Ctrl-C finally registers.

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