source: greenstone3/trunk/src/java/org/greenstone/server/Server2.java@ 19241

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

Timeout length set in a variable. Can be changed (but better to be consistent with GLI's LocalLibraryServer.java code).

File size: 11.2 KB
Line 
1
2package org.greenstone.server;
3
4import java.io.BufferedReader;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileOutputStream;
8import java.io.InputStreamReader;
9import java.io.IOException;
10import java.net.ServerSocket;
11import java.net.Socket;
12import java.net.URL;
13//import java.net.URLConnection;
14import java.util.Properties;
15import java.util.ArrayList;
16
17import org.apache.log4j.*;
18
19import org.greenstone.server.BaseServer;
20import org.greenstone.server.BaseProperty;
21
22public class Server2 extends BaseServer
23{
24 private static final int WAITING_TIME = 60; // time to wait and check for whether the server is running
25
26 protected String libraryURL;
27
28 private class QuitListener extends Thread
29 {
30 int quitPort = -1;
31 ServerSocket serverSocket = null;
32
33 public QuitListener(int quitport) throws Exception {
34 ///Server2.this.recordSuccess("In QuitListener constructor");
35 this.quitPort = quitport;
36 serverSocket = new ServerSocket(quitPort);
37 }
38
39 public void run() {
40 Socket connection = null;
41
42 try {
43 // wait for a connection
44 connection = serverSocket.accept();
45
46 // read input
47 try {
48 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
49 String line = null;
50 if((line = reader.readLine()) != null) {
51 if(line.equals("QUIT")) {
52 // Server2.this.recordSuccess("In QuitListener - line is QUIT");
53 reader.close();
54 reader = null;
55 serverSocket.close();
56 serverSocket = null;
57 }
58 }
59 } catch(Exception e) {
60 Server2.this.recordError("Exception in QuitListener thread.");
61 } finally {
62 Server2.this.stop();
63 System.exit(0);
64 }
65 } catch(IOException ioe) {
66 Server2.this.recordError("Server2.QuitListener: Unable to make the connection with the client socket." + ioe);
67 }
68 }
69 }
70
71
72 public Server2(String gsdl2_home, String lang, String configfile, int quitPort)
73 {
74 super(gsdl2_home, lang, configfile, "etc"+File.separator+"logs-gsi");
75 // configfile can be either glisite.cfg or llssite.cfg
76
77 Property = new Server2Property();
78
79 String frame_title = dictionary.get("ServerControl.Frame_Title");
80 server_control_ = new Server2Control(this,frame_title);
81
82 /* Make command tagets for managing Web server */
83 START_CMD = "web-start";
84 RESTART_CMD = "web-restart";
85 CONFIGURE_CMD = "configure-web " + configfile;
86 STOP_CMD = "web-stop";
87
88 // now we can monitor for the quit command if applicable
89 if(quitPort != -1) {
90 // First check if given port is within the range of allowed ports
91 if(PortFinder.isAssignablePortNumber(quitPort)) {
92 try {
93 new QuitListener(quitPort).start();
94 } catch(Exception e) {
95 Server2.this.recordError("Exception constructing the QuitListener thread.");
96 }
97 }
98 else {
99 recordError("QuitPort provided is not within acceptable range: ("
100 + PortFinder.PORTS_RESERVED + " - " + PortFinder.MAX_PORT + "]" );
101 quitPort = -1;
102 }
103 }
104
105 autoStart();
106 }
107
108 // Prepare the log4j.properties for GS2
109 protected void initLogger() {
110
111 String libjavaFolder = gsdl_home+File.separator+"lib"+File.separator+"java"+File.separator;
112 File propsFile = new File(libjavaFolder+"log4j.properties");
113
114 // create it from the template file log4j.properties.in
115 if(!propsFile.exists()) {
116 try {
117 // need to set gsdl2.home property's value to be gsdl_home,
118 // so that the location of the log files gets resolved correctly
119
120 // load the template log4j.properties.in file into logProps
121 FileInputStream infile = new FileInputStream(new File(libjavaFolder+"log4j.properties.in"));
122 if(infile != null) {
123 Properties logProps = new Properties();
124 logProps.load(infile);
125 infile.close();
126
127 // set gsdl3.home to gsdl_home
128 logProps.setProperty("gsdl2.home", gsdl_home);
129
130 // write the customised properties out to a custom log4j.properties file
131 FileOutputStream outfile = new FileOutputStream(propsFile);
132 if(outfile != null) {
133 logProps.store(outfile, "Customised log4j.properties file");
134 outfile.close();
135 } else {
136 System.err.println("Could not store properties file " + propsFile + " for Server2.");
137 }
138 }
139 } catch(Exception e) {
140 System.err.println("Exception occurred when custom-configuring the logger for Server2.\n" + e);
141 }
142 }
143
144 // now configure the logger with the custom log4j.properties file
145 if(propsFile.exists()) {
146 PropertyConfigurator.configure(propsFile.getAbsolutePath());
147 } else {
148 System.err.println("Could not create properties file " + propsFile + " for Server2.");
149 }
150 }
151
152
153 protected int runTarget(String cmd)
154 {
155 RunMake runMake = new RunMake();
156 runMake.setTargetCmd(cmd);
157 runMake.run();
158 return runMake.getTargetState();
159 }
160
161 public String getBrowserURL() {
162 return libraryURL;
163 }
164
165 // works out the library URL again
166 public void reload() {
167 // default values, to be replaced with what's in gsdlsite.cfg
168 String host = "localhost";
169 String port = "80";
170 String gwcgi;
171 String httpprefix = "greenstone";
172 String suffix = "/cgi-bin/library.cgi";
173
174 // get the prefix from the gsdlsite.cfg and build.properties files
175 // (port number and servername)
176 try{
177 File gsdlsite_cfg = new File(gsdl_home + File.separator + "cgi-bin" + File.separator + "gsdlsite.cfg");
178 FileInputStream fin = new FileInputStream(gsdlsite_cfg);
179 Properties gsdlProperties = new Properties();
180 if(fin != null) {
181 gsdlProperties.load(fin);
182
183 gwcgi = gsdlProperties.getProperty("gwcgi");
184 if(gwcgi != null) {
185 suffix = gwcgi;
186 } else {
187 httpprefix = gsdlProperties.getProperty("httpprefix", httpprefix);
188 suffix = httpprefix + suffix;
189 }
190 fin.close();
191 } else {
192 recordError("Could not open gsdlsite_cfg for reading, using default library prefix.");
193 }
194 //reloadConfigProperties();
195 port = config_properties.getProperty("portnumber", port);
196 } catch(Exception e) {
197 recordError("Exception trying to load properties from gsdlsite_cfg. Using default library prefix.", e);
198 suffix = httpprefix + suffix;
199 }
200
201 libraryURL = "http://" + host + ":" + port + suffix;
202 }
203
204 public void reloadConfigProperties() {
205 super.reloadConfigProperties();
206
207 // make sure the port is okay, otherwise find another port
208 // first choice is port 80, second choice starts at 8282
209 String port = config_properties.getProperty("portnumber", "80");
210 int portDefault = 8282;
211 try {
212 int portNum = Integer.parseInt(port);
213
214 if(!PortFinder.isPortAvailable(portNum)) {
215
216 PortFinder portFinder = new PortFinder(portDefault, 101);
217 portNum = portFinder.findPortInRange();
218 port = (portNum == -1) ? Integer.toString(portDefault) : Integer.toString(portNum);
219 config_properties.setProperty("portnumber", port); // store the correct port
220
221 // write this updated port to the config file, since the configure target uses the file to run
222 ScriptReadWrite scriptReadWrite = new ScriptReadWrite();
223 ArrayList fileLines = scriptReadWrite.readInFile(BaseServer.config_properties_file);
224 scriptReadWrite.replaceOrAddLine(fileLines, "portnumber", port, false); // write the correct port
225 scriptReadWrite.writeOutFile(config_properties_file, fileLines);
226
227 configure_required_ = true;
228 }
229 } catch (Exception e) {
230 recordError("Exception in Server2.reload(): " + e.getMessage());
231 port = Integer.toString(portDefault);
232 }
233
234 }
235
236
237 // About to stop the webserver
238 // Custom GS2 action: remove the url property from the config file
239 protected void preStop() {
240 ScriptReadWrite scriptReadWrite = new ScriptReadWrite();
241 ArrayList fileLines = scriptReadWrite.readInFile(BaseServer.config_properties_file);
242 if (fileLines.contains("url="+getBrowserURL())) {
243 // would be last element, remove it:
244 fileLines.remove(fileLines.size()-1);
245 }
246 scriptReadWrite.writeOutFile(config_properties_file, fileLines);
247 }
248
249 // Called when the URL has been changed (called after a reload() and starting the server).
250 // By the time we get here, reload() would already have been called and have set
251 // both the port and worked out libraryURL
252 // This method needs to write the URL to the configfile since things should work
253 // like GS2's Local Lib Server for Windows
254 protected void postStart() {
255
256 URL libURL = null;
257 try {
258 libURL = new URL(libraryURL);
259 } catch (Exception e) {
260 recordError("Unable to convert library URL string into a valid URL, Server2.java." + e);
261 }
262
263 // 1. Test that the server is running at the libraryURL before writing it out to glisite.cfg/configfile
264 // A quick test involves opening a connection to get the home page for this collection
265 if(libURL != null) {
266
267 boolean ready = false;
268 for(int i = 0; i < WAITING_TIME && !ready; i++) {
269 try {
270 libURL.openConnection();
271 //URLConnection connection = new URL(libraryURL).openConnection();
272 //connection.getContent();
273 ready = true;
274 recordSuccess("Try connecting to server on url: '" + libraryURL + "'");
275 } catch (IOException bad_url_connection) {
276 // keep looping
277 recordSuccess("NOT YET CONNECTED. Waiting to try again...");
278 try {
279 Thread.sleep(1000);
280 } catch (InterruptedException ie) {
281 ready = true;
282 recordError("Unexpected: got an InterruptedException in sleeping thread, Server2.java." + ie);
283 }
284 } catch (Exception e) {
285 ready = true;
286 recordError("Got an Exception while waiting for the connection to become live, Server2.java." + e);
287 }
288 }
289 }
290
291 // 2. Now write the URL to the config file
292 String port = config_properties.getProperty("portnumber");
293
294 ScriptReadWrite scriptReadWrite = new ScriptReadWrite();
295 ArrayList fileLines = scriptReadWrite.readInFile(BaseServer.config_properties_file);
296 scriptReadWrite.replaceOrAddLine(fileLines, "url", libraryURL, true);
297 scriptReadWrite.replaceOrAddLine(fileLines, "portnumber", port, false); // write the correct port
298 scriptReadWrite.writeOutFile(config_properties_file, fileLines);
299 }
300
301
302 public static void main (String[] args)
303 {
304 if ((args.length < 1) || (args.length > 4)) {
305 System.err.println(
306 "Usage: java org.greenstone.server.Server2 <gsdl2-home-dir> [lang] [--config=configfile] [--quitport=portNum]");
307 System.exit(1);
308 }
309
310 String gsdl2_home = args[0];
311 File gsdl2_dir = new File(gsdl2_home);
312 if (!gsdl2_dir.isDirectory()) {
313 System.err.println("gsdl-home-dir directory does not exist!");
314 System.exit(1);
315 }
316
317 String lang = (args.length>=2) ? args[1] : "en";
318
319 // if no config file is given, then the following defaults to llssite.cfg
320 String configfile = (args.length>=3 && args[2].startsWith("--config=")) ? args[2] : gsdl2_home+File.separator+"llssite.cfg";
321 int equalSign = configfile.indexOf('=');
322 if(equalSign != -1) {
323 configfile = configfile.substring(equalSign+1);
324 }
325
326 String quitport = (args.length == 4 && args[3].startsWith("--quitport=")) ? args[3] : "";
327 equalSign = quitport.indexOf('=');
328 int port = -1;
329 if(equalSign != -1) {
330 try {
331 quitport = quitport.substring(equalSign+1);
332 port = Integer.parseInt(quitport);
333 } catch(Exception e) { // parse fails
334 System.err.println("Port must be numeric. Continuing without it.");
335 }
336 }
337
338 //System.err.println("Running server with config file: " + configfile);
339
340 new Server2(gsdl2_home, lang, configfile, port);
341 }
342}
Note: See TracBrowser for help on using the repository browser.