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

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

First phase of shifting gli code to use SafeProcess instead of Java Process. This phase takes care of all the easy cases.

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