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

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

Changing the EventListeners list in GShell over to be CopyOnWriteArrayList because it is threadsafe, as is needed here, though the change comes at the expense of reduced efficiency. Also removed Imagemagick test debug statements in Gatherer.

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