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

Last change on this file since 20480 was 20480, checked in by ak19, 15 years ago

Changes made to incorporate the Local Apache Library Server on Windows. Needs to be retested on Linux to make sure things still work there.

  • Property svn:keywords set to Author Date Id Revision
File size: 28.0 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.Utility;
41
42
43public class LocalLibraryServer
44{
45 static final private int WAITING_TIME = 20; // number of seconds to wait for the server to start and stop
46
47 static final private String ADD_COMMAND = "?a=config&cmd=add-collection&c=";
48 static final private String RELEASE_COMMAND = "?a=config&cmd=release-collection&c=";
49 static final private String QUIT_COMMAND = "?a=config&cmd=kill";
50
51 static private LLSSiteConfig llssite_cfg_file = null;
52 static private File local_library_server_file = null;
53
54 static private boolean running = false;
55 static private String ID = "greenstone-server"; // a sort of process ID
56
57 // Need to use sockets to tell the server program to terminate when on Linux
58 // The socket port number that we will use to communicate the termination
59 static private int port;
60
61 // The server is persistent if it does not have to reload all the values
62 // over and over again each time. Tomcat is persistent and fastcgi is too,
63 // but the Apache webserver is not persistent by default.
64 // Change the initialisation of this value depending on whether fastcgi is
65 // on. At the moment, this does not apply to the Apache local library server.
66 static private boolean isPersistentServer = false;
67
68 static public void addCollection(String collection_name)
69 {
70 if (isPersistentServer) {
71 config(ADD_COMMAND + collection_name);
72 }
73 }
74
75
76 // Used to send messages to the local library
77 static private void config(String command)
78 {
79 if (!isPersistentServer) {
80 return;
81 }
82 if (Configuration.library_url == null) {
83 System.err.println("Error: Trying to configure local library with null Configuration.library_url!");
84 return;
85 }
86
87 try {
88 URL url = new URL(Configuration.library_url.toString() + command);
89 HttpURLConnection library_connection = (HttpURLConnection) url.openConnection();
90
91 // It's very important that we read the output of the command
92 // This ensures that the command has actually finished
93 // (The response code is returned immediately)
94 InputStream library_is = library_connection.getInputStream();
95 BufferedReader library_in = new BufferedReader(new InputStreamReader(library_is, "UTF-8"));
96 String library_output_line = library_in.readLine();
97 while (library_output_line != null) {
98 DebugStream.println("Local library server output: " + library_output_line);
99 library_output_line = library_in.readLine();
100 }
101 library_in.close();
102
103 int response_code = library_connection.getResponseCode();
104 if (response_code >= HttpURLConnection.HTTP_OK && response_code < HttpURLConnection.HTTP_MULT_CHOICE) {
105 DebugStream.println("200 - Complete.");
106 }
107 else {
108 DebugStream.println("404 - Failed.");
109 }
110 }
111 catch (Exception exception) {
112 DebugStream.printStackTrace(exception);
113 }
114 }
115
116 // Used to send messages to the local library server wrapper to the Apache web server (server.jar)
117 static private boolean sendMessageToServer(String message) {
118 if(isPersistentServer) {
119 return false;
120 }
121
122 if(port == -1) {
123 return false;
124 }
125
126 try {
127 Socket clientSocket = new Socket("localhost", port);
128 Writer writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
129 writer.write(message);
130 writer.close();
131 writer = null;
132 } catch (Exception e) {
133 System.err.println("An exception occurred when trying to send the message: " + message
134 + "\nto the LocalLibraryServer.\n" + e);
135 return false;
136 }
137 return true;
138 }
139
140 static public boolean isRunning()
141 {
142 if (!running) return false; // if the url is pending, then running would also be false (server not started up yet)
143
144 llssite_cfg_file.load(true);
145 String url = llssite_cfg_file.getURL();
146 if (url == null) return false;
147
148 // Called by Gatherer to check whether we need to stop the server.
149 // if the url is pending, then the GSI hasn't started the server up yet
150 // Already covered in !running
151 //if (url.equals(LLSSiteConfig.URL_PENDING)) return false;
152
153 return true;
154 }
155
156
157 static public void releaseCollection(String collection_name)
158 {
159 if (isPersistentServer) {
160 config(RELEASE_COMMAND + collection_name);
161 }
162 }
163
164 static public boolean start(String gsdl_path, String local_library_server_file_path)
165 {
166 // Check the local library server file (server.exe or gs2-server.sh) exists
167 if(local_library_server_file_path == null) {
168 return false;
169 }
170 local_library_server_file = new File(local_library_server_file_path);
171 if (local_library_server_file.exists()) {
172 if(local_library_server_file.getName().equals("server.exe")) {
173 isPersistentServer = true;
174 } // else it may be gs2-server.bat
175 }
176 else { // local_library_server_file does not exist
177 DebugStream.println("No local library at given file path.");
178
179 if(Utility.isWindows()) { // test for server.exe and gs2-server.bat
180 local_library_server_file = new File(gsdl_path + "server.exe");
181 if (local_library_server_file.exists()) {
182 isPersistentServer = true;
183 } else {
184 local_library_server_file = new File(gsdl_path + "gs2-server.bat");
185 if (!local_library_server_file.exists()) {
186 DebugStream.println("No local library at all.");
187 return false;
188 }
189 }
190 } else { // linux
191 local_library_server_file = new File(gsdl_path + "gs2-server.sh");
192 if (!local_library_server_file.exists()) {
193 DebugStream.println("No local library at all.");
194 return false;
195 }
196 }
197 }
198
199 if(!isPersistentServer) {
200 // In the case of the Local Library Server on Linux or on Win where there's no server.exe, do an extra test:
201 // If GS2 was not configured with --enable-apache-httpd, then there is no apache webserver folder,
202 // even though the gs2-server.sh file would still be there. That means if the folder is absent
203 // we still have no local library server.
204
205 File localServerFolder = new File(gsdl_path, "apache-httpd");
206 if (!localServerFolder.exists() && !localServerFolder.isDirectory()) {
207 DebugStream.println("The web server does not exist at "
208 + localServerFolder.getAbsolutePath() + "\nNo local library at all. Trying web library");
209 return false;
210 } // else apache-httpd folder exists
211 }
212
213 llssite_cfg_file = new LLSSiteConfig(local_library_server_file);
214 if(!llssite_cfg_file.isConfigFileSet()) {
215 return false;
216 }
217
218 // from now on return true: we're in local_library_mode (even if the server is not running)
219
220
221 // If the user launched the GSI independent of GLI, but user has not pressed
222 // Enter Library yet, then we will obtain the previewURL later.
223 if(LocalLibraryServer.isURLPending()) {
224 // running is still false when the URL is pending because only GSI is running, not the server
225 return true;
226 } else if(llssite_cfg_file.isIndependentGSI()) {
227 // there is a url, it's not pending, and it is llssite.cfg: meaning GSI has started up
228 running = true;
229 return true;
230 }
231
232 // Spawn local library server process
233 String local_library_server_command = local_library_server_file.getAbsolutePath() + getExtraLaunchArguments(llssite_cfg_file);
234 if(Utility.isWindows()) {
235 local_library_server_command = "cmd.exe /c start \"GSI\" " + local_library_server_command;
236 }
237
238 // Check if the server is already running
239 String url = llssite_cfg_file.getURL();
240 if (url != null) {
241 // If it is already running then set the Greenstone web server address and we're done
242 // E.g. if previously GLI was not properly shut down, the URL property (signifying
243 // the server is still running) would still be in the glisite_cfg file.
244 try {
245 Configuration.library_url = new URL(url);
246 running = true;
247
248 // Run the server interface
249 Gatherer.spawnApplication(local_library_server_command, ID);
250 return true;
251 }
252 catch (MalformedURLException exception) {
253 DebugStream.printStackTrace(exception);
254 }
255 }
256
257 // Configure the server for immediate entry
258 //llssite_cfg_file.set();
259
260 // Spawn local library server process
261 Gatherer.spawnApplication(local_library_server_command, ID);
262
263 // Wait until program has started
264 try {
265 //System.err.println("**** testing server...");
266 testServerRunning(); // will set running = true when the server is up and running successfully
267 //System.err.println("**** Is server running: " + running);
268 } catch (IOException bad_url_connection) {
269 try {
270 // If this fails then we try changing the url to be localhost
271 Configuration.library_url = new URL(llssite_cfg_file.getLocalHostURL());
272 DebugStream.println("Try connecting to server on local host: '" + Configuration.library_url + "'");
273 URLConnection connection = Configuration.library_url.openConnection();
274 connection.getContent();
275 running = true;
276
277 } catch (IOException worse_url_connection) {
278 DebugStream.println("Can't connect to server on either address.");
279 Configuration.library_url = null;
280 running = false;
281 }
282 }
283
284 return true;
285 }
286
287
288 static public void stop()
289 {
290 if (!running) {
291 // also the case if the URL is pending in an independently launched GSI
292 return;
293 }
294
295 // don't (can't) shutdown the GSI/server if it was launched independent of GLI
296 if(llssite_cfg_file.isIndependentGSI()) {
297 return;
298 }
299
300 // Send the command for it to exit.
301 if (isPersistentServer) {
302 config(QUIT_COMMAND);
303 } else {
304 if(sendMessageToServer("QUIT")) {
305 Gatherer.terminateApplication(ID);
306 } else {
307 System.err.println("Unable to stop the server, since there's no communication port to send the quit msg over."
308 + "\nPlease stop the local Greenstone server manually.");
309 }
310 }
311
312 // Wait until program has stopped, by reloading and checking the URL field
313 llssite_cfg_file.load(false);
314 int attempt_count = 0;
315 String url = llssite_cfg_file.getURL();
316 while (url != null && !url.equals(LLSSiteConfig.URL_PENDING)) { // if pending, the server is already stopped (not running)
317 new OneSecondWait(); // Wait one second (give or take)
318 llssite_cfg_file.load(false);
319 attempt_count++;
320
321 // After waiting for the specified time, ask the user whether they want to wait for that long again
322 if (attempt_count == WAITING_TIME) {
323 int try_again = JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("Server.QuitTimeOut", Integer.toString(WAITING_TIME)),
324 Dictionary.get("General.Warning"), JOptionPane.YES_NO_OPTION);
325 if (try_again == JOptionPane.NO_OPTION) {
326 return;
327 }
328 attempt_count = 0;
329 }
330 // read the url again to see if it's updated
331 url = llssite_cfg_file.getURL();
332 }
333
334 // Restore the llssite_cfg.
335 llssite_cfg_file.restore();
336
337 // If the local server is still running then our changed values will get overwritten.
338 url = llssite_cfg_file.getURL();
339 if (url != null && !url.equals(LLSSiteConfig.URL_PENDING)) {
340 JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("Server.QuitManual"), Dictionary.get("General.Error"), JOptionPane.ERROR_MESSAGE);
341 }
342
343 running = false;
344 }
345
346 static private String getExtraLaunchArguments(LLSSiteConfig site_cfg_file) {
347 String args = " " + site_cfg_file.getSiteConfigFilename();
348
349 if(isPersistentServer) {
350 return args;
351 }
352
353 // Else, when running the Local Apache Library Server on Linux/Win, need to provide a port argument
354 try {
355 PortFinder portFinder = new PortFinder(50100, 100);
356 port = portFinder.findPortInRange(false); // silent mode
357 } catch(Exception e) {
358 System.err.println("Exception when trying to find an available port: " + e);
359 port = -1;
360 }
361
362 return args + " --quitport=" + port;
363 }
364
365
366 // This method first tests whether there is a URL in the llssite_cfg_file
367 // and after that appears, it tests whether the URL is functional.
368 static private void testServerRunning() throws IOException {
369 // Wait until program has started, by reloading and checking the URL field
370 llssite_cfg_file.load(false);
371 int attempt_count = 0;
372 while (llssite_cfg_file.getURL() == null) {
373 new OneSecondWait(); // Wait one second (give or take)
374 //System.err.println("**** One Second Wait");
375 llssite_cfg_file.load(false);
376 attempt_count++;
377
378 // After waiting for the specified time, ask the user whether they want to wait for that long again
379 if (attempt_count == WAITING_TIME) {
380 int try_again = JOptionPane.showConfirmDialog(Gatherer.g_man, Dictionary.get("Server.StartUpTimeOut", Integer.toString(WAITING_TIME)),
381 Dictionary.get("General.Warning"), JOptionPane.YES_NO_OPTION);
382 if (try_again == JOptionPane.NO_OPTION) {
383 return;
384 }
385 attempt_count = 0;
386 }
387 }
388
389 // Ta-da. Now the url should be available
390 try {
391 Configuration.library_url = new URL(llssite_cfg_file.getURL());
392 }
393 catch (MalformedURLException exception) {
394 DebugStream.printStackTrace(exception);
395 }
396
397 // A quick test involves opening a connection to get the home page for this collection
398 try {
399 DebugStream.println("Try connecting to server on config url: '" + Configuration.library_url + "'");
400 URLConnection connection = Configuration.library_url.openConnection();
401 connection.getContent();
402 running = true;
403 }
404 catch (IOException bad_url_connection) {
405 throw bad_url_connection;
406 }
407
408
409 }
410
411 /** Returns true if we're waiting on the user to click on Enter Library button
412 * in an independently launched GSI (one not launched by GLI). */
413 static public boolean isURLPending() {
414 //if(Configuration.library_url != null) {
415 //System.err.println("**** Configuration.library_url: " + Configuration.library_url );
416 //return false; // don't need to do anything as we already have the url
417 //}
418
419 llssite_cfg_file.load(true); // don't force reload, load only if modified
420
421 String url = llssite_cfg_file.getURL();
422
423 if(url != null) {
424 if(url.equals(LLSSiteConfig.URL_PENDING)) {
425 running = false; // imagine if they restarted an external GSI
426 return true;
427 } else {
428 // a valid URL at last
429 try {
430 Configuration.library_url = new URL(url);
431 running = true;
432 }
433 catch (MalformedURLException exception) {
434 running = false;
435 exception.printStackTrace();
436 DebugStream.printStackTrace(exception);
437 }
438 return false;
439 }
440 }
441
442 // If either the URL is null--which means no independent GSI (Greenstone server interface
443 // app) was launched--or if the 'URL' doesn't say it's pending, then we're not waiting
444 return false;
445 }
446
447 static public void checkServerRunning() {
448 if (!running) return; // don't worry about it if it's not supposed to be running
449 llssite_cfg_file.load(true); // don't force reload, load only if modified
450
451 String url = llssite_cfg_file.getURL();
452 if(url != null) {
453 if(url.equals(LLSSiteConfig.URL_PENDING)) {
454 running = false;
455 return;
456 }
457
458 // else, valid URL:
459 try {
460 Configuration.library_url = new URL(url);
461 running = true;
462 }
463 catch (MalformedURLException exception) {
464 running = false;
465 DebugStream.printStackTrace(exception);
466 exception.printStackTrace();
467 }
468 }
469 else { // NO URL in current ConfigFile, check the other configfile for a URL
470 // to see if the server was restarted using that file.
471 // Otherwise need to restart the server again with GLIsite.cfg
472 llssite_cfg_file.save(); // save the configfile, because we may be reloading another
473
474 if(llssite_cfg_file.usingLLS_configFile()) { // if a GSI is already using llssite_cfg, this would have loaded it in
475 url = llssite_cfg_file.getURL(); //if(isURLPending()) {
476 if(url.equals(LLSSiteConfig.URL_PENDING)) {
477 running = false;
478 } else {
479 running = true;
480 }
481 return; // don't need to launch the server, one has been independently launched
482 } else {
483 // else we try using the glisite configfile
484 llssite_cfg_file.useGLISiteCfg(local_library_server_file);
485 //llssite_cfg_file.set();
486
487 // Spawn local library server process
488 running = false;
489 String local_library_server_command = local_library_server_file.getAbsolutePath() + getExtraLaunchArguments(llssite_cfg_file);
490 if(Utility.isWindows()) {
491 local_library_server_command = "cmd.exe /c start \"GSI\" " + local_library_server_command;
492 }
493 Gatherer.spawnApplication(local_library_server_command, ID);
494 try {
495 testServerRunning(); // don't return until the webserver is up and running
496 } catch (IOException bad_url_connection) {
497 DebugStream.println("Can't connect to server on address " + Configuration.library_url);
498 running = false;
499 }
500 }
501 }
502 }
503
504 static private class OneSecondWait
505 {
506 public OneSecondWait()
507 {
508 synchronized(this) {
509 try {
510 wait(1000);
511 }
512 catch (InterruptedException exception) {
513 }
514 }
515 }
516 }
517
518
519 static public class LLSSiteConfig
520 extends LinkedHashMap
521 {
522 private File configFile;
523
524 private File llssite_cfg;
525 private File glisite_cfg;
526 private String autoenter_initial;
527 private String start_browser_initial;
528
529 private long lastModified = 0;
530
531 static final private String AUTOENTER = "autoenter";
532 static final private String COLON = ":";
533 static final private String ENTERLIB = "enterlib";
534 static final private String FALSE = "0";
535 static final private String GLISITE_CFG = "glisite.cfg";
536 static final private String GSDL = "greenstone"; // httpprefix is no longer /gsdl but /greenstone
537 static final private String LLSSITE_CFG = "llssite.cfg";
538 static final private String LOCAL_HOST = "http://localhost";
539 static final private String PORTNUMBER = "portnumber";
540 static final private String SEPARATOR = "/";
541 static final private String SPECIFIC_CONFIG = "--config=";
542 static final private String STARTBROWSER = "start_browser";
543 static final private String TRUE = "1";
544 static final private String URL = "url";
545
546 static final public String URL_PENDING = "URL_pending";
547
548
549 public LLSSiteConfig(File server_exe) {
550 debug("New LLSSiteConfig for: " + server_exe.getAbsolutePath());
551
552 llssite_cfg = new File(server_exe.getParentFile(), LLSSITE_CFG);
553 glisite_cfg = new File(server_exe.getParentFile(), GLISITE_CFG);
554
555 configFile = null;
556
557 autoenter_initial = null;
558 start_browser_initial = null;
559
560 // first test if server was started independently of GLI
561 // if so, the config file we'd be using would be llssite.cfg
562 if(!usingLLS_configFile()) { // if we were using llssite_cfg, this would have loaded it in
563 // else we try using the glisite configfile
564 useGLISiteCfg(server_exe);
565 }
566 }
567
568 /** Tries to get a glisite.cfg file and then loads it, setting it as the configFile */
569 public void useGLISiteCfg(File server_exe)
570 {
571 if(!glisite_cfg.exists()) { // create it from the templates or the llssite.cfg file
572
573 File llssite_cfg_in = new File(server_exe.getParentFile(), LLSSITE_CFG+".in");
574 File glisite_cfg_in = new File(server_exe.getParentFile(), GLISITE_CFG+".in");
575
576 // need to generate glisite_cfg from glisite_cfg_in, llssite_cfg or llssite.cfg.in
577 if(glisite_cfg_in.exists()) {
578 copyConfigFile(glisite_cfg_in, glisite_cfg, false);
579 }
580 else if(llssite_cfg_in.exists()) {
581 copyConfigFile(llssite_cfg_in, glisite_cfg_in, true); // adjust for glisite.cfg
582 copyConfigFile(glisite_cfg_in, glisite_cfg, false);
583 }
584 else if(llssite_cfg.exists()) {
585 copyConfigFile(llssite_cfg, glisite_cfg, true); // adjust for glisite.cfg
586 }
587 else {
588 debug("Neither the file glisite.cfg nor llssite.cfg can be found!");
589 }
590 }
591 // use the config file now
592 if(glisite_cfg.exists()) {
593 configFile = glisite_cfg;
594 load(false); // force reload
595 lastModified = configFile.lastModified();
596 }
597 }
598
599 /** Tests whether the server interface is up, running independently of GLI
600 * If so, we don't need to launch the server interface.
601 * The server interface may not have started up the server itself though
602 * (in which case the server URL would be URL_PENDING).
603 * This method returns true if the server interface has already started
604 * and, if so, it would have loaded in the llssite_cfg configFile.
605 */
606 public boolean usingLLS_configFile() {
607 if(!llssite_cfg.exists()) {
608 return false;
609 }
610
611 // Now to check if the configfile contains the URL line
612 configFile = llssite_cfg;
613 load(false); // force load
614
615 if(getURL() == null) {
616 configFile = null;
617 clear(); // we're not using llssite_cfg, so clear the values we just read
618 return false;
619 }
620
621 lastModified = configFile.lastModified();
622 return true;
623 }
624
625 /** To test we've actually instantiated this object meaningfully. If so, then configFile is set */
626 public boolean isConfigFileSet() {
627 return (configFile != null && configFile.exists());
628 }
629
630 /** @return true if GSI was started up independently and outside of GLI.
631 * In such a case, GLI would be using llssite_cfg. */
632 public boolean isIndependentGSI() {
633 return (configFile == llssite_cfg);
634 }
635
636 public boolean exists() {
637 return configFile.exists();
638 }
639
640 public String getLocalHostURL() {
641 StringBuffer url = new StringBuffer(LOCAL_HOST);
642 url.append(COLON);
643 url.append((String)get(PORTNUMBER));
644 String enterlib = (String)get(ENTERLIB);
645 if(enterlib == null || enterlib.length() == 0) {
646 // Use the default /gsdl and hope for the best.
647 url.append(SEPARATOR);
648 url.append(GSDL);
649 }
650 else {
651 if(!enterlib.startsWith(SEPARATOR)) {
652 url.append(SEPARATOR);
653 }
654 url.append(enterlib);
655 }
656 enterlib = null;
657 debug("Found Local Library Address: " + url.toString());
658 return url.toString();
659 }
660
661 /** @return the cmd-line parameter for the configfile used to launch
662 * the server through GLI: --config <glisite.cfg/llssite.cfg file path>. */
663 public String getSiteConfigFilename() {
664 return SPECIFIC_CONFIG + configFile.getAbsolutePath();
665 }
666
667 public String getURL() {
668 // URL is made from url and portnumber
669 String url = (String) get(URL);
670
671 // server interface is already up, independent of GLI
672 // but it has not started the server (hence URL is pending)
673 if(url != null && url.equals(URL_PENDING)) {
674 return url;
675 }
676
677 if(!isPersistentServer) {
678 return url;
679 }
680
681 if(url != null) {
682 StringBuffer temp = new StringBuffer(url);
683 temp.append(COLON);
684 temp.append((String)get(PORTNUMBER));
685 String enterlib = (String)get(ENTERLIB);
686 if(enterlib == null || enterlib.length() == 0) {
687 // Use the default /greenstone prefix and hope for the best.
688 temp.append(SEPARATOR);
689 temp.append(GSDL);
690 }
691 else {
692 if(!enterlib.startsWith(SEPARATOR)) {
693 temp.append(SEPARATOR);
694 }
695 temp.append(enterlib);
696 }
697 enterlib = null;
698 url = temp.toString();
699 }
700 debug("Found Local Library Address: " + url);
701 return url;
702 }
703
704 public boolean isModified() {
705 return (lastModified != configFile.lastModified());
706 }
707
708 public void load(boolean reloadOnlyIfModified) {
709
710 if(configFile == null) {
711 debug(configFile.getAbsolutePath() + " cannot be found!");
712 }
713
714 if(isModified()) {
715 lastModified = configFile.lastModified();
716 } else if(reloadOnlyIfModified) {
717 return; // asked to reload only if modified. Don't reload since not modified
718 }
719
720 if(configFile.exists()) {
721 debug("Load: " + configFile.getAbsolutePath());
722 clear();
723 try {
724 BufferedReader in = new BufferedReader(new FileReader(configFile));
725 String line = null;
726 while((line = in.readLine()) != null) {
727 String key = null;
728 String value = null;
729 int index = -1;
730 if((index = line.indexOf("=")) != -1 && line.length() >= index + 1) {
731 key = line.substring(0, index);
732 value = line.substring(index + 1);
733 }
734 else {
735 key = line;
736 }
737 put(key, value);
738 }
739 in.close();
740 }
741 catch (Exception error) {
742 error.printStackTrace();
743 }
744 }
745 else {
746 debug(configFile.getAbsolutePath() + " cannot be found!");
747 }
748 }
749
750 /** Restore the autoenter value to its initial value, and remove url if present. */
751 public void restore() {
752 if(configFile != null) {
753 // Delete the file
754 configFile.delete();
755 }
756 else {
757 debug("Restore Initial Settings");
758 put(AUTOENTER, autoenter_initial);
759 put(STARTBROWSER, start_browser_initial);
760 remove(URL);
761 save();
762 }
763 }
764
765 public void set() {
766 debug("Set Session Settings");
767 if(autoenter_initial == null) {
768 autoenter_initial = (String) get(AUTOENTER);
769 debug("Remember autoenter was: " + autoenter_initial);
770 }
771 put(AUTOENTER, TRUE);
772 if(start_browser_initial == null) {
773 start_browser_initial = (String) get(STARTBROWSER);
774 debug("Remember start_browser was: " + start_browser_initial);
775 }
776 put(STARTBROWSER, FALSE);
777 save();
778 }
779
780 private void debug(String message) {
781 ///ystem.err.println(message);
782 }
783
784 private void save() {
785 //debug("Save: " + llssite_cfg.getAbsolutePath());
786 debug("Save: " + configFile.getAbsolutePath());
787 try {
788 //BufferedWriter out = new BufferedWriter(new FileWriter(llssite_cfg, false));
789 BufferedWriter out = new BufferedWriter(new FileWriter(configFile, false));
790 for(Iterator keys = keySet().iterator(); keys.hasNext(); ) {
791 String key = (String) keys.next();
792 String value = (String) get(key);
793 out.write(key, 0, key.length());
794 if(value != null) {
795 out.write('=');
796
797 // if the server is using llssite.cfg, don't overwrite its default
798 // autoenter and startbrowser values
799 if(configFile == llssite_cfg && (key == AUTOENTER || key == STARTBROWSER)) {
800 if(key == AUTOENTER) {
801 out.write(autoenter_initial, 0, autoenter_initial.length());
802 } else { // STARTBROWSER
803 out.write(start_browser_initial, 0, start_browser_initial.length());
804 }
805 } else {
806 out.write(value, 0, value.length());
807 }
808 }
809 out.newLine();
810 }
811 out.flush();
812 out.close();
813 }
814 catch (Exception error) {
815 error.printStackTrace();
816 }
817 }
818
819 private static void copyConfigFile(File source_cfg, File dest_cfg, boolean setToGliSiteDefaults) {
820 // source_cfg file should exist
821 // dest_cfg file should not yet exist
822 // If setToGliSiteDefaults is true, then GLIsite.cfg's default configuration
823 // is applied to concerned lines: autoenter=1, and startbrowser=0
824
825 try {
826 BufferedReader in = new BufferedReader(new FileReader(source_cfg));
827 BufferedWriter out = new BufferedWriter(new FileWriter(dest_cfg, false));
828
829 String line = null;
830 while((line = in.readLine()) != null) {
831
832 if(setToGliSiteDefaults) {
833 if(line.startsWith(AUTOENTER)) {
834 line = AUTOENTER+"=1";
835 }
836 else if(line.startsWith(STARTBROWSER)) {
837 line = STARTBROWSER+"=0";
838 }
839 }
840
841 // write out the line
842 out.write(line + "\n");
843 }
844
845 out.flush();
846 in.close();
847 out.close();
848 } catch(Exception e) {
849 System.err.println("Exception occurred when trying to copy the config file "
850 + source_cfg.getName() + " to " + dest_cfg.getName() + ": " + e);
851 e.printStackTrace();
852 }
853 }
854 }
855}
Note: See TracBrowser for help on using the repository browser.