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

Last change on this file since 28628 was 26331, checked in by ak19, 12 years ago

If local GS3 with a fedora installed as a webapp in GS3's tomcat packages, then we ask for fedora login details after starting up the local tomcat server.

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