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

Last change on this file since 24294 was 24294, checked in by ak19, 13 years ago

If the user has a non-standard collecthome (collecthome is not in the default location of the GS installation) a message appears informing the user of this at startup.

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