source: main/trunk/gli/src/org/greenstone/gatherer/greenstone/LocalLibraryServer.java@ 31813

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

Adding shutdownhook for GS2 to ensure the GS2 server is stopped on Ctrl-C. Tested on Linux.

  • Property svn:keywords set to Author Date Id Revision
File size: 36.8 KB
Line 
1/**
2 *############################################################################
3 * A component of the Greenstone Librarian Interface, part of the Greenstone
4 * digital library suite from the New Zealand Digital Library Project at the
5 * University of Waikato, New Zealand.
6 *
7 * Author: Michael Dewsnip, NZDL Project, University of Waikato, NZ
8 *
9 * Copyright (C) 2004 New Zealand Digital Library Project
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 *############################################################################
25 */
26
27package org.greenstone.gatherer.greenstone;
28
29
30import java.io.*;
31import java.lang.*;
32import java.net.*;
33import java.util.*;
34import javax.swing.*;
35import org.greenstone.gatherer.Configuration;
36import org.greenstone.gatherer.DebugStream;
37import org.greenstone.gatherer.Dictionary;
38import org.greenstone.gatherer.Gatherer;
39import org.greenstone.gatherer.util.PortFinder;
40import org.greenstone.gatherer.util.SafeProcess;
41import org.greenstone.gatherer.util.Utility;
42
43
44public class LocalLibraryServer
45{
46 static final private int WAITING_TIME = 20; // number of seconds to wait for the server to start and stop
47
48 static final private String ADD_COMMAND = "?a=config&cmd=add-collection&c=";
49 static final private String RELEASE_COMMAND = "?a=config&cmd=release-collection&c=";
50 static final private String QUIT_COMMAND = "?a=config&cmd=kill";
51 static final private String RESTART_COMMAND = "?a=config&cmd=restart";
52
53 static private LLSSiteConfig llssite_cfg_file = null;
54 static private File local_library_server_file = null;
55
56 static private boolean running = false;
57 static private String ID = "greenstone-server"; // a sort of process ID
58
59 // Need to use sockets to tell the server program to terminate when on Linux
60 // The socket port number that we will use to communicate the termination
61 static private int port;
62 static private Socket clientSocket = null;
63 static private Writer clientSocketWriter = null;
64
65 // The server is persistent if it does not have to reload all the values
66 // over and over again each time. Tomcat is persistent and fastcgi is too,
67 // but the Apache webserver is not persistent by default.
68 // Change the initialisation of this value depending on whether fastcgi is
69 // on. At the moment, this does not apply to the Apache local library server.
70 static private boolean isPersistentServer = false;
71
72 static public boolean isPersistentServer() {
73 return isPersistentServer;
74 }
75
76 static public void addCollection(String collection_name)
77 {
78 if (isPersistentServer) {
79 config(ADD_COMMAND + collection_name);
80 }
81 }
82
83
84 // Used to send messages to the local library
85 static private void config(String command)
86 {
87 if (!isPersistentServer) {
88 return;
89 }
90 if (Configuration.library_url == null) {
91 System.err.println("Error: Trying to configure local library with null Configuration.library_url!");
92 return;
93 }
94
95 try {
96 URL url = new URL(Configuration.library_url.toString() + command);
97 HttpURLConnection library_connection = (HttpURLConnection) url.openConnection();
98
99 // It's very important that we read the output of the command
100 // This ensures that the command has actually finished
101 // (The response code is returned immediately)
102 InputStream library_is = library_connection.getInputStream();
103 BufferedReader library_in = new BufferedReader(new InputStreamReader(library_is, "UTF-8"));
104 String library_output_line = library_in.readLine();
105 while (library_output_line != null) {
106 DebugStream.println("Local library server output: " + library_output_line);
107 library_output_line = library_in.readLine();
108 }
109 library_in.close();
110
111 int response_code = library_connection.getResponseCode();
112 if (response_code >= HttpURLConnection.HTTP_OK && response_code < HttpURLConnection.HTTP_MULT_CHOICE) {
113 DebugStream.println("200 - Complete.");
114 }
115 else {
116 DebugStream.println("404 - Failed.");
117 }
118 }
119 catch (Exception exception) {
120 DebugStream.printStackTrace(exception);
121 }
122 }
123
124 // Used to send messages to the local library server wrapper to the Apache web server (server.jar)
125 static private boolean sendMessageToServer(String message) {
126 if(isPersistentServer) {
127 return false;
128 }
129
130 if(port == -1) {
131 return false;
132 }
133
134 try {
135 if(clientSocket == null) {
136 clientSocket = new Socket("localhost", port);
137 }
138 if(clientSocketWriter == null) {
139 clientSocketWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
140 }
141 clientSocketWriter.write(message);
142 clientSocketWriter.flush();
143
144 } catch (Exception e) {
145 System.err.println("An exception occurred when trying to send the message: " + message
146 + "\nto the LocalLibraryServer.\n" + e);
147 return false;
148 }
149 return true;
150 }
151
152 static public boolean isRunning()
153 {
154 if (!running) return false; // if the url is pending, then running would also be false (server not started up yet)
155
156 llssite_cfg_file.load(true);
157 String url = llssite_cfg_file.getURL();
158 if (url == null) return false;
159
160 // Called by Gatherer to check whether we need to stop the server.
161 // if the url is pending, then the GSI hasn't started the server up yet
162 // Already covered in !running
163 //if (url.equals(LLSSiteConfig.URL_PENDING)) return false;
164
165 return true;
166 }
167
168 /** collection name can be a group-qualified collect name */
169 static public void releaseCollection(String collection_name)
170 {
171 if (isPersistentServer) {
172 config(RELEASE_COMMAND + collection_name);
173 }
174 }
175
176 static public boolean start(String gsdl_path, String local_library_server_file_path)
177 {
178 // Check the local library server file (server.exe or gs2-server.sh) exists
179 if(local_library_server_file_path == null) {
180 return false;
181 }
182 local_library_server_file = new File(local_library_server_file_path);
183 if (local_library_server_file.exists()) {
184 if(local_library_server_file.getName().equals("server.exe")) {
185 isPersistentServer = true;
186 } // else it may be gs2-web-server.bat
187 }
188 else { // local_library_server_file does not exist
189 DebugStream.println("No local library at given file path.");
190
191 if(Utility.isWindows()) { // test for server.exe and gs2-web-server.bat
192 local_library_server_file = new File(gsdl_path + "server.exe");
193 if (local_library_server_file.exists()) {
194 isPersistentServer = true;
195 } else {
196 local_library_server_file = new File(gsdl_path + "gs2-web-server.bat");
197 if (!local_library_server_file.exists()) {
198 DebugStream.println("No local library at all.");
199 return false;
200 }
201 }
202 } else { // linux
203 local_library_server_file = new File(gsdl_path + "gs2-server.sh");
204 if (!local_library_server_file.exists()) {
205 DebugStream.println("No local library at all.");
206 return false;
207 }
208 }
209 }
210
211 if(!isPersistentServer) {
212 // In the case of the Local Library Server on Linux or on Win where there's no server.exe, do an extra test:
213 // If GS2 was not configured with --enable-apache-httpd, then there is no apache webserver folder,
214 // even though the gs2-server.sh file would still be there. That means if the folder is absent
215 // we still have no local library server.
216
217 File localServerFolder = new File(gsdl_path, "apache-httpd");
218 if (!localServerFolder.exists() && !localServerFolder.isDirectory()) {
219 DebugStream.println("The web server does not exist at "
220 + localServerFolder.getAbsolutePath() + "\nNo local library at all. Trying web library");
221 return false;
222 } // else apache-httpd folder exists
223 }
224
225 llssite_cfg_file = new LLSSiteConfig(local_library_server_file);
226 if(!llssite_cfg_file.isConfigFileSet()) {
227 return false;
228 }
229
230 // from now on return true: we're in local_library_mode (even if the server is not running)
231
232
233 // If the user launched the GSI independent of GLI, but user has not pressed
234 // Enter Library yet, then we will obtain the previewURL later.
235 if(LocalLibraryServer.isURLPending()) {
236 // running is still false when the URL is pending because only GSI is running, not the server
237 return true;
238 } else if(llssite_cfg_file.isIndependentGSI()) {
239 // There is already a url and it's not pending: meaning the server
240 // has started up and that GSI was launched outside of GLI
241 running = true;
242 return true;
243 }
244
245 // Spawn local library server process
246 final String QUOTES = Utility.isWindows() ? "\"" : ""; // need to embed path in quotes on Windows for spaces (interferes on Linux)
247 String local_library_server_command = QUOTES+local_library_server_file.getAbsolutePath()+QUOTES + getExtraLaunchArguments(llssite_cfg_file);
248 if(Utility.isWindows() && !isPersistentServer) { // launching gs2-web-server.bat (Windows) needs cmd start
249 local_library_server_command = "cmd.exe /c start \"GSI\" " + local_library_server_command;
250 }
251
252 // Check if the server is already running
253 String url = llssite_cfg_file.getURL();
254 if (url != null) {
255 // If it is already running then set the Greenstone web server address and we're done
256 // E.g. if previously GLI was not properly shut down, the URL property (signifying
257 // the server is still running) would still be in the config file.
258 try {
259 Configuration.library_url = new URL(url);
260 running = true;
261
262 // Run the server interface
263 Gatherer.spawnApplication(local_library_server_command, ID);
264 return true;
265 }
266 catch (MalformedURLException exception) {
267 DebugStream.printStackTrace(exception);
268 }
269 }
270
271 // Configure the server for immediate entry
272 //llssite_cfg_file.set();
273
274 // Spawn local library server process
275 Gatherer.spawnApplication(local_library_server_command, ID);
276
277 // Wait until program has started
278 try {
279 //System.err.println("**** testing server...");
280 testServerRunning(); // will set running = true when the server is up and running successfully
281 //System.err.println("**** Is server running: " + running);
282 } catch (IOException bad_url_connection) {
283 try {
284 // If this fails then we try changing the url to be localhost
285 Configuration.library_url = new URL(llssite_cfg_file.getLocalHostURL());
286 DebugStream.println("Try connecting to server on local host: '" + Configuration.library_url + "'");
287 URLConnection connection = Configuration.library_url.openConnection();
288 connection.getContent();
289 running = true;
290
291 } catch (IOException worse_url_connection) {
292 DebugStream.println("Can't connect to server on either address.");
293 Configuration.library_url = null;
294 running = false;
295 }
296 }
297
298 return true;
299 }
300
301 /** Call this when the collect directory has changed. Only works when using
302 * the web server launched by GLI. */
303 static public void reconfigure() {
304 if(isPersistentServer) {
305 // 1st: server may have nulled URL if server was stopped inbetween,
306 // so load that new URL, if GLI conf file modified
307 // Then put the new collectDir into the GLI configfile being used
308 llssite_cfg_file.load(true);
309
310 String collectDir = Gatherer.getCollectDirectoryPath();
311 collectDir = collectDir.substring(0, collectDir.length()-1); // remove file separator at end
312 llssite_cfg_file.put(LLSSiteConfig.COLLECTHOME, collectDir);
313 llssite_cfg_file.save();
314
315 // tell the server to restart, so it will read the new configuration
316
317 // (1) need a server to be running in order for us to send a restart message to it
318 if(checkServerRunning()) { // if true, it wasn't running before, but has now restarted the server. We're done
319 return;
320 }
321 // (2) otherwise the server may already have been running, need to tell it to restart after setting the collect dir
322 if(running) {
323 config(RESTART_COMMAND);
324 }
325 return;
326 }
327
328 // can't control the GSI/server if it was launched independent of GLI
329 if(llssite_cfg_file.isIndependentGSI()) {
330 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("Server.Reconfigure"), Dictionary.get("General.Reconfigure"), JOptionPane.INFORMATION_MESSAGE);
331 return;
332 }
333
334 // someone may have closed the web server
335 if(checkServerRunning()) { // need a server to be running in order for us to send a reconfigure message to it
336 return; // it has reconfigured and restarted the server
337 }
338
339 // If it was already running, tell the server a reconfigure is required on next restart
340 // and then restart
341 if(running && sendMessageToServer("RECONFIGURE\n")) {
342 // restart
343 if(running) {
344 running = false;
345
346 if(sendMessageToServer("RESTART\n")) { //if(sendMessageToServer("RECONFIGURE\n")) {
347 // wait for the server to update the URL in the gli config file
348 llssite_cfg_file.setLastModified();
349
350 int attempt_count = 0;
351 while (!llssite_cfg_file.isModified()) {
352 new OneSecondWait(); // Wait one second (give or take)
353 attempt_count++;
354
355 // After waiting for the specified time, ask the user whether they want to wait for that long again
356 if (attempt_count == WAITING_TIME) {
357 break; // can't be waiting forever, we'll be waiting again below
358 }
359 }
360
361 try {
362 testServerRunning(); // will set running = true when the server is up and running successfully
363 } catch (IOException bad_url_connection) {
364 try {
365 // If this fails then we try changing the url to be localhost
366 Configuration.library_url = new URL(llssite_cfg_file.getLocalHostURL());
367 DebugStream.println("Try connecting to server on local host: '" + Configuration.library_url + "'");
368 URLConnection connection = Configuration.library_url.openConnection();
369 connection.getContent();
370 running = true;
371
372 } catch (IOException worse_url_connection) {
373 DebugStream.println("Can't connect to server on either address.");
374 Configuration.library_url = null;
375 running = false;
376 }
377 }
378 }
379 }
380 } else {
381 System.err.println("GLI was unable to send a reconfigure request to the local library server."
382 + "\nPlease reconfigure and restart the local Greenstone server manually.");
383 }
384 }
385
386
387 static public void stop()
388 {
389 if (!running) {
390 // also the case if the URL is pending in an independently launched GSI
391 return;
392 }
393
394 // don't (can't) shutdown the GSI/server if it was launched independent of GLI
395 if(llssite_cfg_file.isIndependentGSI()) {
396 return;
397 }
398
399 // Send the command for it to exit.
400 if (isPersistentServer) {
401 config(QUIT_COMMAND);
402 } else {
403 boolean success = sendMessageToServer("QUIT\n");
404 try {
405 if(clientSocketWriter != null) {
406 clientSocketWriter.close();
407 clientSocketWriter = null;
408 }
409 clientSocket = null;
410 } catch(Exception e) {
411 System.err.println("An exception occurred when trying to close the socket"
412 + "\nto the LocalLibraryServer.\n" + e);
413 }
414 if(success) {
415 Gatherer.terminateApplication(ID);
416 } else {
417 System.err.println("Unable to stop the server, since there's no communication port to send the quit msg over."
418 + "\nPlease stop the local Greenstone server manually.");
419 }
420 }
421
422 // Wait until program has stopped, by reloading and checking the URL field
423 llssite_cfg_file.load(false);
424 int attempt_count = 0;
425 String url = llssite_cfg_file.getURL();
426 while (url != null && !url.equals(LLSSiteConfig.URL_PENDING)) { // if pending, the server is already stopped (not running)
427 new OneSecondWait(); // Wait one second (give or take)
428 llssite_cfg_file.load(false);
429 attempt_count++;
430
431 // After waiting for the specified time, ask the user whether they want to wait for that long again
432 if (attempt_count == WAITING_TIME) {
433 int try_again = JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("Server.QuitTimeOut", Integer.toString(WAITING_TIME)),
434 Dictionary.get("General.Warning"), JOptionPane.YES_NO_OPTION);
435 if (try_again == JOptionPane.NO_OPTION) {
436 return;
437 }
438 attempt_count = 0;
439 }
440 // read the url again to see if it's updated
441 url = llssite_cfg_file.getURL();
442 }
443
444 // Restore the llssite_cfg.
445 llssite_cfg_file.restore();
446
447 // If the local server is still running then our changed values will get overwritten.
448 url = llssite_cfg_file.getURL();
449 if (url != null && !url.equals(LLSSiteConfig.URL_PENDING)) {
450 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("Server.QuitManual"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
451 }
452
453 running = false;
454 }
455
456 // This method does the approximate equivalent of util.GSServerThread.stopServer()
457 // On unexpected, unnatural termination of GLI, call this to send the web-stop message the local library server to stop
458 static public void forceStopServer() {
459 SafeProcess p = null;
460 if (Utility.isWindows()) {
461 // cmd /C "cd "C:\path\to\greenstone3" && ant stop"
462 p = new SafeProcess("cmd /C \"cd \"" + Configuration.gsdl_path + File.separator + "\" && gsicontrol.bat web-stop\"");
463 } else {
464 p = new SafeProcess(new String[]{"/bin/bash", "-c", "cd \"" + Configuration.gsdl_path + "\" && ./gsicontrol.sh web-stop"});
465 }
466 int result = p.runProcess();
467 if(result == 0) {
468 System.err.println("Successfully stopped GS2 server.");
469 //DebugStream.println("********** SUCCESSFULLY stopped THE GS2 SERVER ON EXIT");
470 }
471 else {
472 System.err.println("********** FAILED TO SUCCESSFULLY stop THE GS2 SERVER ON EXIT");
473 }
474 p = null;
475 }
476
477 static private String getExtraLaunchArguments(LLSSiteConfig site_cfg_file) {
478 String args = " " + LLSSiteConfig.GLIMODE + " " + site_cfg_file.getSiteConfigFilename();
479
480 if(isPersistentServer) {
481 return args;
482 }
483
484 // Else, when running the Local Apache Library Server on Linux/Win, need to provide a port argument
485 try {
486 PortFinder portFinder = new PortFinder(50100, 100);
487 port = portFinder.findPortInRange(false); // silent mode
488 } catch(Exception e) {
489 System.err.println("Exception when trying to find an available port: " + e);
490 port = -1;
491 }
492
493 return args + " --quitport=" + port;
494 }
495
496
497 // This method first tests whether there is a URL in the llssite_cfg_file
498 // and after that appears, it tests whether the URL is functional.
499 static private void testServerRunning() throws IOException {
500 // Wait until program has started, by reloading and checking the URL field
501 llssite_cfg_file.load(false);
502 int attempt_count = 0;
503 while (llssite_cfg_file.getURL() == null) {
504 new OneSecondWait(); // Wait one second (give or take)
505 //System.err.println("**** One Second Wait");
506 llssite_cfg_file.load(false);
507 attempt_count++;
508
509 // After waiting for the specified time, ask the user whether they want to wait for that long again
510 if (attempt_count == WAITING_TIME) {
511 int try_again = JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("Server.StartUpTimeOut", Integer.toString(WAITING_TIME)),
512 Dictionary.get("General.Warning"), JOptionPane.YES_NO_OPTION);
513 if (try_again == JOptionPane.NO_OPTION) {
514 return;
515 }
516 attempt_count = 0;
517 }
518 }
519
520 // Ta-da. Now the url should be available
521 try {
522 Configuration.library_url = new URL(llssite_cfg_file.getURL());
523 }
524 catch (MalformedURLException exception) {
525 DebugStream.printStackTrace(exception);
526 }
527
528 // A quick test involves opening a connection to get the home page for this collection
529 try {
530 DebugStream.println("Try connecting to server on config url: '" + Configuration.library_url + "'");
531 URLConnection connection = Configuration.library_url.openConnection();
532 connection.getContent();
533 running = true;
534 }
535 catch (IOException bad_url_connection) {
536 System.err.println("Unable to open a connection to " + Configuration.library_url
537 + "\nCheck whether the port may already be in use. If so, change your\n"
538 + "Greenstone port number in the Greenstone Server Interface(GSI).");
539 throw bad_url_connection;
540 }
541
542
543 }
544
545 /** Returns true if we're waiting on the user to click on Enter Library button
546 * in an independently launched GSI (one not launched by GLI). */
547 static public boolean isURLPending() {
548 //if(Configuration.library_url != null) {
549 //System.err.println("**** Configuration.library_url: " + Configuration.library_url );
550 //return false; // don't need to do anything as we already have the url
551 //}
552
553 llssite_cfg_file.load(true); // don't force reload, load only if modified
554
555 String url = llssite_cfg_file.getURL();
556
557 if(url != null) {
558 if(url.equals(LLSSiteConfig.URL_PENDING)) {
559 running = false; // imagine if they restarted an external GSI
560 return true;
561 } else {
562 // a valid URL at last
563 try {
564 Configuration.library_url = new URL(url);
565 running = true;
566 }
567 catch (MalformedURLException exception) {
568 running = false;
569 exception.printStackTrace();
570 DebugStream.printStackTrace(exception);
571 }
572 return false;
573 }
574 }
575
576 // If either the URL is null--which means no independent GSI (Greenstone server interface
577 // app) was launched--or if the 'URL' doesn't say it's pending, then we're not waiting
578 return false;
579 }
580
581 /** @returns true if it had to restart the server. Returns false if it didn't restart it. */
582 static public boolean checkServerRunning() {
583 boolean serverRestarted = false;
584
585 if (!running) return false; // don't worry about it if it's not supposed to be running
586 llssite_cfg_file.load(true); // don't force reload, load only if modified
587
588 String url = llssite_cfg_file.getURL();
589 if(url != null) {
590 if(url.equals(LLSSiteConfig.URL_PENDING)) {
591 running = false;
592 return false;
593 }
594
595 // else, valid URL:
596 try {
597 Configuration.library_url = new URL(url);
598 running = true;
599 }
600 catch (MalformedURLException exception) {
601 running = false;
602 DebugStream.printStackTrace(exception);
603 exception.printStackTrace();
604 }
605 }
606 else { // NO URL in current mode of configFile, try other mode (e.g. "gli.url")
607
608 if(llssite_cfg_file.usingGSImode()) { // if a GSI is already using llssite_cfg, this would have loaded it in
609 url = llssite_cfg_file.getURL(); //if(isURLPending()) {
610 if(url.equals(LLSSiteConfig.URL_PENDING)) {
611 running = false;
612 } else {
613 running = true;
614 }
615 return false; // don't need to launch the server, one has been independently launched
616 } else {
617 // else we try using the "gli." prefix to access the url property in the config file
618 llssite_cfg_file.useGLImode();
619 //llssite_cfg_file.set();
620
621 // since we're going to restart the server, make sure to reset all
622 // the client socket and its writer (for communicating with the web server)
623 // will only be reinstantiated if they are first nulled
624 if(clientSocket != null) {
625 clientSocket = null;
626 }
627 if(clientSocketWriter != null) {
628 try{
629 clientSocketWriter.close();
630 clientSocketWriter = null;
631 } catch(Exception e) {
632 System.err.println("Unable to close the client socket outputstream.");
633 } finally {
634 clientSocketWriter = null;
635 }
636 }
637
638 // Spawn local library server process
639 running = false;
640 final String QUOTES = Utility.isWindows() ? "\"" : ""; // need to embed path in quotes on Windows for spaces (interferes on Linux)
641 String local_library_server_command = QUOTES+local_library_server_file.getAbsolutePath()+QUOTES + getExtraLaunchArguments(llssite_cfg_file);
642 if(Utility.isWindows() && !isPersistentServer) { // launching gs2-web-server.bat (Windows) needs cmd start
643 local_library_server_command = "cmd.exe /c start \"GSI\" " + local_library_server_command;
644 }
645 Gatherer.spawnApplication(local_library_server_command, ID);
646 try {
647 testServerRunning(); // don't return until the webserver is up and running
648 serverRestarted = true;
649 } catch (IOException bad_url_connection) {
650 DebugStream.println("Can't connect to server on address " + Configuration.library_url);
651 running = false;
652 }
653 }
654 }
655 return serverRestarted;
656 }
657
658 static private class OneSecondWait
659 {
660 public OneSecondWait()
661 {
662 synchronized(this) {
663 try {
664 wait(1000);
665 }
666 catch (InterruptedException exception) {
667 }
668 }
669 }
670 }
671
672
673 static public class LLSSiteConfig
674 extends LinkedHashMap
675 {
676 private File configFile;
677
678 private String autoenter_initial;
679 private String start_browser_initial;
680
681 private long lastModified = 0;
682 private boolean isIndependentGSI;
683
684 static final private String GLI_PREFIX = "gli";
685 static final private String GSI_AUTOENTER = "autoenter";
686 static final private String AUTOENTER = GLI_PREFIX+"."+"autoenter";
687 static final private String COLON = ":";
688 static final private String ENTERLIB = "enterlib";
689 static final private String FALSE = "0";
690 static final private String GSDL = "greenstone"; // httpprefix is no longer /gsdl but /greenstone
691 static final private String LLSSITE_CFG = "llssite.cfg";
692 static final private String LOCAL_HOST = "http://localhost";
693 static final private String PORTNUMBER = "portnumber";
694 static final private String SEPARATOR = "/";
695 static final private String SPECIFIC_CONFIG = "--config=";
696 static final private String STARTBROWSER = GLI_PREFIX+"."+"start_browser";
697 static final private String GSI_STARTBROWSER = "start_browser";
698 static final private String TRUE = "1";
699 static final private String URL = GLI_PREFIX+"."+"url";
700 static final private String GSI_URL = "url";
701 static final private String COLLECTHOME = "collecthome";
702 static final private String GLIMODE = "--mode="+GLI_PREFIX;
703
704 static final public String URL_PENDING = "URL_pending";
705
706
707 public LLSSiteConfig(File server_exe) {
708 debug("New LLSSiteConfig for: " + server_exe.getAbsolutePath());
709
710 configFile = new File(server_exe.getParentFile(), LLSSITE_CFG);
711 if(!configFile.exists()) { // create it from the template
712 File llssite_cfg_in = new File(server_exe.getParentFile(), LLSSITE_CFG+".in");
713
714 // need to generate llssite_cfg from llssite_cfg_in
715 if(llssite_cfg_in.exists()) {
716 copyConfigFile(llssite_cfg_in, configFile, true); // adjust for gli
717 }
718 else {
719 debug("File llssite.cfg.in can't be found. Can't create llssite.cfg frrom llssite.cfg.in.");
720 }
721 }
722
723 // use the config file now
724 if(configFile.exists()) {
725 // first test if server was started independently of GLI
726 // if so, the config file we'd be using would be llssite.cfg
727 if(!usingGSImode()) { // this step will try to access the url and other
728 // special properties in the config file using the "gli." prefix.
729 useGLImode();
730 }
731
732 } else {
733 System.err.println("**** ERROR. Configfile is null.");
734 configFile = null;
735 }
736
737 autoenter_initial = null;
738 start_browser_initial = null;
739
740 // GS2. We're in the constructor, so we'll be running the LLS the first time
741 // Set the correct collectdir (from last time) before the server is started up
742
743 String orig_collection_path = Configuration.getString("general.open_collection_gs2", true);
744 String collectDir = Gatherer.getCollectDirectoryPath(); // Gatherer would've set this up
745 String defaultColDir = Gatherer.getDefaultGSCollectDirectoryPath(true); // with file separator at end
746
747 if(orig_collection_path.equals("")) { // default GS collect dir path
748 return;
749 }
750
751 if (!orig_collection_path.startsWith(collectDir) // if coldir would've been changed on startup OR if coldir is non-standard collect folder
752 || !collectDir.equals(defaultColDir))
753 {
754 // if we're running *server.exe* and if the current collect dir at Local Lib's startup is
755 // anything other than the default GS collect dir or if we changed back to the default collect
756 // dir because the non-standard collectDir didn't exist/wasn't specified in the GLI config
757 // file, then write out the new collectDir (minus file separator at end) to the lls site conf in use
758 // Regardless of what collecthome value was in the llssite file, we end up resetting it here
759 if (isPersistentServer) { // server.exe, so we're dealing with a local GS2
760 put(COLLECTHOME, collectDir);
761 save();
762 lastModified = configFile.lastModified();
763 }
764 } // now the correct current collect dir will get loaded when the server is started up hereafter
765 }
766
767 /** Changes the mode to GLI mode (since GSI was not launched independently but by GLI): in this
768 * mode, the "gli." prefix is used to access GLI specific properties from the config file */
769 public void useGLImode()
770 {
771 isIndependentGSI = false;
772 load(true); // reload if modified
773 }
774
775 /** Tests whether the server interface is up, running independently of GLI
776 * If so, we don't need to launch the server interface.
777 * The server interface may not have started up the server itself though
778 * (in which case the server URL would be URL_PENDING).
779 * This method returns true if the server interface has already started
780 * and, if so, it would have loaded in the configFile. It sets the mode to
781 * GSI Mode (meaning GSI was launched independently): no prefix is used to
782 * access properties from the config file.
783 */
784 public boolean usingGSImode() {
785 // Now to check if the configfile contains the GSI_URL line
786 load(false); // force load
787 isIndependentGSI = true;
788 if(getURL() == null) {
789 isIndependentGSI = false;
790 return false;
791 }
792
793 lastModified = configFile.lastModified();
794 return true;
795 }
796
797 /** To test we've actually instantiated this object meaningfully. If so, then configFile is set */
798 public boolean isConfigFileSet() {
799 return (configFile != null && configFile.exists());
800 }
801
802 /** @return true if GSI was started up independently and outside of GLI.
803 * In such a case, GLI would be using llssite_cfg. */
804 public boolean isIndependentGSI() {
805 return isIndependentGSI;
806 }
807
808 public boolean exists() {
809 return configFile.exists();
810 }
811
812 public String getLocalHostURL() {
813 StringBuffer url = new StringBuffer(LOCAL_HOST);
814 url.append(COLON);
815 url.append((String)get(PORTNUMBER));
816 String enterlib = (String)get(ENTERLIB);
817 if(!isPersistentServer || enterlib == null || enterlib.length() == 0) {
818 // Use the default /gsdl and hope for the best.
819 url.append(SEPARATOR);
820 url.append(GSDL);
821 }
822 else {
823 if(!enterlib.startsWith(SEPARATOR)) {
824 url.append(SEPARATOR);
825 }
826 url.append(enterlib);
827 }
828 enterlib = null;
829 debug("Found Local Library Address: " + url.toString());
830 return url.toString();
831 }
832
833 /** @return the cmd-line parameter for the configfile used to launch
834 * the server through GLI: --config=<llssite.cfg file path>. */
835 public String getSiteConfigFilename() {
836 return SPECIFIC_CONFIG + configFile.getAbsolutePath();
837 }
838
839 public String getURL() {
840 String urlPropertyName = isIndependentGSI() ? GSI_URL : URL;
841 // URL is made from url and portnumber
842 String url = (String) get(urlPropertyName);
843
844 // server interface is already up, independent of GLI
845 // but it has not started the server (hence URL is pending)
846 if(url != null && url.equals(URL_PENDING)) {
847 return url;
848 }
849
850 if(!isPersistentServer) {
851 return url;
852 }
853
854 if(url != null) {
855 StringBuffer temp = new StringBuffer(url);
856 temp.append(COLON);
857 temp.append((String)get(PORTNUMBER));
858 String enterlib = (String)get(ENTERLIB);
859 if(enterlib == null || enterlib.length() == 0) {
860 // Use the default /greenstone prefix and hope for the best.
861 temp.append(SEPARATOR);
862 temp.append(GSDL);
863 }
864 else {
865 if(!enterlib.startsWith(SEPARATOR)) {
866 temp.append(SEPARATOR);
867 }
868 temp.append(enterlib);
869 }
870 enterlib = null;
871 url = temp.toString();
872 }
873 debug("Found Local Library Address: " + url);
874 return url;
875 }
876
877 public void setLastModified() {
878 if(isModified()) {
879 lastModified = configFile.lastModified();
880 }
881 }
882
883 public boolean isModified() {
884 return (lastModified != configFile.lastModified());
885 }
886
887 public void load(boolean reloadOnlyIfModified) {
888
889 if(configFile == null) {
890 debug(configFile.getAbsolutePath() + " cannot be found!");
891 }
892
893 if(isModified()) {
894 lastModified = configFile.lastModified();
895 } else if(reloadOnlyIfModified) {
896 return; // asked to reload only if modified. Don't reload since not modified
897 }
898
899 if(configFile.exists()) {
900 debug("Load: " + configFile.getAbsolutePath());
901 clear();
902 try {
903 BufferedReader in = new BufferedReader(new FileReader(configFile));
904 String line = null;
905 while((line = in.readLine()) != null) {
906 String key = null;
907 String value = null;
908 int index = -1;
909 if((index = line.indexOf("=")) != -1 && line.length() >= index + 1) {
910 key = line.substring(0, index);
911 value = line.substring(index + 1);
912 }
913 else {
914 key = line;
915 }
916 put(key, value);
917 }
918
919 in.close();
920 }
921 catch (Exception error) {
922 error.printStackTrace();
923 }
924 }
925 else {
926 debug(configFile.getAbsolutePath() + " cannot be found!");
927 }
928 }
929
930 /** Restore the autoenter value to its initial value, and remove url if present. */
931 public void restore() {
932 if(configFile != null) {
933 // Delete the file
934 //configFile.delete();
935
936 // Not restoring nor deleting here. Just removing the URL (which indicates a running server),
937 // so that the file's state indicates the server has stopped, and then saving the property file.
938 // Should all properties not defined in the llssite.cfg.in template be removed below?
939 String urlPropertyName = isIndependentGSI() ? GSI_URL : URL;
940 remove(urlPropertyName);
941
942 remove("gsdlhome");
943 remove("collecthome");
944 remove("gdbmhome");
945 remove("logfilename");
946
947 // For some reason launching GLI with server.exe clobbers autoenter and startbrowser
948 // values for independent GSI in llssite.cfg file, and gli.autoenter and gli.startbrowser.
949 // So set them here.
950 if(get(GSI_AUTOENTER) == null) {
951 put(GSI_AUTOENTER, "0");
952 }
953 if(get(GSI_STARTBROWSER) == null) {
954 put(GSI_STARTBROWSER, "1");
955 }
956 if(get(AUTOENTER) == null) {
957 put(AUTOENTER, "1");
958 }
959 if(get(STARTBROWSER) == null) {
960 put(STARTBROWSER, "0");
961 }
962 save();
963 }
964 else {
965 String urlPropertyName = isIndependentGSI() ? GSI_URL : URL;
966 debug("Restore Initial Settings");
967 put(AUTOENTER, autoenter_initial);
968 put(STARTBROWSER, start_browser_initial);
969 remove(urlPropertyName);
970 save();
971 }
972 }
973
974 public void set() {
975 debug("Set Session Settings");
976 if(autoenter_initial == null) {
977 autoenter_initial = (String) get(AUTOENTER);
978 debug("Remember autoenter was: " + autoenter_initial);
979 }
980 put(AUTOENTER, TRUE);
981 if(start_browser_initial == null) {
982 start_browser_initial = (String) get(STARTBROWSER);
983 debug("Remember start_browser was: " + start_browser_initial);
984 }
985 put(STARTBROWSER, FALSE);
986 save();
987 }
988
989 private void debug(String message) {
990 ///ystem.err.println(message);
991 }
992
993 private void save() {
994 debug("Save: " + configFile.getAbsolutePath());
995 try {
996 BufferedWriter out = new BufferedWriter(new FileWriter(configFile, false));
997 for(Iterator keys = keySet().iterator(); keys.hasNext(); ) {
998 String key = (String) keys.next();
999 String value = (String) get(key);
1000 out.write(key, 0, key.length());
1001 if(value != null) {
1002 out.write('=');
1003
1004 // if the GSI was launched outside of GLI, don't overwrite its default
1005 // autoenter and startbrowser values
1006 if(isIndependentGSI && (key == GSI_AUTOENTER || key == GSI_STARTBROWSER)) {
1007 if(key == GSI_AUTOENTER) {
1008 out.write(autoenter_initial, 0, autoenter_initial.length());
1009 } else { // GSI_STARTBROWSER
1010 out.write(start_browser_initial, 0, start_browser_initial.length());
1011 }
1012 } else {
1013 out.write(value, 0, value.length());
1014 }
1015 }
1016 out.newLine();
1017 }
1018 out.flush();
1019 out.close();
1020 }
1021 catch (Exception error) {
1022 error.printStackTrace();
1023 }
1024 }
1025
1026 private static void copyConfigFile(File source_cfg, File dest_cfg, boolean setToGliSiteDefaults) {
1027 // source_cfg file should exist
1028 // dest_cfg file should not yet exist
1029 // If setToGliSiteDefaults is true, then GLIsite.cfg's default configuration
1030 // is applied to concerned lines: gli.autoenter=1, and gli.startbrowser=0
1031
1032 try {
1033 BufferedReader in = new BufferedReader(new FileReader(source_cfg));
1034 BufferedWriter out = new BufferedWriter(new FileWriter(dest_cfg, false));
1035
1036 String line = null;
1037 while((line = in.readLine()) != null) {
1038
1039 if(setToGliSiteDefaults) {
1040 if(line.startsWith(AUTOENTER)) {
1041 line = AUTOENTER+"=1";
1042 }
1043 else if(line.startsWith(STARTBROWSER)) {
1044 line = STARTBROWSER+"=0";
1045 }
1046 }
1047
1048 // write out the line
1049 out.write(line);
1050 out.newLine();
1051 }
1052
1053 out.flush();
1054 in.close();
1055 out.close();
1056 } catch(Exception e) {
1057 System.err.println("Exception occurred when trying to copy the config file "
1058 + source_cfg.getName() + " to " + dest_cfg.getName() + ": " + e);
1059 e.printStackTrace();
1060 }
1061 }
1062 }
1063}
Note: See TracBrowser for help on using the repository browser.