Debian Codegraph @

src/java/org/astrogrid/samp/httpd/HttpServer.java

raw
1 package org.astrogrid.samp.httpd;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.InputStream;
6 import java.io.IOException;
7 import java.io.OutputStream;
8 import java.io.PrintStream;
9 import java.net.MalformedURLException;
10 import java.net.ServerSocket;
11 import java.net.Socket;
12 import java.net.SocketAddress;
13 import java.net.URL;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.Iterator;
18 import java.util.LinkedHashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23 import java.util.logging.Logger;
24 import java.util.logging.Level;
25 import javax.net.ssl.SSLServerSocket;
26 import org.astrogrid.samp.SampUtils;
27
28 /**
29 * Simple modular HTTP server.
30 * One thread is started per request. Connections are not kept open between
31 * requests.
32 * Suitable for very large response bodies, but not for very large
33 * request bodies.
34 * Add one or more {@link HttpServer.Handler}s to serve actual requests.
35 * The protocol version served is HTTP/1.0.
36 *
37 * <p>This class is completely self-contained, so that it can easily be
38 * lifted out and used in other packages if required.
39 *
40 * @author Mark Taylor
41 * @since 21 Aug 2008
42 */
43 public class HttpServer {
44
45 private final ServerSocket serverSocket_;
46 private boolean isDaemon_;
47 private List handlerList_;
48 private final URL baseUrl_;
49 private volatile boolean started_;
50 private volatile boolean stopped_;
51
52 /** Header string for MIME content type. */
53 public static final String HDR_CONTENT_TYPE = "Content-Type";
54 private static final String HDR_CONTENT_LENGTH = "Content-Length";
55
56 /** Status code for OK (200). */
57 public static final int STATUS_OK = 200;
58
59 private static final String URI_REGEX =
60 "([^\\s\\?]*)\\??([^\\s\\?]*)";
61 private static final String HTTP_VERSION_REGEX =
62 "HTTP/[0-9]+\\.[0-9]+";
63 private static final String HTTP_TOKEN_REGEX =
64 "[a-zA-Z0-9_\\.\\-]+";
65
66 private static final Pattern SIMPLE_REQUEST_PATTERN =
67 Pattern.compile( "GET" + " " + "(" + "\\S+" + ")" );
68 private static final Pattern REQUEST_LINE_PATTERN =
69 Pattern.compile( "(" + HTTP_TOKEN_REGEX + ")" // typically GET, HEAD etc
70 + " " + "(" + "\\S+" + ")"
71 + " " + HTTP_VERSION_REGEX );
72 private static final Pattern HEADER_PATTERN =
73 Pattern.compile( "(" + "[^\\s:]+" +")" + ":\\s*(.*)" );
74
75 private static final Logger logger_ =
76 Logger.getLogger( HttpServer.class.getName() );
77
78 /**
79 * Constructs a server based on a given socket.
80 *
81 * @param socket listening socket
82 */
83 public HttpServer( ServerSocket socket ) {
84 serverSocket_ = socket;
85 isDaemon_ = true;
86 handlerList_ = Collections.synchronizedList( new ArrayList() );
87 boolean isTls = socket instanceof SSLServerSocket;
88 String scheme = isTls ? "https" : "http";
89 StringBuffer ubuf = new StringBuffer()
90 .append( scheme )
91 .append( "://" )
92 .append( SampUtils.getLocalhost() );
93 int port = socket.getLocalPort();
94 if ( port != ( isTls ? 443 : 80 ) ) {
95 ubuf.append( ':' )
96 .append( port );
97 }
98 try {
99 baseUrl_ = new URL( ubuf.toString() );
100 }
101 catch ( MalformedURLException e ) {
102 throw new AssertionError( "Bad scheme " + scheme + ": ??" );
103 }
104 }
105
106 /**
107 * Constructs a server based on a default socket, on any free port.
108 */
109 public HttpServer() throws IOException {
110 this( new ServerSocket( 0 ) );
111 }
112
113 /**
114 * Adds a handler which can serve some requests going through this server.
115 *
116 * @param handler handler to add
117 */
118 public void addHandler( Handler handler ) {
119 handlerList_.add( handler );
120 }
121
122 /**
123 * Removes a handler previously added by {@link #addHandler}.
124 *
125 * @param handler handler to remove
126 */
127 public void removeHandler( Handler handler ) {
128 handlerList_.remove( handler );
129 }
130
131 /**
132 * Returns the socket on which this server listens.
133 *
134 * @return server socket
135 */
136 public ServerSocket getSocket() {
137 return serverSocket_;
138 }
139
140 /**
141 * Returns the base URL for this server.
142 *
143 * @return base URL
144 */
145 public URL getBaseUrl() {
146 return baseUrl_;
147 }
148
149 /**
150 * Does the work for providing output corresponding to a given HTTP request.
151 * This implementation calls each Handler in turn and the first one
152 * to provide a non-null response is used.
153 *
154 * @param request represents an HTTP request that has been received
155 * @return represents the content of an HTTP response that should be sent
156 */
157 public Response serve( Request request ) {
158 Handler[] handlers =
159 (Handler[]) handlerList_.toArray( new Handler[ 0 ] );
160 for ( int ih = 0; ih < handlers.length; ih++ ) {
161 Handler handler = handlers[ ih ];
162 Response response = handler.serveRequest( request );
163 if ( response != null ) {
164 return response;
165 }
166 }
167 return createErrorResponse( 404, "No handler for URL" );
168 }
169
170 /**
171 * Determines whether the server thread will be a daemon thread or not.
172 * Must be called before {@link #start} to have an effect.
173 * The default is true.
174 *
175 * @param isDaemon whether server thread will be daemon
176 * @see java.lang.Thread#setDaemon
177 */
178 public void setDaemon( boolean isDaemon ) {
179 isDaemon_ = isDaemon;
180 }
181
182 /**
183 * Starts the server if it is not already started.
184 */
185 public synchronized void start() {
186 if ( ! started_ ) {
187 Thread server = new Thread( "HTTP Server" ) {
188 public void run() {
189 try {
190 while ( ! stopped_ ) {
191 try {
192 final Socket sock = serverSocket_.accept();
193 new Thread( "HTTP Request" ) {
194 public void run() {
195 try {
196 serveRequest( sock );
197 }
198 catch ( Throwable e ) {
199 logger_.log( Level.WARNING,
200 "Httpd error", e );
201 }
202 }
203 }.start();
204 }
205 catch ( IOException e ) {
206 if ( ! stopped_ ) {
207 logger_.log( Level.WARNING,
208 "Socket error", e );
209 }
210 }
211 }
212 }
213 finally {
214 HttpServer.this.stop();
215 }
216 }
217 };
218 server.setDaemon( isDaemon_ );
219 logger_.info( "Server " + getBaseUrl() + " starting" );
220 server.start();
221 started_ = true;
222 logger_.config( "Server " + getBaseUrl() + " started" );
223 }
224 }
225
226 /**
227 * Stops the server if it is currently running. Processing of any requests
228 * which have already been received is completed.
229 */
230 public synchronized void stop() {
231 if ( ! stopped_ ) {
232 stopped_ = true;
233 logger_.info( "Server " + getBaseUrl() + " stopping" );
234 try {
235 serverSocket_.close();
236 }
237 catch ( IOException e ) {
238 logger_.log( Level.WARNING,
239 "Error during server stop: " + e, e );
240 }
241 }
242 }
243
244 /**
245 * Indicates whether this server is currently running.
246 *
247 * @return true if running
248 */
249 public boolean isRunning() {
250 return started_ && ! stopped_;
251 }
252
253 /**
254 * Called by the server thread for each new connection.
255 *
256 * @param sock client connection socket
257 */
258 protected void serveRequest( Socket sock ) throws IOException {
259
260 // Try to generate a request object by examining the socket's
261 // input stream. If that fails, generate a response representing
262 // the error.
263 InputStream in = sock.getInputStream();
264 in = new BufferedInputStream( in );
265 Response response = null;
266 Request request = null;
267 try {
268 request = parseRequest( in, sock.getRemoteSocketAddress() );
269
270 // If there was no input, make no response at all.
271 if ( request == null ) {
272 return;
273 }
274 }
275 catch ( HttpException e ) {
276 response = e.createResponse();
277 }
278 catch ( IOException e ) {
279 response = createErrorResponse( 400, "I/O error", e );
280 }
281 catch ( Throwable e ) {
282 response = createErrorResponse( 500, "Server error", e );
283 }
284
285 // If we have a request (and hence no error response) process it to
286 // obtain a response object.
287 if ( response == null ) {
288 assert request != null;
289 try {
290 response = serve( request );
291 }
292 catch ( Throwable e ) {
293 response = createErrorResponse( 500, e.toString(), e );
294 }
295 }
296 final Level level;
297 switch ( response.getStatusCode() ) {
298 case 200:
299 level = Level.CONFIG;
300 break;
301 case 404:
302 level = Level.INFO;
303 break;
304 default:
305 level = Level.WARNING;
306 }
307 if ( logger_.isLoggable( level ) ) {
308 StringBuffer sbuf = new StringBuffer();
309 if ( request != null ) {
310 sbuf.append( request.getMethod() )
311 .append( ' ' )
312 .append( request.getUrl() );
313 }
314 else {
315 sbuf.append( "<bad-request>" );
316 }
317 sbuf.append( " --> " )
318 .append( response.statusCode_ )
319 .append( ' ' )
320 .append( response.statusPhrase_ );
321 logger_.log( level, sbuf.toString() );
322 }
323
324 // Send the response back to the client.
325 BufferedOutputStream bos =
326 new BufferedOutputStream( sock.getOutputStream() );
327 try {
328 response.writeResponse( bos );
329 bos.flush();
330 }
331 finally {
332 try {
333 bos.close();
334 }
335 catch ( IOException e ) {
336 }
337 }
338 }
339
340 /**
341 * Takes the input stream from a client connection and turns it into
342 * a Request object.
343 * As a special case, if the input stream has no content at all,
344 * null is returned.
345 *
346 * @param in input stream
347 * @param remoteAddress address of requesting client
348 * @return parsed request, or null
349 */
350 private static Request parseRequest( InputStream in,
351 SocketAddress remoteAddress )
352 throws IOException {
353
354 // Read the pre-body part.
355 String[] hdrLines = readHeaderLines( in );
356
357 // No text at all?
358 if ( hdrLines == null ) {
359 return null;
360 }
361
362 // No header content?
363 if ( hdrLines.length == 0 ) {
364 throw new HttpException( 400, "Empty request" );
365 }
366
367 // HTTP/0.9 style simple request - probably rare.
368 Matcher simpleMatcher = SIMPLE_REQUEST_PATTERN.matcher( hdrLines[ 0 ] );
369 if ( simpleMatcher.matches() ) {
370 return new Request( "GET", simpleMatcher.group( 1 ),
371 new HashMap(), remoteAddress, null );
372 }
373
374 // Normal HTTP/1.0 request.
375 // First parse the request line.
376 Matcher fullMatcher = REQUEST_LINE_PATTERN.matcher( hdrLines[ 0 ] );
377 if ( fullMatcher.matches() ) {
378 String method = fullMatcher.group( 1 );
379 String uri = fullMatcher.group( 2 );
380
381 // Then read and parse header lines.
382 HttpHeaderMap headerMap = new HttpHeaderMap();
383 int iLine = 1;
384 boolean headerEnd = false;
385 int contentLength = 0;
386 for ( ; iLine < hdrLines.length; iLine++ ) {
387 String line = hdrLines[ iLine ];
388 Matcher headerMatcher = HEADER_PATTERN.matcher( line );
389 if ( headerMatcher.matches() ) {
390 String key = headerMatcher.group( 1 );
391 String value = headerMatcher.group( 2 );
392
393 // Cope with continuation lines.
394 boolean cont = true;
395 while ( iLine + 1 < hdrLines.length && cont ) {
396 cont = false;
397 String line1 = hdrLines[ iLine + 1 ];
398 if ( line1.length() > 0 ) {
399 char c1 = line1.charAt( 0 );
400 if ( c1 == ' ' || c1 == '\t' ) {
401 value += line1.trim();
402 iLine++;
403 cont = true;
404 }
405 }
406 }
407
408 // Store the header.
409 headerMap.addHeader( key, value );
410
411 // Iff we have a content-length line it means we can expect
412 // a body later.
413 if ( key.equalsIgnoreCase( HDR_CONTENT_LENGTH ) ) {
414 try {
415 contentLength =
416 Integer.parseInt( value.trim() );
417 }
418 catch ( NumberFormatException e ) {
419 throw new HttpException( 400,
420 "Failed to parse "
421 + key + " header "
422 + value );
423 }
424 }
425 }
426 }
427
428 // Read body if there is one.
429 final byte[] body;
430 if ( contentLength > 0 ) {
431 body = new byte[ contentLength ];
432 int ib = 0;
433 while ( ib < contentLength ) {
434 int nb = in.read( body, ib, contentLength - ib );
435 if ( nb < 0 ) {
436 throw new HttpException( 500,
437 "Insufficient bytes for declared Content-Length: "
438 + ib + "<" + contentLength );
439 }
440 ib += nb;
441 }
442 assert ib == contentLength;
443 }
444 else {
445 body = null;
446 }
447
448 // Decode escaped characters in the requested URI.
449 uri = SampUtils.uriDecode( uri );
450
451 // Make sure it's a relative URI (probably not necessary
452 // at HTTP 1.1).
453 if ( uri.startsWith( "http://" ) ) {
454 String path;
455 try {
456 URL url = new URL( uri );
457 path = url.getPath();
458 String query = url.getQuery();
459 if ( query != null ) {
460 path += '?' + query;
461 }
462 uri = path;
463 }
464 catch ( MalformedURLException e ) {
465 // never mind
466 }
467 }
468
469 // Return the request.
470 return new Request( method, uri, headerMap, remoteAddress, body );
471 }
472
473 // Unrecognised.
474 else {
475 throw new HttpException( 400, "Bad request" );
476 }
477 }
478
479 /**
480 * Reads the header lines from an HTTP client connection input stream.
481 * All lines are read up to the first CRLF, which is when the body starts.
482 * The input stream is left in a state ready to read the first body line.
483 * As a special case, if the input stream has no content at all,
484 * null is returned.
485 *
486 * @param is socket input stream
487 * @return array of header lines (including initial request line);
488 * the terminal blank line is not included, or null
489 */
490 private static String[] readHeaderLines( InputStream is )
491 throws IOException {
492 List lineList = new ArrayList();
493 StringBuffer sbuf = new StringBuffer();
494 boolean hasChars = false;
495 for ( int c; ( c = is.read() ) >= 0; ) {
496 hasChars = true;
497 switch ( c ) {
498
499 // CRLF is the correct HTTP line terminator.
500 case '\r':
501 if ( is.read() == '\n' ) {
502 if ( sbuf.length() == 0 ) {
503 return (String[])
504 lineList.toArray( new String[ 0 ] );
505 }
506 else {
507 lineList.add( sbuf.toString() );
508 sbuf.setLength( 0 );
509 }
510 }
511 else {
512 throw new HttpException( 400, "CR w/o LF" );
513 }
514 break;
515
516 // HTTP 1.1 recommends that a lone LF is also tolerated as a
517 // line terminator.
518 case '\n':
519 if ( sbuf.length() == 0 ) {
520 return (String[])
521 lineList.toArray( new String[ 0 ] );
522 }
523 else {
524 lineList.add( sbuf.toString() );
525 sbuf.setLength( 0 );
526 }
527 break;
528
529 default:
530 sbuf.append( (char) c );
531 }
532 }
533
534 // No input.
535 if ( ! hasChars ) {
536 return null;
537 }
538
539 // Special case: can handle HTTP/0.9 type simple requests.
540 // Probably very rare.
541 if ( lineList.size() == 1 ) {
542 String line = (String) lineList.get( 0 );
543 if ( SIMPLE_REQUEST_PATTERN.matcher( line ).matches() ) {
544 return new String[] { line };
545 }
546 }
547
548 // If it's got this far, there was no blank line.
549 throw new HttpException( 500, "No CRLF line" );
550 }
551
552 /**
553 * Returns a header value from a header map.
554 * Key value is case-insensitive.
555 * In the (undesirable) case that multiple keys with the same
556 * case-insensitive value exist, the values are concatenated with
557 * comma separators, as per RFC2616 section 4.2.
558 *
559 * @param headerMap map
560 * @param key header key
561 * @return value of map entry with case-insensitive match for key
562 */
563 public static String getHeader( Map headerMap, String key ) {
564 List valueList = new ArrayList();
565 for ( Iterator it = headerMap.entrySet().iterator(); it.hasNext(); ) {
566 Map.Entry entry = (Map.Entry) it.next();
567 if ( ((String) entry.getKey()).equalsIgnoreCase( key ) ) {
568 Object value = entry.getValue();
569 if ( value instanceof String ) {
570 valueList.add( value );
571 }
572 }
573 }
574 int nval = valueList.size();
575 if ( nval == 0 ) {
576 return null;
577 }
578 else if ( nval == 1 ) {
579 return (String) valueList.get( 0 );
580 }
581 else {
582 StringBuffer sbuf = new StringBuffer();
583 for ( Iterator vit = valueList.iterator(); vit.hasNext(); ) {
584 sbuf.append( (String) vit.next() );
585 if ( vit.hasNext() ) {
586 sbuf.append( ", " );
587 }
588 }
589 return sbuf.toString();
590 }
591 }
592
593 /**
594 * Utility method to create an error response.
595 *
596 * @param code status code
597 * @param phrase status phrase
598 * @return new response object
599 */
600 public static Response createErrorResponse( int code, String phrase ) {
601 return new Response( code, phrase, new HashMap() ) {
602 public void writeBody( OutputStream out ) {
603 }
604 };
605 }
606
607 /**
608 * Creates an HTTP response indicating that the requested method
609 * (GET, POST, etc) is not supported.
610 *
611 * @param supportedMethods list of the methods which are supported
612 * @return error response
613 */
614 public static Response create405Response( String[] supportedMethods ) {
615 Map hdrMap = new LinkedHashMap();
616 StringBuffer mlist = new StringBuffer();
617 for ( int i = 0; i < supportedMethods.length; i++ ) {
618 if ( i > 0 ) {
619 mlist.append( ", " );
620 }
621 mlist.append( supportedMethods[ i ] );
622 }
623 hdrMap.put( "Allow", mlist.toString() );
624 hdrMap.put( "Content-Length", "0" );
625 return new Response( 405, "Method not allowed", hdrMap ) {
626 public void writeBody( OutputStream out ) {
627 }
628 };
629 }
630
631 /**
632 * Utility method to create an error response given an exception.
633 *
634 * @param code status code
635 * @param phrase status phrase
636 * @param e exception which caused the trouble
637 * @return new response object
638 */
639 public static Response createErrorResponse( int code, String phrase,
640 final Throwable e ) {
641 Map hdrMap = new LinkedHashMap();
642 hdrMap.put( HDR_CONTENT_TYPE, "text/plain" );
643 return new Response( code, phrase, hdrMap ) {
644 public void writeBody( OutputStream out ) {
645 PrintStream pout = new PrintStream( out );
646 e.printStackTrace( pout );
647 pout.flush();
648 }
649 };
650 }
651
652 /**
653 * Represents a parsed HTTP client request.
654 */
655 public static class Request {
656 private final String method_;
657 private final String url_;
658 private final Map headerMap_;
659 private final SocketAddress remoteAddress_;
660 private final byte[] body_;
661
662 /**
663 * Constructor.
664 *
665 * @param method HTTP method string (GET, HEAD etc)
666 * @param url requested URL path (should start "/")
667 * @param headerMap map of HTTP request header key-value pairs
668 * @param remoteAddress address of the client making the request
669 * @param body bytes comprising request body, or null if none present
670 */
671 public Request( String method, String url, Map headerMap,
672 SocketAddress remoteAddress, byte[] body ) {
673 method_ = method;
674 url_ = url;
675 headerMap_ = headerMap;
676 remoteAddress_ = remoteAddress;
677 body_ = body;
678 }
679
680 /**
681 * Returns the request method string.
682 *
683 * @return GET, HEAD, or whatever
684 */
685 public String getMethod() {
686 return method_;
687 }
688
689 /**
690 * Returns the request URL string. This should be a path starting
691 * "/" (the hostname part is not present).
692 *
693 * @return url path
694 */
695 public String getUrl() {
696 return url_;
697 }
698
699 /**
700 * Returns a map of key-value pairs representing HTTP request headers.
701 * Note that for HTTP usage, header keys are case-insensitive
702 * (RFC2616 sec 4.2); the {@link #getHeader} utility method
703 * can be used to interrogate the returned map.
704 *
705 * @return header map
706 */
707 public Map getHeaderMap() {
708 return headerMap_;
709 }
710
711 /**
712 * Returns the address of the client which made this request.
713 *
714 * @return requesting client's socket address
715 */
716 public SocketAddress getRemoteAddress() {
717 return remoteAddress_;
718 }
719
720 /**
721 * Returns the body of the HTTP request if there was one.
722 *
723 * @return body bytes or null
724 */
725 public byte[] getBody() {
726 return body_;
727 }
728
729 public String toString() {
730 StringBuffer sbuf = new StringBuffer()
731 .append( method_ )
732 .append( ' ' )
733 .append( url_ );
734 if ( headerMap_ != null && ! headerMap_.isEmpty() ) {
735 sbuf.append( "\n " )
736 .append( headerMap_ );
737 }
738 if ( body_ != null && body_.length > 0 ) {
739 sbuf.append( "\n " )
740 .append( "body[" )
741 .append( body_.length )
742 .append( ']' );
743 }
744 return sbuf.toString();
745 }
746 }
747
748 /**
749 * Represents a response to an HTTP request.
750 */
751 public static abstract class Response {
752 private final int statusCode_;
753 private final String statusPhrase_;
754 private final Map headerMap_;
755
756 /**
757 * Constructor.
758 *
759 * @param statusCode 3-digit status code
760 * @param statusPhrase text string passed to client along
761 * with the status code
762 * @param headerMap map of key-value pairs representing response
763 * header information; should normally contain
764 * at least a content-type key
765 */
766 public Response( int statusCode, String statusPhrase, Map headerMap ) {
767 if ( Integer.toString( statusCode ).length() != 3 ) {
768 throw new IllegalArgumentException( "Bad status "
769 + statusCode );
770 }
771 statusCode_ = statusCode;
772 statusPhrase_ = statusPhrase;
773 headerMap_ = headerMap;
774 }
775
776 /**
777 * Returns the 3-digit status code.
778 *
779 * @return status code
780 */
781 public int getStatusCode() {
782 return statusCode_;
783 }
784
785 /**
786 * Returns the status phrase.
787 *
788 * @return status phrase
789 */
790 public String getStatusPhrase() {
791 return statusPhrase_;
792 }
793
794 /**
795 * Returns a map of key-value pairs representing HTTP response headers.
796 * Note that for HTTP usage, header keys are case-insensitive
797 * (RFC2616 sec 4.2); the {@link #getHeader} utility method
798 * can be used to interrogate the returned map.
799 *
800 * @return header map
801 */
802 public Map getHeaderMap() {
803 return headerMap_;
804 }
805
806 /**
807 * Implemented to generate the bytes in the body of the response.
808 *
809 * @param out destination stream for body bytes
810 */
811 public abstract void writeBody( OutputStream out ) throws IOException;
812
813 /**
814 * Writes this response to an output stream in a way suitable for
815 * replying to the client.
816 * Status line and any headers are written, then {@link #writeBody}
817 * is called.
818 *
819 * @param out destination stream
820 */
821 public void writeResponse( OutputStream out ) throws IOException {
822 String statusLine = new StringBuffer()
823 .append( "HTTP/1.0" )
824 .append( ' ' )
825 .append( getStatusCode() )
826 .append( ' ' )
827 .append( getStatusPhrase() )
828 .append( '\r' )
829 .append( '\n' )
830 .toString();
831 out.write( statusLine.getBytes( "UTF-8" ) );
832 if ( headerMap_ != null ) {
833 StringBuffer sbuf = new StringBuffer();
834 for ( Iterator it = getHeaderMap().entrySet().iterator();
835 it.hasNext(); ) {
836 Map.Entry entry = (Map.Entry) it.next();
837 sbuf.setLength( 0 );
838 String line = sbuf
839 .append( entry.getKey() )
840 .append( ':' )
841 .append( ' ' )
842 .append( entry.getValue() )
843 .append( '\r' )
844 .append( '\n' )
845 .toString();
846 out.write( line.getBytes( "UTF-8" ) );
847 }
848 }
849 out.write( '\r' );
850 out.write( '\n' );
851 writeBody( out );
852 }
853 }
854
855 /**
856 * Convenience class for representing an error whose content should be
857 * returned to the user as an HTTP erro response of some kind.
858 */
859 private static class HttpException extends IOException {
860 private final int code_;
861 private final String phrase_;
862
863 /**
864 * Constructor.
865 *
866 * @param code 3-digit status code
867 * @param phrase status phrase
868 */
869 HttpException( int code, String phrase ) {
870 code_ = code;
871 phrase_ = phrase;
872 }
873
874 /**
875 * Turns this exception into a response object.
876 *
877 * @return error response
878 */
879 Response createResponse() {
880 return createErrorResponse( code_, phrase_ );
881 }
882 }
883
884 /**
885 * Map implementation suitable for storing HTTP headers.
886 * It should be populated using the {@link #addHeader}, not {@link #put},
887 * method.
888 * This implementation should be used when a header is being constructed
889 * from an uncontrolled source of (key,value) pairs.
890 * If you are adding headers yourself and know that you won't duplicate
891 * keys, then a normal Map implementation will do.
892 */
893 static class HttpHeaderMap extends LinkedHashMap {
894
895 /**
896 * Adds a header value to this map.
897 * This differs from put in two subtle ways.
898 * First, key matching is case-insensitive.
899 * Second, if a value for the given key already exists, the new
900 * value will be appended after a comma, rather than replacing
901 * the old entry. See RFC2616 section 4.2 for the HTTP rules.
902 *
903 * @param key header name
904 * @param value header value
905 */
906 public void addHeader( String key, String value ) {
907 boolean added = false;
908 for ( Iterator it = entrySet().iterator();
909 it.hasNext() && ! added; ) {
910 Map.Entry entry = (Map.Entry) it.next();
911 if ( ((String) entry.getKey()).equalsIgnoreCase( key ) ) {
912 entry.setValue( entry.getValue() + ", " + value );
913 added = true;
914 }
915 }
916 if ( ! added ) {
917 put( key, value );
918 }
919 }
920 }
921
922 /**
923 * Implemented to serve data for some URLs.
924 */
925 public interface Handler {
926
927 /**
928 * Provides a response to an HTTP request.
929 * A handler which does not recognise the URL should simply return null;
930 * in this case there may be another handler which is able to serve
931 * the request. If the URL appears to be in this handler's domain but
932 * the request cannot be served for some reason, an error response
933 * should be returned.
934 *
935 * @param request HTTP request
936 * @return response response to request, or null
937 */
938 Response serveRequest( Request request );
939 }
940 }