aboutsummaryrefslogtreecommitdiff
path: root/src/uk/org/ury/server/Server.java
blob: 8a25916bd87148507af6f4a3c229bc472b42985d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
 * 
 */
package uk.org.ury.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLDecoder;

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import uk.org.ury.config.ConfigReader;
import uk.org.ury.database.DatabaseDriver;
import uk.org.ury.database.UserClass;
import uk.org.ury.database.exceptions.ConnectionFailureException;
import uk.org.ury.database.exceptions.MissingCredentialsException;
import uk.org.ury.server.exceptions.HandleFailureException;

/**
 * The unified URY server, accepting requests over HTTP.
 * 
 * @author  Matt Windsor
 */

public class Server
{

  private ServerSocket serverSocket;
  
  private static final String HTTP_VERSION   = "HTTP/1.1";
  private static final String SERVER_VERSION = "SLUT 0.0";
  private static final String DOCTYPE        = 
      "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""
    + "\"http://www.w3.org/TR/html4/strict.dtd\">";
  private static final String INDEX_HTML     =
      "\n<html>"
    + "\n  <head>"
    + "\n    <title>" + SERVER_VERSION + "</title>"
    + "\n  </head>"
    + "\n  <body>"
    + "\n    <h1>Welcome to the " + SERVER_VERSION + " server</h1>"
    + "\n    <p>This server exposes a class-based API for accessing"
    + "\n    the internals of the " + SERVER_VERSION + " system.</p>"
    + "\n    <p>See the documentation for details.</p>"
    + "\n  </body>"
    + "\n</html>";
  
  
  /**
   * The main method, which serves to create a server.
   * 
   * @param args  The argument vector.
   */
  
  public static void
  main (String[] args)
  {
    Server srv = new Server ();
    srv.run ();
  }

  
  /**
   * Run the server.
   */
  
  private void
  run ()
  {
    try
      {
        serverSocket = new ServerSocket (8000);
      }
    catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace ();
      }
    
    Socket clientSocket = null;
    
    while (true)
    {
      System.out.println ("Accepting connections... bring 'em on!");
      
      try
      {
        clientSocket = serverSocket.accept ();
      }
      catch (IOException e)
      {
        System.out.println ("SLUT: Accept failed on port 8000.  I'm bailing.");
        System.exit (-1);
      }
    
      try
        {
          doConnection (clientSocket);
        }
      catch (IOException e)
        {
          e.printStackTrace ();
        }
      finally
        {
          try
            {
              clientSocket.close ();
            }
          catch (IOException e)
            {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
        }
    }
  }

  
  public void
  doConnection (Socket clientSocket)
  throws IOException
  {
    PrintWriter out = new PrintWriter (clientSocket.getOutputStream(), true);
    BufferedReader in = new BufferedReader (new InputStreamReader (
                                            clientSocket.getInputStream()));
    String inputLine;

    //initiate conversation with client
    
    List<String> buffer = new ArrayList<String> ();
    
    
    for (inputLine = in.readLine (); inputLine != null; inputLine = in.readLine ())
      {
        if (inputLine.equals (""))
          break;
        
        buffer.add (inputLine);

        if (inputLine.startsWith ("Expect:") 
            && inputLine.split (":")[1].startsWith ("100-continue"))
          out.print ("HTTP/1.1 100 Continue\n\r\n");

        out.flush ();
      }
    
    processBuffer (buffer, out);
    
    out.flush ();
    out.close ();
    in.close ();
    
    System.out.println ("Just finished with this one...");
  }
  
  
  public void
  processBuffer (List<String> buffer, PrintWriter out)
  {
    String requestStart = buffer.get (0);
    
    System.out.println (requestStart);
    
    if (requestStart.startsWith ("GET"))
      {
        System.out.println ("That was a GET..."); 
        handleGet (buffer, out);
      }
    else
      {
        System.out.println ("Uh-oh! I don't know what to do!");
        
        out.println (HTTP_VERSION + " 501 Not Implemented");
        out.println ("Connection: close");
        out.print ("\r\n");
      }
  }
  
