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

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

Fourth set of commits to do with the migration of cgi-bin into common-src, so that upon make install, common-src\cgi-bin will be installed in cgi-bin\GSDLOS(GSDLARCH). The first commit was of changes to files in cgi-bin itself. The second commit was moving cgi-bin. The third one involves changes to all the files in GS2 referring to cgi-bin where this needs to be changed to cgi-bin\OS_and_ARCH. This final change is to affected references to cgi-bin in GLI.

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