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

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

Combining the shutdown hooks for GS2 and GS3

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