  public void
  handleGet (List<String> buffer, PrintWriter out)
  {
    String[] getsplit = buffer.get (0).split (" ");
    String   path     = getsplit[1];
    
    if (path.equals ("/index.html")
        || path.equals ("/"))
      {
        // Someone's trying to get the index page!
        // Humour them.
        
        out.println (HTTP_VERSION + " 200 OK");
        out.println ("Connection: close");
        out.print ("\r\n");
        
        out.println (DOCTYPE + INDEX_HTML);
      }
    else
      {
        // Convert this into a URL and fan out the various parts of it.
        
        URL pathURL = null;
        
        try
          {
            pathURL = new URL ("http://localhost" + path);
          }
        catch (MalformedURLException e1)
          {
            serveError (400, "Malformed URL.", out);
          }
        
        
        String className    = "uk.org.ury" + pathURL.getPath ().replace ('/', '.');
        System.out.println (className);
        Class<?> newClass   = null;
 
        
        try
          {
            newClass = Class.forName (className);
          }
        catch (ClassNotFoundException e)
          {
            serveError (404, "Class " + className + " not found.", out);
            return;
          }
        
        if (RequestHandler.class.isAssignableFrom (newClass))
          {
            String queryString = pathURL.getQuery ();
            Map<String, String> parameters;
            try
              {
                parameters = parseQueryString (queryString);
              }
            catch (UnsupportedEncodingException e)
              {
                serveError (500, "URL decode failure for class "
                    + className
                    + " (" + e.getMessage () + ").", out);
                return;
              }
            
            List<String> response;
            
            try
              {
                RequestHandler srh = ((RequestHandler) newClass.newInstance ());
                response = srh.handleGetRequest (parameters, this);
              }
            catch (InstantiationException e)
              {
                serveError (500, "Instantiation exception for class "
                            + className
                            + " (" + e.getMessage () + ").", out);
                return;
              }
            catch (IllegalAccessException e)
              {
                serveError (500, "Illegal access exception for class "
                            + className 
                            + " (" + e.getMessage () + ").", out);
                return;
              }
            catch (HandleFailureException e)
              {
                serveError (500, "Failed to handle request for class "
                            + className
                            + " (" + e.getMessage () + ").", out);
                return;
              }
            
            // If we made it this far, the response is A-OK.
            
            out.println (HTTP_VERSION + " 200 OK");
            out.println ("Content-Type: text/plain");
            out.print ("\r\n");
            
            out.println ("START");
            
            for (String line : response)
              out.println (line);
            
            out.println ("END");
            
            out.flush ();            
          }
        else
          {
            serveError (404, "Class " + className + " does not handle requests.", out);
            return;
          }
      }
  }
  
  
  /**
   * Serve a HTTP plain-text error.
   * 
   * @param code    HTTP status code to use.
   * @param reason  The reason to display to the client.
   * @param out     The output stream.
   */
  
  private void
  serveError (int code, String reason, PrintWriter out)
  {
    String errorStatus = "";
    
    switch (code)
      {
      case 400:
        errorStatus = "400 Bad Request";
        break;
      case 404:
        errorStatus = "404 Not Found";
        break;
      default:
        errorStatus = "500 Internal Server Error";
        break;
      }
    
    out.println (HTTP_VERSION + " " + errorStatus);
    out.println ("Content-Type: text/plain");
    out.println ("Connection: close");
    out.print ("\r\n");
   
    out.println ("ERROR: " + reason);    
    out.flush ();
  }
  
  
  /**
   * Parse a query string, populating a key-value map of the 
   * URL-unescaped results.
   * 
   * @param query  The query string to parse.
   * 
   * @return       A map associating parameter keys and values.
   * 
   * @throws       UnsupportedEncodingException if the URL decoder
   *               fails.
   */
  
  public Map<String, String>
  parseQueryString (String query)
  throws UnsupportedEncodingException
  {
    Map<String, String> params = new HashMap<String, String> ();
    
    // At least one parameter
    if (query != null
        && query.endsWith ("&") == false)
      {
        String[] qsplit = {query};
        
        // More than one parameter - split the query.
        if (query.contains ("&"))
          qsplit = query.split ("&");

        
        for (String param : qsplit)
          {
            // Has a value
            if (param.contains ("=")
                && param.endsWith ("=") == false)
              {
                String[] paramsplit = param.split ("=");
                params.put (URLDecoder.decode (paramsplit[0], "UTF-8"), 
                            URLDecoder.decode (paramsplit[1], "UTF-8"));
              }
            // Doesn't have a value
            else if (param.contains ("=") == false)
              {
                params.put (URLDecoder.decode (param, "UTF-8"), null);
              }
          }
      }
    
    return params;
  }
  
  
  /**
   * Get a database connection using the given user class.
   * 
   * @param  userClass  The user class to get a connection for.
   * 
   * @return            a database connection, which may or may not 
   *                    have been created on this call.
   *                    
   * @throw             MissingCredentialsException if the credentials
   *                    for the given userclass are missing.
   * 
   * @throw             ConnectionFailureException if the connection 
   *                    failed.
   */
  
  public DatabaseDriver
  getDatabaseConnection (UserClass userClass)
  throws MissingCredentialsException, ConnectionFailureException
  {
    // TODO: Singleton
  
    ConfigReader config = new ConfigReader ("res/conf.xml");
    
    return new DatabaseDriver (config, UserClass.READ_ONLY);
  }


  /**
   * @return  the version string of the server.
   */
  
  public String
  getVersion ()
  {
    return SERVER_VERSION;
  }
}