Small refactoring

This commit is contained in:
Ziver Koc 2016-06-29 17:13:23 +02:00
parent 74ad14e052
commit e091a9abe6
2 changed files with 91 additions and 81 deletions

View file

@ -45,23 +45,25 @@ public class HttpPrintStream extends OutputStream{
RESPONSE RESPONSE
} }
// The actual output stream /** The actual output stream */
private PrintStream out; private PrintStream out;
// This defines the type of message that will be generated /** This defines the supported http version */
private String httpVersion;
/** This defines the type of message that will be generated */
private HttpMessageType message_type; private HttpMessageType message_type;
// The status code of the message, ONLY for response /** The status code of the message, ONLY for response */
private Integer res_status_code; private Integer res_status_code;
// The request type of the message ONLY for request /** The request type of the message ONLY for request */
private String req_type; private String req_type;
// The requesting url ONLY for request /** The requesting url ONLY for request */
private String req_url; private String req_url;
// An Map of all the header values /** An Map of all the header values */
private HashMap<String, String> headers; private HashMap<String, String> headers;
// An Map of all the cookies /** An Map of all the cookies */
private HashMap<String, String> cookies; private HashMap<String, String> cookies;
// The buffered header /** The buffered header */
private StringBuffer buffer; private StringBuffer buffer;
// If the header buffering is enabled /** If the header buffering is enabled */
private boolean buffer_enabled; private boolean buffer_enabled;
/** /**
@ -82,6 +84,7 @@ public class HttpPrintStream extends OutputStream{
*/ */
public HttpPrintStream(OutputStream out, HttpMessageType type) { public HttpPrintStream(OutputStream out, HttpMessageType type) {
this.out = new PrintStream(out); this.out = new PrintStream(out);
this.httpVersion = "1.1";
this.message_type = type; this.message_type = type;
this.res_status_code = 0; this.res_status_code = 0;
this.headers = new HashMap<String, String>(); this.headers = new HashMap<String, String>();
@ -104,6 +107,13 @@ public class HttpPrintStream extends OutputStream{
if(!buffer_enabled) flush(); if(!buffer_enabled) flush();
} }
/**
* Set the http version that will be used in the http header
*/
public void setHttpVersion(String version){
this.httpVersion = version;
}
/** /**
* Adds a cookie that will be sent to the client * Adds a cookie that will be sent to the client
* *
@ -208,9 +218,9 @@ public class HttpPrintStream extends OutputStream{
else{ else{
if(res_status_code != null){ if(res_status_code != null){
if( message_type==HttpMessageType.REQUEST ) if( message_type==HttpMessageType.REQUEST )
out.print(req_type + " " + req_url + " HTTP/1.1"); out.print(req_type + " " + req_url + " HTTP/"+httpVersion);
else else
out.print("HTTP/1.1 " + res_status_code + " " + getStatusString(res_status_code)); out.print("HTTP/"+httpVersion+" " + res_status_code + " " + getStatusString(res_status_code));
out.println(); out.println();
res_status_code = null; res_status_code = null;
req_type = null; req_type = null;
@ -306,6 +316,7 @@ public class HttpPrintStream extends OutputStream{
case 100: return "Continue"; case 100: return "Continue";
case 200: return "OK"; case 200: return "OK";
case 301: return "Moved Permanently"; case 301: return "Moved Permanently";
case 304: return "Not Modified";
case 307: return "Temporary Redirect"; case 307: return "Temporary Redirect";
case 400: return "Bad Request"; case 400: return "Bad Request";
case 401: return "Unauthorized"; case 401: return "Unauthorized";

View file

@ -51,7 +51,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
public static final String SESSION_ID_KEY = "session_id"; public static final String SESSION_ID_KEY = "session_id";
public static final String SESSION_TTL_KEY = "session_ttl"; public static final String SESSION_TTL_KEY = "session_ttl";
public static final String SERVER_VERSION = "Ziver HttpServer 1.1"; public static final String SERVER_VERSION = "Zutil HttpServer";
public static final int SESSION_TTL = 10*60*1000; // in milliseconds public static final int SESSION_TTL = 10*60*1000; // in milliseconds
@ -142,6 +142,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
return null; return null;
} }
private static int noOfConnections = 0;
/** /**
* Internal class that handles all the requests * Internal class that handles all the requests
* *
@ -160,90 +161,87 @@ public class HttpServer extends ThreadedTCPNetworkServer{
} }
public void run(){ public void run(){
String tmp = null; //logger.finest("New Connection: "+socket.getInetAddress()+" (Ongoing connections: "+(++noOfConnections)+")");
HttpHeaderParser headerParser = new HttpHeaderParser(in);
//**************************** REQUEST *********************************
try { try {
long time = System.currentTimeMillis(); //**************************** PARSE REQUEST *********************************
HttpHeader header = headerParser.read(); long time = System.currentTimeMillis();
if(header == null){ HttpHeaderParser headerParser = new HttpHeaderParser(in);
HttpHeader header = headerParser.read();
if (header == null) {
logger.finer("No header received"); logger.finer("No header received");
return; return;
} }
String tmp = null;
//******* Read in the post data if available //******* Read in the post data if available
if( header.getHeader("Content-Length") != null ){ if (header.getHeader("Content-Length") != null) {
// Reads the post data size // Reads the post data size
tmp = header.getHeader("Content-Length"); tmp = header.getHeader("Content-Length");
int post_data_length = Integer.parseInt( tmp ); int post_data_length = Integer.parseInt(tmp);
// read the data // read the data
StringBuilder tmpBuff = new StringBuilder(); StringBuilder tmpBuff = new StringBuilder();
// read the data // read the data
for(int i=0; i<post_data_length ;i++){ for (int i = 0; i < post_data_length; i++) {
tmpBuff.append((char)in.read()); tmpBuff.append((char) in.read());
} }
tmp = header.getHeader("Content-Type"); tmp = header.getHeader("Content-Type");
if( tmp.contains("application/x-www-form-urlencoded") ){ if (tmp.contains("application/x-www-form-urlencoded")) {
// get the variables // get the variables
HttpHeaderParser.parseURLParameters(header, tmpBuff.toString()); HttpHeaderParser.parseURLParameters(header, tmpBuff.toString());
} } else if (tmp.contains("application/soap+xml") ||
else if( tmp.contains("application/soap+xml" ) || tmp.contains("text/xml") ||
tmp.contains("text/xml") || tmp.contains("text/plain")) {
tmp.contains("text/plain") ){ // save the variables
// save the variables header.putURLAttribute("", tmpBuff.toString());
header.putURLAttribute("" , tmpBuff.toString()); } else if (tmp.contains("multipart/form-data")) {
} // TODO: File upload
else if( tmp.contains("multipart/form-data") ){ throw new UnsupportedOperationException("HTTP Content-Type 'multipart-form-data' not supported.");
// TODO: File upload }
throw new UnsupportedOperationException("HTTP Content-Type 'multipart-form-data' not supported." ); }
}
}
//**************************** HANDLE REQUEST ********************************* //**************************** HANDLE REQUEST *********************************
// Get the client session or create one // Get the client session or create one
Map<String, Object> session; Map<String, Object> session;
long ttlTime = System.currentTimeMillis() + SESSION_TTL; long ttlTime = System.currentTimeMillis() + SESSION_TTL;
String sessionCookie = header.getCookie(SESSION_ID_KEY); String sessionCookie = header.getCookie(SESSION_ID_KEY);
if( sessionCookie != null && sessions.containsKey(sessionCookie) && if (sessionCookie != null && sessions.containsKey(sessionCookie) &&
(Long)sessions.get(sessionCookie).get(SESSION_TTL_KEY) < System.currentTimeMillis()){ // Check if session is still valid (Long) sessions.get(sessionCookie).get(SESSION_TTL_KEY) < System.currentTimeMillis()) { // Check if session is still valid
session = sessions.get(sessionCookie); session = sessions.get(sessionCookie);
// renew the session TTL // renew the session TTL
session.put(SESSION_TTL_KEY, ttlTime); session.put(SESSION_TTL_KEY, ttlTime);
} } else {
else{ session = Collections.synchronizedMap(new HashMap<String, Object>());
session = Collections.synchronizedMap(new HashMap<String, Object>()); session.put(SESSION_ID_KEY, nextSessionId);
session.put(SESSION_ID_KEY, nextSessionId ); session.put(SESSION_TTL_KEY, ttlTime);
session.put(SESSION_TTL_KEY, ttlTime ); sessions.put(nextSessionId, session);
sessions.put(nextSessionId, session ); ++nextSessionId;
++nextSessionId; }
}
//**************************** RESPONSE ************************************ //**************************** RESPONSE ************************************
out.setStatusCode(200); out.setHttpVersion("1.0");
out.setHeader("Server", SERVER_VERSION); out.setStatusCode(200);
out.setHeader("Content-Type", "text/html"); out.setHeader("Server", SERVER_VERSION);
out.setCookie(SESSION_ID_KEY, ""+session.get(SESSION_ID_KEY)); out.setHeader("Content-Type", "text/html");
//out.setHeader("Connection", "keep-alive");
out.setCookie(SESSION_ID_KEY, "" + session.get(SESSION_ID_KEY));
if( header.getRequestURL() != null && pages.containsKey(header.getRequestURL())){ if (header.getRequestURL() != null && pages.containsKey(header.getRequestURL())) {
HttpPage page = pages.get(header.getRequestURL()); HttpPage page = pages.get(header.getRequestURL());
page.respond(out, header, session, header.getCookieMap(), header.getUrlAttributeMap()); page.respond(out, header, session, header.getCookieMap(), header.getUrlAttributeMap());
if(LogUtil.isLoggable(page.getClass(), Level.FINER)) if (LogUtil.isLoggable(page.getClass(), Level.FINER))
logRequest(header, session, time); logRequest(header, session, time);
} } else if (header.getRequestURL() != null && defaultPage != null) {
else if( header.getRequestURL() != null && defaultPage != null ){ defaultPage.respond(out, header, session, header.getCookieMap(), header.getUrlAttributeMap());
defaultPage.respond(out, header, session, header.getCookieMap(), header.getUrlAttributeMap()); if (LogUtil.isLoggable(defaultPage.getClass(), Level.FINER))
if(LogUtil.isLoggable(defaultPage.getClass(), Level.FINER)) logRequest(header, session, time);
logRequest(header, session, time); } else {
} out.setStatusCode(404);
else{ out.println("404 Page Not Found: " + header.getRequestURL());
out.setStatusCode(404); logger.warning("Page not defined: " + header.getRequestURL());
out.println("404 Page Not Found: "+header.getRequestURL()); }
logger.warning("Page not defined: " + header.getRequestURL());
}
//******************************************************************************** //********************************************************************************
} catch (Exception e) { } catch (Exception e) {
logger.log(Level.SEVERE, "500 Internal Server Error", e); logger.log(Level.SEVERE, "500 Internal Server Error", e);
@ -266,6 +264,7 @@ public class HttpServer extends ThreadedTCPNetworkServer{
out.close(); out.close();
in.close(); in.close();
socket.close(); socket.close();
//logger.finest("Connection Closed: "+socket.getInetAddress()+" (Ongoing connections: "+(--noOfConnections)+")");
} catch( Exception e ) { } catch( Exception e ) {
logger.log(Level.WARNING, "Could not close connection", e); logger.log(Level.WARNING, "Could not close connection", e);
} }