com.marringtons.net.HTTP
Class Response

java.lang.Object
  extended bycom.marringtons.net.HTTP.Response

public class Response
extends Object

This class builds up a HTTP response and sends it to a client browser.

 
 // Sending normal data (i.e. HTML)
 Response response = new Response(socket);
 response.reset(request); // always reset the response before use - provides request to relative references
 while ((line = getLine()) != null)
 	response.add(line);
 response.send(); // sends header with body length, then body
 // can handle multiple request/response pairs for connection
 response.reset(); // prepare for new response
 
 // Files can be sent directly - FileReader is used to find them on the data path.
 // A FileCache is used so that frequently used files are cached. The cache size is
 // specified in a system.properties key "http.file.read.cache.size".
 response.sendFile(fileName);
 // can handle multiple request/response pairs for connection
 
 // Send data as it is generated (also used for server push)
 // Send at least once a minute so browser does not abort
 Response response = new Response(socket);
 response.send(); // do right away so no body length
 while ((line = getLine()) != null)
 	response.add(line);
 response.send(); // must do after any add() calls
 while (waiting())
 	response.send("*"); // same as add(); send();
 response.add("Done");
 response.send(); // same as response.send()
 socket.close(); // must close as no length (HTTP requirement)
 
 

Author:
Paul Marrington

Field Summary
static boolean debug
          Set true by test routines to log errors and force all content to reload from server (to test file changes).
 Socket socket
          Socket this response sends to.
 
Constructor Summary
Response(Request request, OutputStream stream)
          Called by JUnit to test a response.
Response(Request request, Socket socket)
          Called by connection thread to create a response object from a socket.
 
Method Summary
 Response append(Object bodyText)
          Add text to the body of the response (but don't send to client).
 void CGIsend(int character)
          Special case to send characters to the browser one at a time (unbuffered).
 void close()
          Flush and close the connection.
static String contentType(String type)
          Used by HTTPconnection to see if the browser can definitely handle this type of file.
 void error(int returnCode)
          Send an error response to the client/browser - using a default message.
 void error(int returnCode, Object reason)
          Send an error response to the client/browser and closes the socket.
 void push()
          Send response so far to client so that it will display.
 void redirect(String url)
          Send browser off to a new page.
 void reset()
          Clear the header and body.
 void send()
          Send response to client so that it will display.
 void send(Object text)
          Send response so far to client - including more text provided.
 boolean sendFile(String fileName, String after)
          Complete the response by sending the contents of a file.
 boolean sendFile(String before, String fileName, String after)
          Complete the response by sending the contents of a file.
 void setContentType(String contentType)
          Default content type is text/html - or that set by file entension.
 void setPermanentCookie(String key, Object value)
          Set a browser cookie that will last forever.
 void setPersistentCookie(String key, Object value, int lifeInMinutes)
          Set a browser cookie that will last for the time specified
 void setSessionCookie(String key, Object value)
          Set a browser cookie that will only last until the browser closes (browser session).
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

debug

public static boolean debug
Set true by test routines to log errors and force all content to reload from server (to test file changes).


socket

public Socket socket
Socket this response sends to.

Constructor Detail

Response

public Response(Request request,
                Socket socket)
         throws IOException
Called by connection thread to create a response object from a socket.

Parameters:
request - for which this response exists.
socket - that hosts the conversation.
Throws:
IOException - on socket error.

Response

public Response(Request request,
                OutputStream stream)
Called by JUnit to test a response.

Parameters:
request - for which this response exists.
stream - that hosts this conversation.
Method Detail

append

public Response append(Object bodyText)
Add text to the body of the response (but don't send to client). Alway follow with a flush() or complete().

Parameters:
bodyText - text to be added to the end of the response body.
Returns:
Response object so that response.append("one").append("two") works

send

public void send(Object text)
Send response so far to client - including more text provided. Same as add() followed by flush(). Use for server push or for a progress page Doesn't set content length because more to come.

Parameters:
text - more text after any from add

send

public void send()
Send response to client so that it will display. For normal pages use append() followed by send().


push

public void push()
Send response so far to client so that it will display. Use for server push or for a progress page. For normal pages use add() followed by send(). Don't set content length because more to come.


sendFile

public boolean sendFile(String fileName,
                        String after)
                 throws IOException
Complete the response by sending the contents of a file. The extension is used to define the content type of the file for the browser. Additional ones can be added to files called "contentTypes.txt" from any directory on the data path - although the default one should cover most situations.

Handles active content as a special case. Files of mask *.dynamic.html are considered active content. The file will be startwith . The template file is opened and dumped to the browser before the active content file. In practice the template file is a complete HTML file with ID tag identifiers for DHTML elements. The active content is javascript to fill in the blanks. Use this sendFile to send static content to the browser. When not in debug mode the browser will cache the contents for up to 12 hours. If the contents will change every time this code is run, use sendFile( before, fileName, after).

Parameters:
fileName - name of file to send as part of the response.
after - static text to place at the end of the transmission
Returns:
true if worked as expected
Throws:
IOException

sendFile

public boolean sendFile(String before,
                        String fileName,
                        String after)
                 throws IOException
Complete the response by sending the contents of a file. The extension is used to define the content type of the file for the browser. Additional ones can be added to files called "contentTypes.txt" from any directory on the data path - although the default one should cover most situations.

Handles active content as a special case. Files of mask *.dynamic.html are considered active content. The file will be startwith . The template file is opened and dumped to the browser before the active content file. In practice the template file is a complete HTML file with ID tag identifiers for DHTML elements. The active content is javascript to fill in the blanks. All content is expected to be active. The browser will not cache the contents.

Parameters:
before - html/javascript to send before the html file (and tag)
fileName - html/javascript to send after the html file (and /tag)
after - more to add to end of HTML (typically javascript control)
Returns:
true of worked as expected
Throws:
IOException - - only on socket errors. File errors will return false to try elsewhere

CGIsend

public void CGIsend(int character)
             throws IOException
Special case to send characters to the browser one at a time (unbuffered). The normal header is not sent (apart from response code) as this has become the responsibility of the CGI program.

Parameters:
character - 1 unbuffered character to go to browser
Throws:
IOException

error

public void error(int returnCode)
Send an error response to the client/browser - using a default message.

Parameters:
returnCode - as in 404 for not found or 500 for server error.
 
  100 Continue
  101 Switching Protocols
  200 OK
  201 Created
  202 Accepted
  203 Non-Authoritative Information
  204 No Content
  205 Reset Content
  206 Partial Content
  300 Multiple Choices
  301 Moved Permanently
  302 Found
  303 See Other
  304 Not Modified
  305 Use Proxy
  306 (Unused)
  307 Temporary Redirect
  400 Bad Request
  401 Unauthorized
  402 Payment Required
  403 Forbidden
  404 Not Found
  405 Method Not Allowed
  406 Not Acceptable
  407 Proxy Authentication Required
  408 Request Timeout
  409 Conflict
  410 Gone
  411 Length Required
  412 Precondition Failed
  413 Request Entity Too Large
  414 Request URI Too Long
  415 Unsupported Media Type
  416 Requested Range Not Satisfiable
  417 Expectation Failed
  500 Internal Server Error
  501 Not Implemented
  502 Bad Gateway
  503 Service Unavailable
  504 Gateway Timeout
  505 HTTP Version Not Supported
  
 

error

public void error(int returnCode,
                  Object reason)
Send an error response to the client/browser and closes the socket. Will send default content and redirect to a specific page if error.xxx is in the system properties file.

Parameters:
returnCode - as in 404 for not found or 500 for server error.
reason - A string describing why the error response occurred.

redirect

public void redirect(String url)
Send browser off to a new page. Uses JavaScript if the header has already been written, otherwise uses Location header element

Parameters:
url - to redirect to.

reset

public void reset()
Clear the header and body. Doesn't work after a flush.


close

public void close()
Flush and close the connection.


contentType

public static String contentType(String type)
Used by HTTPconnection to see if the browser can definitely handle this type of file.

Parameters:
type - file extension/type gleaned from the URL
Returns:
Mime type (i.e. image/gif) or null if not found.

setContentType

public void setContentType(String contentType)
Default content type is text/html - or that set by file entension. Use this method to change that. To display raw text, make it text/text.

Parameters:
contentType - as in text/html

setSessionCookie

public void setSessionCookie(String key,
                             Object value)
Set a browser cookie that will only last until the browser closes (browser session).

Parameters:
key - cookie key
value - cookie value

setPermanentCookie

public void setPermanentCookie(String key,
                               Object value)
Set a browser cookie that will last forever.

Parameters:
key - cookie key
value - cookie value

setPersistentCookie

public void setPersistentCookie(String key,
                                Object value,
                                int lifeInMinutes)
Set a browser cookie that will last for the time specified

Parameters:
key - cookie key
value - cookie value
lifeInMinutes - time in minutes after which cookie will disappear.


Copyright © 2005 Paul Marrington http://library.marringtons.com