diff options
author | ritchie <ritchie@gmx.at> | 2015-05-10 13:41:19 +0200 |
---|---|---|
committer | ritchie <ritchie@gmx.at> | 2015-05-10 13:41:19 +0200 |
commit | 9058464950a9734da0a7ff2dc47f3081bbb5117c (patch) | |
tree | 6e6ab43930c3d0e134dc194e4a8a4a57cb1c7e7f /core/src | |
parent | a59803b641f7eee45cfd0cf170e669dfe2b1eb8d (diff) | |
download | nanohttpd-9058464950a9734da0a7ff2dc47f3081bbb5117c.tar.gz |
after the last pull request in this series the formatter is now active
Diffstat (limited to 'core/src')
16 files changed, 548 insertions, 398 deletions
diff --git a/core/src/main/java/fi/iki/elonen/NanoHTTPD.java b/core/src/main/java/fi/iki/elonen/NanoHTTPD.java index 5132bbf..0705196 100644 --- a/core/src/main/java/fi/iki/elonen/NanoHTTPD.java +++ b/core/src/main/java/fi/iki/elonen/NanoHTTPD.java @@ -72,7 +72,6 @@ import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; - import java.security.KeyStore; import javax.net.ssl.*; @@ -81,7 +80,10 @@ import javax.net.ssl.*; * <p/> * <p/> * NanoHTTPD - * <p>Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias</p> + * <p> + * Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, + * 2010 by Konstantinos Togias + * </p> * <p/> * <p/> * <b>Features + limitations: </b> @@ -90,8 +92,10 @@ import javax.net.ssl.*; * <li>Only one Java file</li> * <li>Java 5 compatible</li> * <li>Released as open source, Modified BSD licence</li> - * <li>No fixed config files, logging, authorization etc. (Implement yourself if you need them.)</li> - * <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT support in 1.25)</li> + * <li>No fixed config files, logging, authorization etc. (Implement yourself if + * you need them.)</li> + * <li>Supports parameter parsing of GET and POST methods (+ rudimentary PUT + * support in 1.25)</li> * <li>Supports both dynamic content and file serving</li> * <li>Supports file upload (since version 1.2, 2010)</li> * <li>Supports partial content (streaming)</li> @@ -106,7 +110,8 @@ import javax.net.ssl.*; * <li>File server supports simple skipping for files (continue download)</li> * <li>File server serves also very long files without memory overhead</li> * <li>Contains a built-in list of most common MIME types</li> - * <li>All header names are converted to lower case so they don't vary between browsers/clients</li> + * <li>All header names are converted to lower case so they don't vary between + * browsers/clients</li> * <p/> * </ul> * <p/> @@ -118,43 +123,56 @@ import javax.net.ssl.*; * <p/> * </ul> * <p/> - * See the separate "LICENSE.md" file for the distribution license (Modified BSD licence) + * See the separate "LICENSE.md" file for the distribution license (Modified BSD + * licence) */ public abstract class NanoHTTPD { + /** * Maximum time to wait on Socket.getInputStream().read() (in milliseconds) - * This is required as the Keep-Alive HTTP connections would otherwise - * block the socket reading thread forever (or as long the browser is open). + * This is required as the Keep-Alive HTTP connections would otherwise block + * the socket reading thread forever (or as long the browser is open). */ public static final int SOCKET_READ_TIMEOUT = 5000; + /** * Common MIME type for dynamic content: plain text */ public static final String MIME_PLAINTEXT = "text/plain"; + /** * Common MIME type for dynamic content: html */ public static final String MIME_HTML = "text/html"; + /** - * Pseudo-Parameter to use to store the actual query string in the parameters map for later re-processing. + * Pseudo-Parameter to use to store the actual query string in the + * parameters map for later re-processing. */ private static final String QUERY_STRING_PARAMETER = "NanoHttpd.QUERY_STRING"; - - /** - * logger to log to. - */ - private static Logger LOG = Logger.getLogger(NanoHTTPD.class.getName()); - + + /** + * logger to log to. + */ + private static Logger LOG = Logger.getLogger(NanoHTTPD.class.getName()); + private final String hostname; + private final int myPort; + private ServerSocket myServerSocket; + private Set<Socket> openConnections = new HashSet<Socket>(); + private SSLServerSocketFactory sslServerSocketFactory; + private Thread myThread; + /** * Pluggable strategy for asynchronously executing requests. */ private AsyncRunner asyncRunner; + /** * Pluggable strategy for creating and cleaning up temporary files. */ @@ -182,86 +200,84 @@ public abstract class NanoHTTPD { try { closeable.close(); } catch (IOException e) { - LOG.log(Level.SEVERE, "Could not close",e); + LOG.log(Level.SEVERE, "Could not close", e); } } } - /** - * Creates an SSLSocketFactory for HTTPS. - * - * Pass a KeyStore resource with your certificate and passphrase - */ - public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException { - SSLServerSocketFactory res = null; - try { - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath); - keystore.load(keystoreStream, passphrase); - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(keystore); - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - keyManagerFactory.init(keystore, passphrase); - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); - res = ctx.getServerSocketFactory(); - } catch (Exception e) { - throw new IOException(e.getMessage()); - } - return res; - } - - /** - * Creates an SSLSocketFactory for HTTPS. - * - * Pass a loaded KeyStore and a loaded KeyManagerFactory. - * These objects must properly loaded/initialized by the caller. - */ - public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException { - SSLServerSocketFactory res = null; - try { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(loadedKeyStore); - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(loadedKeyFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); - res = ctx.getServerSocketFactory(); - } catch (Exception e) { - throw new IOException(e.getMessage()); - } - return res; - } - - /** - * Creates an SSLSocketFactory for HTTPS. - * - * Pass a loaded KeyStore and an array of loaded KeyManagers. - * These objects must properly loaded/initialized by the caller. - */ - public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException { - SSLServerSocketFactory res = null; - try { - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(loadedKeyStore); - SSLContext ctx = SSLContext.getInstance("TLS"); - ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null); - res = ctx.getServerSocketFactory(); - } catch (Exception e) { - throw new IOException(e.getMessage()); - } - return res; - } - - /** - * Call before start() to serve over HTTPS instead of HTTP - */ - public void makeSecure(SSLServerSocketFactory sslServerSocketFactory) { - this.sslServerSocketFactory = sslServerSocketFactory; - } + /** + * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your + * certificate and passphrase + */ + public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException { + SSLServerSocketFactory res = null; + try { + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath); + keystore.load(keystoreStream, passphrase); + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(keystore); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, passphrase); + SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); + res = ctx.getServerSocketFactory(); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + return res; + } + + /** + * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a + * loaded KeyManagerFactory. These objects must properly loaded/initialized + * by the caller. + */ + public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException { + SSLServerSocketFactory res = null; + try { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(loadedKeyStore); + SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(loadedKeyFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); + res = ctx.getServerSocketFactory(); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + return res; + } + + /** + * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an + * array of loaded KeyManagers. These objects must properly + * loaded/initialized by the caller. + */ + public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException { + SSLServerSocketFactory res = null; + try { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(loadedKeyStore); + SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null); + res = ctx.getServerSocketFactory(); + } catch (Exception e) { + throw new IOException(e.getMessage()); + } + return res; + } + + /** + * Call before start() to serve over HTTPS instead of HTTP + */ + public void makeSecure(SSLServerSocketFactory sslServerSocketFactory) { + this.sslServerSocketFactory = sslServerSocketFactory; + } /** * Start the server. - * - * @throws IOException if the socket is in use. + * + * @throws IOException + * if the socket is in use. */ public void start() throws IOException { if (sslServerSocketFactory != null) { @@ -275,6 +291,7 @@ public abstract class NanoHTTPD { myServerSocket.bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort)); myThread = new Thread(new Runnable() { + @Override public void run() { do { @@ -284,6 +301,7 @@ public abstract class NanoHTTPD { finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT); final InputStream inputStream = finalAccept.getInputStream(); asyncRunner.exec(new Runnable() { + @Override public void run() { OutputStream outputStream = null; @@ -295,13 +313,15 @@ public abstract class NanoHTTPD { session.execute(); } } catch (Exception e) { - // When the socket is closed by the client, we throw our own SocketException - // to break the "keep alive" loop above. If the exception was anything other - // than the expected SocketException OR a SocketTimeoutException, print the + // When the socket is closed by the client, + // we throw our own SocketException + // to break the "keep alive" loop above. If + // the exception was anything other + // than the expected SocketException OR a + // SocketTimeoutException, print the // stacktrace - if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && - !(e instanceof SocketTimeoutException)) { - LOG.log(Level.FINE, "Communication with the client broken", e); + if (!(e instanceof SocketException && "NanoHttpd Shutdown".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) { + LOG.log(Level.FINE, "Communication with the client broken", e); } } finally { safeClose(outputStream); @@ -312,7 +332,7 @@ public abstract class NanoHTTPD { } }); } catch (IOException e) { - LOG.log(Level.FINE, "Communication with the client broken", e); + LOG.log(Level.FINE, "Communication with the client broken", e); } } while (!myServerSocket.isClosed()); } @@ -333,14 +353,15 @@ public abstract class NanoHTTPD { myThread.join(); } } catch (Exception e) { - LOG.log(Level.SEVERE, "Could not stop all connections", e); + LOG.log(Level.SEVERE, "Could not stop all connections", e); } } /** * Registers that a new connection has been set up. - * - * @param socket the {@link Socket} for the connection. + * + * @param socket + * the {@link Socket} for the connection. */ public synchronized void registerConnection(Socket socket) { openConnections.add(socket); @@ -348,7 +369,7 @@ public abstract class NanoHTTPD { /** * Registers that a connection has been closed - * + * * @param socket * the {@link Socket} for the connection. */ @@ -382,16 +403,21 @@ public abstract class NanoHTTPD { * <p/> * <p/> * (By default, this returns a 404 "Not Found" plain text error response.) - * - * @param uri Percent-decoded URI without parameters, for example "/index.cgi" - * @param method "GET", "POST" etc. - * @param parms Parsed, percent decoded parameters from URI and, in case of POST, data. - * @param headers Header entries, percent decoded + * + * @param uri + * Percent-decoded URI without parameters, for example + * "/index.cgi" + * @param method + * "GET", "POST" etc. + * @param parms + * Parsed, percent decoded parameters from URI and, in case of + * POST, data. + * @param headers + * Header entries, percent decoded * @return HTTP response, see class Response for details */ @Deprecated - public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, - Map<String, String> files) { + public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { return new Response(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found"); } @@ -400,8 +426,9 @@ public abstract class NanoHTTPD { * <p/> * <p/> * (By default, this returns a 404 "Not Found" plain text error response.) - * - * @param session The HTTP session + * + * @param session + * The HTTP session * @return HTTP response, see class Response for details */ public Response serve(IHTTPSession session) { @@ -424,39 +451,46 @@ public abstract class NanoHTTPD { /** * Decode percent encoded <code>String</code> values. - * - * @param str the percent encoded <code>String</code> - * @return expanded form of the input, for example "foo%20bar" becomes "foo bar" + * + * @param str + * the percent encoded <code>String</code> + * @return expanded form of the input, for example "foo%20bar" becomes + * "foo bar" */ protected String decodePercent(String str) { String decoded = null; try { decoded = URLDecoder.decode(str, "UTF8"); } catch (UnsupportedEncodingException ignored) { - LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored); + LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored); } return decoded; } /** - * Decode parameters from a URL, handing the case where a single parameter name might have been - * supplied several times, by return lists of values. In general these lists will contain a single - * element. - * - * @param parms original <b>NanoHTTPD</b> parameters values, as passed to the <code>serve()</code> method. - * @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied). + * Decode parameters from a URL, handing the case where a single parameter + * name might have been supplied several times, by return lists of values. + * In general these lists will contain a single element. + * + * @param parms + * original <b>NanoHTTPD</b> parameters values, as passed to the + * <code>serve()</code> method. + * @return a map of <code>String</code> (parameter name) to + * <code>List<String></code> (a list of the values supplied). */ protected Map<String, List<String>> decodeParameters(Map<String, String> parms) { return this.decodeParameters(parms.get(QUERY_STRING_PARAMETER)); } /** - * Decode parameters from a URL, handing the case where a single parameter name might have been - * supplied several times, by return lists of values. In general these lists will contain a single - * element. - * - * @param queryString a query string pulled from the URL. - * @return a map of <code>String</code> (parameter name) to <code>List<String></code> (a list of the values supplied). + * Decode parameters from a URL, handing the case where a single parameter + * name might have been supplied several times, by return lists of values. + * In general these lists will contain a single element. + * + * @param queryString + * a query string pulled from the URL. + * @return a map of <code>String</code> (parameter name) to + * <code>List<String></code> (a list of the values supplied). */ protected Map<String, List<String>> decodeParameters(String queryString) { Map<String, List<String>> parms = new HashMap<String, List<String>>(); @@ -478,41 +512,53 @@ public abstract class NanoHTTPD { return parms; } - // ------------------------------------------------------------------------------- // + // ------------------------------------------------------------------------------- + // // // // Threading Strategy. // - // ------------------------------------------------------------------------------- // + // ------------------------------------------------------------------------------- + // // /** * Pluggable strategy for asynchronously executing requests. - * - * @param asyncRunner new strategy for handling threads. + * + * @param asyncRunner + * new strategy for handling threads. */ public void setAsyncRunner(AsyncRunner asyncRunner) { this.asyncRunner = asyncRunner; } - // ------------------------------------------------------------------------------- // + // ------------------------------------------------------------------------------- + // // // // Temp file handling strategy. // - // ------------------------------------------------------------------------------- // + // ------------------------------------------------------------------------------- + // // /** * Pluggable strategy for creating and cleaning up temporary files. - * - * @param tempFileManagerFactory new strategy for handling temp files. + * + * @param tempFileManagerFactory + * new strategy for handling temp files. */ public void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) { this.tempFileManagerFactory = tempFileManagerFactory; } /** - * HTTP Request methods, with the ability to decode a <code>String</code> back to its enum value. + * HTTP Request methods, with the ability to decode a <code>String</code> + * back to its enum value. */ public enum Method { - GET, PUT, POST, DELETE, HEAD, OPTIONS; + GET, + PUT, + POST, + DELETE, + HEAD, + OPTIONS; static Method lookup(String method) { for (Method m : Method.values()) { @@ -528,6 +574,7 @@ public abstract class NanoHTTPD { * Pluggable strategy for asynchronously executing requests. */ public interface AsyncRunner { + void exec(Runnable code); } @@ -535,18 +582,23 @@ public abstract class NanoHTTPD { * Factory to create temp file managers. */ public interface TempFileManagerFactory { + TempFileManager create(); } - // ------------------------------------------------------------------------------- // + // ------------------------------------------------------------------------------- + // // /** * Temp file manager. * <p/> - * <p>Temp file managers are created 1-to-1 with incoming requests, to create and cleanup - * temporary files created as a result of handling the request.</p> + * <p> + * Temp file managers are created 1-to-1 with incoming requests, to create + * and cleanup temporary files created as a result of handling the request. + * </p> */ public interface TempFileManager { + TempFile createTempFile() throws Exception; void clear(); @@ -555,10 +607,13 @@ public abstract class NanoHTTPD { /** * A temp file. * <p/> - * <p>Temp files are responsible for managing the actual temporary storage and cleaning - * themselves up when no longer needed.</p> + * <p> + * Temp files are responsible for managing the actual temporary storage and + * cleaning themselves up when no longer needed. + * </p> */ public interface TempFile { + OutputStream open() throws Exception; void delete() throws Exception; @@ -569,11 +624,14 @@ public abstract class NanoHTTPD { /** * Default threading strategy for NanoHTTPD. * <p/> - * <p>By default, the server spawns a new Thread for every incoming request. These are set - * to <i>daemon</i> status, and named according to the request number. The name is - * useful when profiling the application.</p> + * <p> + * By default, the server spawns a new Thread for every incoming request. + * These are set to <i>daemon</i> status, and named according to the request + * number. The name is useful when profiling the application. + * </p> */ public static class DefaultAsyncRunner implements AsyncRunner { + private long requestCount; @Override @@ -589,14 +647,17 @@ public abstract class NanoHTTPD { /** * Default strategy for creating and cleaning up temporary files. * <p/> - * <p>This class stores its files in the standard location (that is, - * wherever <code>java.io.tmpdir</code> points to). Files are added - * to an internal list, and deleted when no longer needed (that is, - * when <code>clear()</code> is invoked at the end of processing a - * request).</p> + * <p> + * This class stores its files in the standard location (that is, wherever + * <code>java.io.tmpdir</code> points to). Files are added to an internal + * list, and deleted when no longer needed (that is, when + * <code>clear()</code> is invoked at the end of processing a request). + * </p> */ public static class DefaultTempFileManager implements TempFileManager { + private final String tmpdir; + private final List<TempFile> tempFiles; public DefaultTempFileManager() { @@ -617,7 +678,7 @@ public abstract class NanoHTTPD { try { file.delete(); } catch (Exception ignored) { - LOG.log(Level.WARNING, "could not delete file ", ignored); + LOG.log(Level.WARNING, "could not delete file ", ignored); } } tempFiles.clear(); @@ -627,11 +688,15 @@ public abstract class NanoHTTPD { /** * Default strategy for creating and cleaning up temporary files. * <p/> - * <p>By default, files are created by <code>File.createTempFile()</code> in - * the directory specified.</p> + * <p> + * By default, files are created by <code>File.createTempFile()</code> in + * the directory specified. + * </p> */ public static class DefaultTempFile implements TempFile { + private File file; + private OutputStream fstream; public DefaultTempFile(String tempdir) throws IOException { @@ -660,33 +725,40 @@ public abstract class NanoHTTPD { * HTTP response. Return one of these from serve(). */ public static class Response { + /** * HTTP status code after processing, e.g. "200 OK", Status.OK */ private IStatus status; + /** * MIME type of content, e.g. "text/html" */ private String mimeType; + /** * Data of the response, may be null. */ private InputStream data; + /** * Headers for the HTTP response. Use addHeader() to add lines. */ private Map<String, String> header = new HashMap<String, String>(); + /** * The request method that spawned this response. */ private Method requestMethod; + /** * Use chunkedTransfer */ private boolean chunkedTransfer; /** - * Default constructor: response = Status.OK, mime = MIME_HTML and your supplied message + * Default constructor: response = Status.OK, mime = MIME_HTML and your + * supplied message */ public Response(String msg) { this(Status.OK, MIME_HTML, msg); @@ -710,7 +782,7 @@ public abstract class NanoHTTPD { try { this.data = txt != null ? new ByteArrayInputStream(txt.getBytes("UTF-8")) : null; } catch (java.io.UnsupportedEncodingException uee) { - LOG.log(Level.SEVERE,"encoding problem",uee); + LOG.log(Level.SEVERE, "encoding problem", uee); } } @@ -769,7 +841,7 @@ public abstract class NanoHTTPD { outputStream.flush(); safeClose(data); } catch (IOException ioe) { - LOG.log(Level.SEVERE, "Could not send response to the client", ioe); + LOG.log(Level.SEVERE, "Could not send response to the client", ioe); } } @@ -784,7 +856,7 @@ public abstract class NanoHTTPD { } } - pw.print("Content-Length: "+ size +"\r\n"); + pw.print("Content-Length: " + size + "\r\n"); return size; } @@ -870,7 +942,9 @@ public abstract class NanoHTTPD { } public interface IStatus { + int getRequestStatus(); + String getDescription(); } @@ -878,11 +952,24 @@ public abstract class NanoHTTPD { * Some HTTP response status codes */ public enum Status implements IStatus { - SWITCH_PROTOCOL(101, "Switching Protocols"), OK(200, "OK"), CREATED(201, "Created"), ACCEPTED(202, "Accepted"), NO_CONTENT(204, "No Content"), PARTIAL_CONTENT(206, "Partial Content"), REDIRECT(301, - "Moved Permanently"), NOT_MODIFIED(304, "Not Modified"), BAD_REQUEST(400, "Bad Request"), UNAUTHORIZED(401, - "Unauthorized"), FORBIDDEN(403, "Forbidden"), NOT_FOUND(404, "Not Found"), METHOD_NOT_ALLOWED(405, "Method Not Allowed"), RANGE_NOT_SATISFIABLE(416, - "Requested Range Not Satisfiable"), INTERNAL_ERROR(500, "Internal Server Error"); + SWITCH_PROTOCOL(101, "Switching Protocols"), + OK(200, "OK"), + CREATED(201, "Created"), + ACCEPTED(202, "Accepted"), + NO_CONTENT(204, "No Content"), + PARTIAL_CONTENT(206, "Partial Content"), + REDIRECT(301, "Moved Permanently"), + NOT_MODIFIED(304, "Not Modified"), + BAD_REQUEST(400, "Bad Request"), + UNAUTHORIZED(401, "Unauthorized"), + FORBIDDEN(403, "Forbidden"), + NOT_FOUND(404, "Not Found"), + METHOD_NOT_ALLOWED(405, "Method Not Allowed"), + RANGE_NOT_SATISFIABLE(416, "Requested Range Not Satisfiable"), + INTERNAL_ERROR(500, "Internal Server Error"); + private final int requestStatus; + private final String description; Status(int requestStatus, String description) { @@ -903,6 +990,7 @@ public abstract class NanoHTTPD { } public static final class ResponseException extends Exception { + private static final long serialVersionUID = 6569838532917408380L; private final Response.Status status; @@ -926,6 +1014,7 @@ public abstract class NanoHTTPD { * Default strategy for creating and cleaning up temporary files. */ private class DefaultTempFileManagerFactory implements TempFileManagerFactory { + @Override public TempFileManager create() { return new DefaultTempFileManager(); @@ -933,9 +1022,11 @@ public abstract class NanoHTTPD { } /** - * Handles one session, i.e. parses the HTTP request and returns the response. + * Handles one session, i.e. parses the HTTP request and returns the + * response. */ public interface IHTTPSession { + void execute() throws IOException; Map<String, String> getParms(); @@ -957,24 +1048,39 @@ public abstract class NanoHTTPD { /** * Adds the files in the request body to the files map. - * @param files map to modify + * + * @param files + * map to modify */ void parseBody(Map<String, String> files) throws IOException, ResponseException; } protected class HTTPSession implements IHTTPSession { + public static final int BUFSIZE = 8192; + private final TempFileManager tempFileManager; + private final OutputStream outputStream; + private PushbackInputStream inputStream; + private int splitbyte; + private int rlen; + private String uri; + private Method method; + private Map<String, String> parms; + private Map<String, String> headers; + private CookieHandler cookies; + private String queryParameterString; + private String remoteIp; public HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) { @@ -997,7 +1103,8 @@ public abstract class NanoHTTPD { // Read the first 8192 bytes. // The full header should fit in here. // Apache's default header limit is 8KB. - // Do NOT assume that a single read will get the entire header at once! + // Do NOT assume that a single read will get the entire header + // at once! byte[] buf = new byte[BUFSIZE]; splitbyte = 0; rlen = 0; @@ -1030,17 +1137,16 @@ public abstract class NanoHTTPD { } parms = new HashMap<String, String>(); - if(null == headers) { + if (null == headers) { headers = new HashMap<String, String>(); } else { headers.clear(); } if (null != remoteIp) { - headers.put("remote-addr", remoteIp); - headers.put("http-client-ip", remoteIp); - } - + headers.put("remote-addr", remoteIp); + headers.put("http-client-ip", remoteIp); + } // Create a BufferedReader for parsing the header. BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen))); @@ -1074,7 +1180,7 @@ public abstract class NanoHTTPD { // treat socket timeouts the same way we treat socket exceptions // i.e. close the stream & finalAccept object by throwing the // exception up the call stack. - throw ste; + throw ste; } catch (IOException ioe) { Response r = new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); r.send(outputStream); @@ -1108,7 +1214,7 @@ public abstract class NanoHTTPD { // Now read all the body and write it to f byte[] buf = new byte[512]; while (rlen >= 0 && size > 0) { - rlen = inputStream.read(buf, 0, (int)Math.min(size, 512)); + rlen = inputStream.read(buf, 0, (int) Math.min(size, 512)); size -= rlen; if (rlen > 0) { randomAccessFile.write(buf, 0, rlen); @@ -1140,7 +1246,8 @@ public abstract class NanoHTTPD { if ("multipart/form-data".equalsIgnoreCase(contentType)) { // Handle multipart/form-data if (!st.hasMoreTokens()) { - throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html"); + throw new ResponseException(Response.Status.BAD_REQUEST, + "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html"); } String boundaryStartString = "boundary="; @@ -1164,10 +1271,12 @@ public abstract class NanoHTTPD { postLine = postLineBuffer.toString().trim(); // Handle application/x-www-form-urlencoded if ("application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) { - decodeParms(postLine, parms); + decodeParms(postLine, parms); } else if (postLine.length() != 0) { - // Special case for raw POST data => create a special files entry "postData" with raw content data - files.put("postData", postLine); + // Special case for raw POST data => create a + // special files entry "postData" with raw content + // data + files.put("postData", postLine); } } } else if (Method.PUT.equals(method)) { @@ -1182,8 +1291,7 @@ public abstract class NanoHTTPD { /** * Decodes the sent headers and loads the data into Key/value pairs */ - private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) - throws ResponseException { + private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) throws ResponseException { try { // Read the request line String inLine = in.readLine(); @@ -1237,15 +1345,15 @@ public abstract class NanoHTTPD { /** * Decodes the Multipart Body data and put it into Key/Value pairs. */ - private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms, - Map<String, String> files) throws ResponseException { + private void decodeMultipartData(String boundary, ByteBuffer fbuf, BufferedReader in, Map<String, String> parms, Map<String, String> files) throws ResponseException { try { int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes()); int boundarycount = 1; String mpline = in.readLine(); while (mpline != null) { if (!mpline.contains(boundary)) { - throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html"); + throw new ResponseException(Response.Status.BAD_REQUEST, + "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html"); } boundarycount++; Map<String, String> item = new HashMap<String, String>(); @@ -1260,7 +1368,8 @@ public abstract class NanoHTTPD { if (mpline != null) { String contentDisposition = item.get("content-disposition"); if (contentDisposition == null) { - throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html"); + throw new ResponseException(Response.Status.BAD_REQUEST, + "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html"); } StringTokenizer st = new StringTokenizer(contentDisposition, ";"); Map<String, String> disposition = new HashMap<String, String>(); @@ -1293,14 +1402,14 @@ public abstract class NanoHTTPD { } int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]); String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4); - if(!files.containsKey(pname)) { - files.put(pname, path); + if (!files.containsKey(pname)) { + files.put(pname, path); } else { - int count = 2; - while(files.containsKey(pname+count)) { - count++; - } - files.put(pname+count, path); + int count = 2; + while (files.containsKey(pname + count)) { + count++; + } + files.put(pname + count, path); } value = disposition.get("filename"); value = value.substring(1, value.length() - 1); @@ -1317,7 +1426,8 @@ public abstract class NanoHTTPD { } /** - * Find byte index separating header from body. It must be the last byte of the first two sequential new lines. + * Find byte index separating header from body. It must be the last byte + * of the first two sequential new lines. */ private int findHeaderEnd(final byte[] buf, int rlen) { int splitbyte = 0; @@ -1361,7 +1471,8 @@ public abstract class NanoHTTPD { } /** - * Retrieves the content of a sent file and saves it to a temporary file. The full path to the saved file is returned. + * Retrieves the content of a sent file and saves it to a temporary + * file. The full path to the saved file is returned. */ private String saveTmpFile(ByteBuffer b, int offset, int len) { String path = ""; @@ -1389,12 +1500,13 @@ public abstract class NanoHTTPD { TempFile tempFile = tempFileManager.createTempFile(); return new RandomAccessFile(tempFile.getName(), "rw"); } catch (Exception e) { - throw new Error(e); // we won't recover, so throw an error + throw new Error(e); // we won't recover, so throw an error } } /** - * It returns the offset separating multipart file headers from the file's data. + * It returns the offset separating multipart file headers from the + * file's data. */ private int stripMultipartHeaders(ByteBuffer b, int offset) { int i; @@ -1407,8 +1519,10 @@ public abstract class NanoHTTPD { } /** - * Decodes parameters in percent-encoded URI-format ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and - * adds them to given Map. NOTE: this doesn't support multiple identical keys due to the simplicity of Map. + * Decodes parameters in percent-encoded URI-format ( e.g. + * "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given + * Map. NOTE: this doesn't support multiple identical keys due to the + * simplicity of Map. */ private void decodeParms(String parms, Map<String, String> p) { if (parms == null) { @@ -1422,8 +1536,7 @@ public abstract class NanoHTTPD { String e = st.nextToken(); int sep = e.indexOf('='); if (sep >= 0) { - p.put(decodePercent(e.substring(0, sep)).trim(), - decodePercent(e.substring(sep + 1))); + p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1))); } else { p.put(decodePercent(e).trim(), ""); } @@ -1435,7 +1548,7 @@ public abstract class NanoHTTPD { return parms; } - public String getQueryParameterString() { + public String getQueryParameterString() { return queryParameterString; } @@ -1466,6 +1579,7 @@ public abstract class NanoHTTPD { } public static class Cookie { + private String n, v, e; public Cookie(String name, String value, String expires) { @@ -1499,14 +1613,16 @@ public abstract class NanoHTTPD { } /** - * Provides rudimentary support for cookies. - * Doesn't support 'path', 'secure' nor 'httpOnly'. - * Feel free to improve it and/or add unsupported features. - * + * Provides rudimentary support for cookies. Doesn't support 'path', + * 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported + * features. + * * @author LordFokas */ public class CookieHandler implements Iterable<String> { + private HashMap<String, String> cookies = new HashMap<String, String>(); + private ArrayList<Cookie> queue = new ArrayList<Cookie>(); public CookieHandler(Map<String, String> httpHeaders) { @@ -1522,14 +1638,16 @@ public abstract class NanoHTTPD { } } - @Override public Iterator<String> iterator() { + @Override + public Iterator<String> iterator() { return cookies.keySet().iterator(); } /** * Read a cookie from the HTTP Headers. - * - * @param name The cookie's name. + * + * @param name + * The cookie's name. * @return The cookie's value if it exists, null otherwise. */ public String read(String name) { @@ -1538,10 +1656,13 @@ public abstract class NanoHTTPD { /** * Sets a cookie. - * - * @param name The cookie's name. - * @param value The cookie's value. - * @param expires How many days until the cookie expires. + * + * @param name + * The cookie's name. + * @param value + * The cookie's value. + * @param expires + * How many days until the cookie expires. */ public void set(String name, String value, int expires) { queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires))); @@ -1552,18 +1673,23 @@ public abstract class NanoHTTPD { } /** - * Set a cookie with an expiration date from a month ago, effectively deleting it on the client side. - * - * @param name The cookie name. + * Set a cookie with an expiration date from a month ago, effectively + * deleting it on the client side. + * + * @param name + * The cookie name. */ public void delete(String name) { set(name, "-delete-", -30); } /** - * Internally used by the webserver to add all queued cookies into the Response's HTTP Headers. - * - * @param response The Response object to which headers the queued cookies will be added. + * Internally used by the webserver to add all queued cookies into the + * Response's HTTP Headers. + * + * @param response + * The Response object to which headers the queued cookies + * will be added. */ public void unloadQueue(Response response) { for (Cookie cookie : queue) { diff --git a/core/src/test/java/fi/iki/elonen/HttpChunkedResponseTest.java b/core/src/test/java/fi/iki/elonen/HttpChunkedResponseTest.java index ab0ba3e..779e43f 100644 --- a/core/src/test/java/fi/iki/elonen/HttpChunkedResponseTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpChunkedResponseTest.java @@ -40,29 +40,30 @@ import java.io.PipedInputStream; import static fi.iki.elonen.NanoHTTPD.Response.Status.OK; public class HttpChunkedResponseTest extends HttpServerTest { + @org.junit.Test public void thatChunkedContentIsChunked() throws Exception { PipedInputStream pipedInputStream = new ChunkedInputStream(new String[]{ - "some", - "thing which is longer than sixteen characters", - "whee!", - "" + "some", + "thing which is longer than sixteen characters", + "whee!", + "" }); String[] expected = { - "HTTP/1.1 200 OK", - "Content-Type: what/ever", - "Date: .*", - "Connection: keep-alive", - "Transfer-Encoding: chunked", - "", - "4", - "some", - "2d", - "thing which is longer than sixteen characters", - "5", - "whee!", - "0", - "" + "HTTP/1.1 200 OK", + "Content-Type: what/ever", + "Date: .*", + "Connection: keep-alive", + "Transfer-Encoding: chunked", + "", + "4", + "some", + "2d", + "thing which is longer than sixteen characters", + "5", + "whee!", + "0", + "" }; testServer.response = new NanoHTTPD.Response(OK, "what/ever", pipedInputStream); testServer.response.setChunkedTransfer(true); @@ -73,7 +74,9 @@ public class HttpChunkedResponseTest extends HttpServerTest { } private static class ChunkedInputStream extends PipedInputStream { + int chunk = 0; + String[] chunks; private ChunkedInputStream(String[] chunks) { diff --git a/core/src/test/java/fi/iki/elonen/HttpDeleteRequestTest.java b/core/src/test/java/fi/iki/elonen/HttpDeleteRequestTest.java index b9883a3..4756b1d 100644 --- a/core/src/test/java/fi/iki/elonen/HttpDeleteRequestTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpDeleteRequestTest.java @@ -50,12 +50,12 @@ public class HttpDeleteRequestTest extends HttpServerTest { ByteArrayOutputStream outputStream = invokeServer("DELETE " + URI + " HTTP/1.1"); String[] expected = { - "HTTP/1.1 204 No Content", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 0", - "" + "HTTP/1.1 204 No Content", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 0", + "" }; assertResponse(outputStream, expected); @@ -63,17 +63,17 @@ public class HttpDeleteRequestTest extends HttpServerTest { @Test public void testDeleteRequestThatDoesntSendBackResponseBody_NullString() throws Exception { - testServer.response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NO_CONTENT, NanoHTTPD.MIME_HTML, (String)null); + testServer.response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NO_CONTENT, NanoHTTPD.MIME_HTML, (String) null); ByteArrayOutputStream outputStream = invokeServer("DELETE " + URI + " HTTP/1.1"); String[] expected = { - "HTTP/1.1 204 No Content", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 0", - "" + "HTTP/1.1 204 No Content", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 0", + "" }; assertResponse(outputStream, expected); @@ -81,17 +81,17 @@ public class HttpDeleteRequestTest extends HttpServerTest { @Test public void testDeleteRequestThatDoesntSendBackResponseBody_NullInputStream() throws Exception { - testServer.response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NO_CONTENT, NanoHTTPD.MIME_HTML, (InputStream)null); + testServer.response = new NanoHTTPD.Response(NanoHTTPD.Response.Status.NO_CONTENT, NanoHTTPD.MIME_HTML, (InputStream) null); ByteArrayOutputStream outputStream = invokeServer("DELETE " + URI + " HTTP/1.1"); String[] expected = { - "HTTP/1.1 204 No Content", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 0", - "" + "HTTP/1.1 204 No Content", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 0", + "" }; assertResponse(outputStream, expected); @@ -104,13 +104,13 @@ public class HttpDeleteRequestTest extends HttpServerTest { ByteArrayOutputStream outputStream = invokeServer("DELETE " + URI + " HTTP/1.1"); String[] expected = { - "HTTP/1.1 200 OK", - "Content-Type: application/xml", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 8", - "", - "<body />" + "HTTP/1.1 200 OK", + "Content-Type: application/xml", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 8", + "", + "<body />" }; assertResponse(outputStream, expected); @@ -123,13 +123,13 @@ public class HttpDeleteRequestTest extends HttpServerTest { ByteArrayOutputStream outputStream = invokeServer("DELETE " + URI + " HTTP/1.1"); String[] expected = { - "HTTP/1.1 202 Accepted", - "Content-Type: application/xml", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 8", - "", - "<body />" + "HTTP/1.1 202 Accepted", + "Content-Type: application/xml", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 8", + "", + "<body />" }; assertResponse(outputStream, expected); diff --git a/core/src/test/java/fi/iki/elonen/HttpGetRequestTest.java b/core/src/test/java/fi/iki/elonen/HttpGetRequestTest.java index aa31397..9980d2e 100644 --- a/core/src/test/java/fi/iki/elonen/HttpGetRequestTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpGetRequestTest.java @@ -47,12 +47,12 @@ public class HttpGetRequestTest extends HttpServerTest { ByteArrayOutputStream outputStream = invokeServer("GET " + URI + " HTTP/1.1"); String[] expected = { - "HTTP/1.1 200 OK", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 0", - "" + "HTTP/1.1 200 OK", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 0", + "" }; assertResponse(outputStream, expected); @@ -65,13 +65,13 @@ public class HttpGetRequestTest extends HttpServerTest { ByteArrayOutputStream outputStream = invokeServer("GET " + URI + " HTTP/1.1"); String[] expected = { - "HTTP/1.1 200 OK", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 8", - "", - responseBody + "HTTP/1.1 200 OK", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 8", + "", + responseBody }; assertResponse(outputStream, expected); @@ -199,6 +199,7 @@ public class HttpGetRequestTest extends HttpServerTest { invokeServer("GET " + URI + "?foo=bar&foo=baz&zot&zim= HTTP/1.1"); assertEquals(testServer.decodedParamters, testServer.decodedParamtersFromParameter); } - // -------------------------------------------------------------------------------------------------------- // + // -------------------------------------------------------------------------------------------------------- + // // } diff --git a/core/src/test/java/fi/iki/elonen/HttpHeadRequestTest.java b/core/src/test/java/fi/iki/elonen/HttpHeadRequestTest.java index 2368211..2602fd9 100644 --- a/core/src/test/java/fi/iki/elonen/HttpHeadRequestTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpHeadRequestTest.java @@ -41,6 +41,7 @@ import java.util.List; import static junit.framework.Assert.*; public class HttpHeadRequestTest extends HttpServerTest { + @Override public void setUp() { super.setUp(); @@ -53,12 +54,12 @@ public class HttpHeadRequestTest extends HttpServerTest { ByteArrayOutputStream outputStream = invokeServer("HEAD " + URI + " HTTP/1.1"); String[] expected = { - "HTTP/1.1 200 OK", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 8", - "" + "HTTP/1.1 200 OK", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 8", + "" }; assertResponse(outputStream, expected); @@ -186,6 +187,7 @@ public class HttpHeadRequestTest extends HttpServerTest { invokeServer("HEAD " + URI + "?foo=bar&foo=baz&zot&zim= HTTP/1.1"); assertEquals(testServer.decodedParamters, testServer.decodedParamtersFromParameter); } - // -------------------------------------------------------------------------------------------------------- // + // -------------------------------------------------------------------------------------------------------- + // // } diff --git a/core/src/test/java/fi/iki/elonen/HttpKeepAliveTest.java b/core/src/test/java/fi/iki/elonen/HttpKeepAliveTest.java index a20f60a..829d5c5 100644 --- a/core/src/test/java/fi/iki/elonen/HttpKeepAliveTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpKeepAliveTest.java @@ -47,41 +47,46 @@ public class HttpKeepAliveTest extends HttpServerTest { public void testManyGetRequests() throws Exception { String request = "GET " + URI + " HTTP/1.1\r\n\r\n"; String[] expected = { - "HTTP/1.1 200 OK", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 0", - "" + "HTTP/1.1 200 OK", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 0", + "" }; testManyRequests(request, expected); } - + @Test public void testManyPutRequests() throws Exception { String data = "BodyData 1\nLine 2"; String request = "PUT " + URI + " HTTP/1.1\r\nContent-Length: " + data.length() + "\r\n\r\n" + data; String[] expected = { - "HTTP/1.1 200 OK", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 0", - "" + "HTTP/1.1 200 OK", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 0", + "" }; testManyRequests(request, expected); } private Throwable error = null; - + /** - * Issue the given request many times to check whether an error occurs. - * For this test, a small stack size is used, since a stack overflow is among the possible errors. - * @param request The request to issue - * @param expected The expected response + * Issue the given request many times to check whether an error occurs. For + * this test, a small stack size is used, since a stack overflow is among + * the possible errors. + * + * @param request + * The request to issue + * @param expected + * The expected response */ public void testManyRequests(final String request, final String[] expected) throws Exception { Runnable r = new Runnable() { + public void run() { try { PipedOutputStream requestStream = new PipedOutputStream(); @@ -108,7 +113,7 @@ public class HttpKeepAliveTest extends HttpServerTest { t.start(); t.join(); if (error != null) { - fail(""+error); + fail("" + error); error.printStackTrace(); } } diff --git a/core/src/test/java/fi/iki/elonen/HttpParsingTest.java b/core/src/test/java/fi/iki/elonen/HttpParsingTest.java index 7780651..9879bbe 100644 --- a/core/src/test/java/fi/iki/elonen/HttpParsingTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpParsingTest.java @@ -41,6 +41,7 @@ import java.net.URLEncoder; import static junit.framework.Assert.assertEquals; public class HttpParsingTest extends HttpServerTest { + @Test public void testNormalCharacters() throws Exception { for (int i = 0x20; i < 0x80; i++) { diff --git a/core/src/test/java/fi/iki/elonen/HttpPostRequestTest.java b/core/src/test/java/fi/iki/elonen/HttpPostRequestTest.java index 4853b00..c83a18d 100644 --- a/core/src/test/java/fi/iki/elonen/HttpPostRequestTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpPostRequestTest.java @@ -47,11 +47,17 @@ import static junit.framework.Assert.assertEquals; public class HttpPostRequestTest extends HttpServerTest { public static final String CONTENT_LENGTH = "Content-Length: "; + public static final String FIELD = "caption"; + public static final String VALUE = "Summer vacation"; + public static final String FIELD2 = "location"; + public static final String VALUE2 = "Grand Canyon"; + public static final String POST_RAW_CONTENT_FILE_ENTRY = "postData"; + public static final String VALUE_TEST_SIMPLE_RAW_DATA_WITH_AMPHASIS = "Test raw data & Result value"; @Test @@ -61,7 +67,7 @@ public class HttpPostRequestTest extends HttpServerTest { int size = content.length() + header.length(); int contentLengthHeaderValueSize = String.valueOf(size).length(); int contentLength = size + contentLengthHeaderValueSize + CONTENT_LENGTH.length(); - String input = header + CONTENT_LENGTH + (contentLength+4) + "\r\n\r\n" + content; + String input = header + CONTENT_LENGTH + (contentLength + 4) + "\r\n\r\n" + content; invokeServer(input); assertEquals(0, testServer.parms.size()); assertEquals(1, testServer.files.size()); @@ -71,17 +77,12 @@ public class HttpPostRequestTest extends HttpServerTest { @Test public void testSimplePostWithSingleMultipartFormField() throws Exception { String divider = UUID.randomUUID().toString(); - String header = "POST " + URI + " HTTP/1.1\nContent-Type: " + - "multipart/form-data; boundary=" + divider + "\n"; - String content = "--" + divider + "\n" + - "Content-Disposition: form-data; name=\""+FIELD+"\"\n" + - "\n" + - VALUE +"\n" + - "--" + divider + "--\n"; + String header = "POST " + URI + " HTTP/1.1\nContent-Type: " + "multipart/form-data; boundary=" + divider + "\n"; + String content = "--" + divider + "\n" + "Content-Disposition: form-data; name=\"" + FIELD + "\"\n" + "\n" + VALUE + "\n" + "--" + divider + "--\n"; int size = content.length() + header.length(); int contentLengthHeaderValueSize = String.valueOf(size).length(); int contentLength = size + contentLengthHeaderValueSize + CONTENT_LENGTH.length(); - String input = header + CONTENT_LENGTH + (contentLength+4) + "\r\n\r\n" + content; + String input = header + CONTENT_LENGTH + (contentLength + 4) + "\r\n\r\n" + content; invokeServer(input); assertEquals(1, testServer.parms.size()); @@ -91,20 +92,14 @@ public class HttpPostRequestTest extends HttpServerTest { @Test public void testPostWithMultipleMultipartFormFields() throws Exception { String divider = UUID.randomUUID().toString(); - String header = "POST " + URI + " HTTP/1.1\nContent-Type: " + - "multipart/form-data; boundary=" + divider + "\n"; - String content = "--" + divider + "\n" + - "Content-Disposition: form-data; name=\""+FIELD+"\"\n" + - "\n" + - VALUE +"\n" +"--" + divider + "\n" + - "Content-Disposition: form-data; name=\""+FIELD2+"\"\n" + - "\n" + - VALUE2 +"\n" + - "--" + divider + "--\n"; + String header = "POST " + URI + " HTTP/1.1\nContent-Type: " + "multipart/form-data; boundary=" + divider + "\n"; + String content = + "--" + divider + "\n" + "Content-Disposition: form-data; name=\"" + FIELD + "\"\n" + "\n" + VALUE + "\n" + "--" + divider + "\n" + + "Content-Disposition: form-data; name=\"" + FIELD2 + "\"\n" + "\n" + VALUE2 + "\n" + "--" + divider + "--\n"; int size = content.length() + header.length(); int contentLengthHeaderValueSize = String.valueOf(size).length(); int contentLength = size + contentLengthHeaderValueSize + CONTENT_LENGTH.length(); - String input = header + CONTENT_LENGTH + (contentLength+4) + "\r\n\r\n" + content; + String input = header + CONTENT_LENGTH + (contentLength + 4) + "\r\n\r\n" + content; invokeServer(input); assertEquals(2, testServer.parms.size()); @@ -115,75 +110,71 @@ public class HttpPostRequestTest extends HttpServerTest { @Test public void testPostWithMultipleMultipartFormFieldsWhereContentTypeWasSeparatedByComma() throws Exception { String divider = UUID.randomUUID().toString(); - String header = "POST " + URI + " HTTP/1.1\nContent-Type: " + - "multipart/form-data, boundary=" + divider + "\n"; - String content = "--" + divider + "\n" + - "Content-Disposition: form-data; name=\""+FIELD+"\"\n" + - "\n" + - VALUE +"\n" +"--" + divider + "\n" + - "Content-Disposition: form-data; name=\""+FIELD2+"\"\n" + - "\n" + - VALUE2 +"\n" + - "--" + divider + "--\n"; + String header = "POST " + URI + " HTTP/1.1\nContent-Type: " + "multipart/form-data, boundary=" + divider + "\n"; + String content = + "--" + divider + "\n" + "Content-Disposition: form-data; name=\"" + FIELD + "\"\n" + "\n" + VALUE + "\n" + "--" + divider + "\n" + + "Content-Disposition: form-data; name=\"" + FIELD2 + "\"\n" + "\n" + VALUE2 + "\n" + "--" + divider + "--\n"; int size = content.length() + header.length(); int contentLengthHeaderValueSize = String.valueOf(size).length(); int contentLength = size + contentLengthHeaderValueSize + CONTENT_LENGTH.length(); - String input = header + CONTENT_LENGTH + (contentLength+4) + "\r\n\r\n" + content; + String input = header + CONTENT_LENGTH + (contentLength + 4) + "\r\n\r\n" + content; invokeServer(input); assertEquals(2, testServer.parms.size()); assertEquals(VALUE, testServer.parms.get(FIELD)); assertEquals(VALUE2, testServer.parms.get(FIELD2)); } - + @Test public void testPostWithMultipartFormUpload() throws Exception { String filename = "GrandCanyon.txt"; String fileContent = VALUE; String input = preparePostWithMultipartForm(filename, fileContent); - + invokeServer(input); - + assertEquals(1, testServer.parms.size()); BufferedReader reader = new BufferedReader(new FileReader(testServer.files.get(FIELD))); List<String> lines = readLinesFromFile(reader); - assertLinesOfText(new String[]{fileContent}, lines); + assertLinesOfText(new String[]{ + fileContent + }, lines); } - + @Test public void testPostWithMultipartFormUploadFilenameHasSpaces() throws Exception { - String fileNameWithSpace = "Grand Canyon.txt"; - String fileContent = VALUE; - String input = preparePostWithMultipartForm(fileNameWithSpace, fileContent); - - invokeServer(input); - - String fileNameAfter = new ArrayList<String>(testServer.parms.values()).get(0); - - assertEquals(fileNameWithSpace, fileNameAfter); + String fileNameWithSpace = "Grand Canyon.txt"; + String fileContent = VALUE; + String input = preparePostWithMultipartForm(fileNameWithSpace, fileContent); + + invokeServer(input); + + String fileNameAfter = new ArrayList<String>(testServer.parms.values()).get(0); + + assertEquals(fileNameWithSpace, fileNameAfter); } - + /** * contains common preparation steps for testing POST with Multipart Form - * @param fileName Name of file to be uploaded - * @param fileContent Content of file to be uploaded - * @return input String with POST request complete information including header, length and content + * + * @param fileName + * Name of file to be uploaded + * @param fileContent + * Content of file to be uploaded + * @return input String with POST request complete information including + * header, length and content */ private String preparePostWithMultipartForm(String fileName, String fileContent) { String divider = UUID.randomUUID().toString(); - String header = "POST " + URI + " HTTP/1.1\nContent-Type: " + - "multipart/form-data, boundary=" + divider + "\n"; - String content = "--" + divider + "\n" + - "Content-Disposition: form-data; name=\""+FIELD+"\"; filename=\""+fileName+"\"\n" + - "Content-Type: image/jpeg\r\n"+ - "\r\n" + - fileContent +"\r\n" + - "--" + divider + "--\n"; + String header = "POST " + URI + " HTTP/1.1\nContent-Type: " + "multipart/form-data, boundary=" + divider + "\n"; + String content = + "--" + divider + "\n" + "Content-Disposition: form-data; name=\"" + FIELD + "\"; filename=\"" + fileName + "\"\n" + "Content-Type: image/jpeg\r\n" + "\r\n" + + fileContent + "\r\n" + "--" + divider + "--\n"; int size = content.length() + header.length(); int contentLengthHeaderValueSize = String.valueOf(size).length(); int contentLength = size + contentLengthHeaderValueSize + CONTENT_LENGTH.length(); - String input = header + CONTENT_LENGTH + (contentLength+5) + "\r\n\r\n" + content; - + String input = header + CONTENT_LENGTH + (contentLength + 5) + "\r\n\r\n" + content; + return input; } diff --git a/core/src/test/java/fi/iki/elonen/HttpPutRequestTest.java b/core/src/test/java/fi/iki/elonen/HttpPutRequestTest.java index 71f3f97..e2755f9 100644 --- a/core/src/test/java/fi/iki/elonen/HttpPutRequestTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpPutRequestTest.java @@ -49,12 +49,12 @@ public class HttpPutRequestTest extends HttpServerTest { ByteArrayOutputStream outputStream = invokeServer("PUT " + URI + " HTTP/1.1\r\n\r\nBodyData 1\nLine 2"); String[] expectedOutput = { - "HTTP/1.1 200 OK", - "Content-Type: text/html", - "Date: .*", - "Connection: keep-alive", - "Content-Length: 0", - "" + "HTTP/1.1 200 OK", + "Content-Type: text/html", + "Date: .*", + "Connection: keep-alive", + "Content-Length: 0", + "" }; assertResponse(outputStream, expectedOutput); @@ -63,8 +63,8 @@ public class HttpPutRequestTest extends HttpServerTest { BufferedReader reader = null; try { String[] expectedInputToServeMethodViaFile = { - "BodyData 1", - "Line 2" + "BodyData 1", + "Line 2" }; reader = new BufferedReader(new FileReader(testServer.files.get("content"))); List<String> lines = readLinesFromFile(reader); diff --git a/core/src/test/java/fi/iki/elonen/HttpServerTest.java b/core/src/test/java/fi/iki/elonen/HttpServerTest.java index 82454bc..f7fbb7b 100644 --- a/core/src/test/java/fi/iki/elonen/HttpServerTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpServerTest.java @@ -47,12 +47,14 @@ import java.util.Map; import static junit.framework.Assert.*; /** - * @author Paul S. Hawke (paul.hawke@gmail.com) - * On: 3/10/13 at 8:32 PM + * @author Paul S. Hawke (paul.hawke@gmail.com) On: 3/10/13 at 8:32 PM */ public class HttpServerTest { + public static final String URI = "http://www.myserver.org/pub/WWW/someFile.html"; + protected TestServer testServer; + private TestTempFileManager tempFileManager; @Before @@ -77,12 +79,10 @@ public class HttpServerTest { } protected void assertLinesOfText(String[] expected, List<String> lines) { -// assertEquals(expected.length, lines.size()); + // assertEquals(expected.length, lines.size()); for (int i = 0; i < expected.length; i++) { String line = lines.get(i); - assertTrue("Output line " + i + " doesn't match expectation.\n" + - " Output: " + line + "\n" + - "Expected: " + expected[i], line.matches(expected[i])); + assertTrue("Output line " + i + " doesn't match expectation.\n" + " Output: " + line + "\n" + "Expected: " + expected[i], line.matches(expected[i])); } } @@ -93,7 +93,7 @@ public class HttpServerTest { try { session.execute(); } catch (IOException e) { - fail(""+e); + fail("" + e); e.printStackTrace(); } return outputStream; @@ -117,6 +117,7 @@ public class HttpServerTest { } public static class TestTempFileManager extends NanoHTTPD.DefaultTempFileManager { + public void _clear() { super.clear(); } @@ -128,14 +129,23 @@ public class HttpServerTest { } public static class TestServer extends NanoHTTPD { + public Response response = new Response(""); + public String uri; + public Method method; + public Map<String, String> header; + public Map<String, String> parms; + public Map<String, String> files; + public Map<String, List<String>> decodedParamters; + public Map<String, List<String>> decodedParamtersFromParameter; + public String queryParameterString; public TestServer() { @@ -150,7 +160,8 @@ public class HttpServerTest { return new HTTPSession(tempFileManager, inputStream, outputStream, inetAddress); } - @Override public Response serve(IHTTPSession session) { + @Override + public Response serve(IHTTPSession session) { this.uri = session.getUri(); this.method = session.getMethod(); this.header = session.getHeaders(); diff --git a/core/src/test/java/fi/iki/elonen/HttpSessionHeadersTest.java b/core/src/test/java/fi/iki/elonen/HttpSessionHeadersTest.java index a3d0f81..3402533 100644 --- a/core/src/test/java/fi/iki/elonen/HttpSessionHeadersTest.java +++ b/core/src/test/java/fi/iki/elonen/HttpSessionHeadersTest.java @@ -43,7 +43,9 @@ import java.net.InetAddress; import static org.junit.Assert.assertEquals; public class HttpSessionHeadersTest extends HttpServerTest { + private static final String DUMMY_REQUEST_CONTENT = "dummy request content"; + private static final TestTempFileManager TEST_TEMP_FILE_MANAGER = new TestTempFileManager(); @Override @@ -56,8 +58,12 @@ public class HttpSessionHeadersTest extends HttpServerTest { public void testHeadersRemoteIp() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream(DUMMY_REQUEST_CONTENT.getBytes()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - String[] ipAddresses = { "127.0.0.1", "192.168.1.1", "192.30.252.129" }; - for(String ipAddress : ipAddresses) { + String[] ipAddresses = { + "127.0.0.1", + "192.168.1.1", + "192.30.252.129" + }; + for (String ipAddress : ipAddresses) { InetAddress inetAddress = InetAddress.getByName(ipAddress); NanoHTTPD.HTTPSession session = testServer.createSession(TEST_TEMP_FILE_MANAGER, inputStream, outputStream, inetAddress); assertEquals(ipAddress, session.getHeaders().get("remote-addr")); diff --git a/core/src/test/java/fi/iki/elonen/InvalidRequestTest.java b/core/src/test/java/fi/iki/elonen/InvalidRequestTest.java index fd3d196..2c40cd1 100644 --- a/core/src/test/java/fi/iki/elonen/InvalidRequestTest.java +++ b/core/src/test/java/fi/iki/elonen/InvalidRequestTest.java @@ -41,7 +41,7 @@ public class InvalidRequestTest extends HttpServerTest { @Test public void testGetRequestWithoutProtocol() { - invokeServer("GET " + URI + "\r\nX-Important-Header: foo" ); + invokeServer("GET " + URI + "\r\nX-Important-Header: foo"); assertNotNull(testServer.parms); assertTrue(testServer.header.size() > 0); @@ -58,10 +58,9 @@ public class InvalidRequestTest extends HttpServerTest { assertNotNull(testServer.uri); } - @Test public void testGetRequestWithProtocol() { - invokeServer("GET " + URI + " HTTP/1.1\r\nX-Important-Header: foo" ); + invokeServer("GET " + URI + " HTTP/1.1\r\nX-Important-Header: foo"); assertNotNull(testServer.parms); assertTrue(testServer.header.size() > 0); @@ -77,4 +76,4 @@ public class InvalidRequestTest extends HttpServerTest { assertNotNull(testServer.files); assertNotNull(testServer.uri); } -}
\ No newline at end of file +} diff --git a/core/src/test/java/fi/iki/elonen/integration/CookieIntegrationTest.java b/core/src/test/java/fi/iki/elonen/integration/CookieIntegrationTest.java index 7a8cfcb..f765a38 100644 --- a/core/src/test/java/fi/iki/elonen/integration/CookieIntegrationTest.java +++ b/core/src/test/java/fi/iki/elonen/integration/CookieIntegrationTest.java @@ -48,8 +48,7 @@ import java.util.List; import static org.junit.Assert.*; /** - * @author Paul S. Hawke (paul.hawke@gmail.com) - * On: 9/2/13 at 10:10 PM + * @author Paul S. Hawke (paul.hawke@gmail.com) On: 9/2/13 at 10:10 PM */ public class CookieIntegrationTest extends IntegrationTestBase<CookieIntegrationTest.CookieTestServer> { @@ -92,19 +91,23 @@ public class CookieIntegrationTest extends IntegrationTestBase<CookieIntegration assertTrue(testServer.cookiesReceived.get(0).getHTTPHeader().contains("name=value")); } - @Override public CookieTestServer createTestServer() { + @Override + public CookieTestServer createTestServer() { return new CookieTestServer(); } public static class CookieTestServer extends NanoHTTPD { + List<Cookie> cookiesReceived = new ArrayList<Cookie>(); + List<Cookie> cookiesToSend = new ArrayList<Cookie>(); public CookieTestServer() { super(8192); } - @Override public Response serve(IHTTPSession session) { + @Override + public Response serve(IHTTPSession session) { CookieHandler cookies = session.getCookies(); for (String cookieName : cookies) { cookiesReceived.add(new Cookie(cookieName, cookies.read(cookieName))); diff --git a/core/src/test/java/fi/iki/elonen/integration/GetAndPostIntegrationTest.java b/core/src/test/java/fi/iki/elonen/integration/GetAndPostIntegrationTest.java index 97adafa..ea4041d 100644 --- a/core/src/test/java/fi/iki/elonen/integration/GetAndPostIntegrationTest.java +++ b/core/src/test/java/fi/iki/elonen/integration/GetAndPostIntegrationTest.java @@ -59,8 +59,7 @@ import java.util.Map; import static org.junit.Assert.assertEquals; /** - * @author Paul S. Hawke (paul.hawke@gmail.com) - * On: 5/19/13 at 5:36 PM + * @author Paul S. Hawke (paul.hawke@gmail.com) On: 5/19/13 at 5:36 PM */ public class GetAndPostIntegrationTest extends IntegrationTestBase<GetAndPostIntegrationTest.TestServer> { @@ -129,11 +128,13 @@ public class GetAndPostIntegrationTest extends IntegrationTestBase<GetAndPostInt assertEquals("POST:testPostRequestWithMultipartEncodedParameters-params=2;age=120;gender=Male", responseBody); } - @Override public TestServer createTestServer() { + @Override + public TestServer createTestServer() { return new TestServer(); } public static class TestServer extends NanoHTTPD { + public String response; public TestServer() { diff --git a/core/src/test/java/fi/iki/elonen/integration/IntegrationTestBase.java b/core/src/test/java/fi/iki/elonen/integration/IntegrationTestBase.java index 6940f48..9ad6b73 100644 --- a/core/src/test/java/fi/iki/elonen/integration/IntegrationTestBase.java +++ b/core/src/test/java/fi/iki/elonen/integration/IntegrationTestBase.java @@ -42,11 +42,12 @@ import org.junit.Before; import java.io.IOException; /** - * @author Paul S. Hawke (paul.hawke@gmail.com) - * On: 9/2/13 at 10:02 PM + * @author Paul S. Hawke (paul.hawke@gmail.com) On: 9/2/13 at 10:02 PM */ public abstract class IntegrationTestBase<T extends NanoHTTPD> { + protected DefaultHttpClient httpclient; + protected T testServer; @Before diff --git a/core/src/test/java/fi/iki/elonen/integration/PutStreamIntegrationTest.java b/core/src/test/java/fi/iki/elonen/integration/PutStreamIntegrationTest.java index 8a80b01..6bdde4d 100644 --- a/core/src/test/java/fi/iki/elonen/integration/PutStreamIntegrationTest.java +++ b/core/src/test/java/fi/iki/elonen/integration/PutStreamIntegrationTest.java @@ -61,18 +61,19 @@ public class PutStreamIntegrationTest extends IntegrationTestBase<PutStreamInteg assertEquals("PUT:" + expected, responseBody); } - @Override public TestServer createTestServer() { + @Override + public TestServer createTestServer() { return new TestServer(); } public static class TestServer extends NanoHTTPD { + public TestServer() { super(8192); } @Override - public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) - { + public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) { throw new UnsupportedOperationException(); } @@ -87,8 +88,7 @@ public class PutStreamIntegrationTest extends IntegrationTestBase<PutStreamInteg DataInputStream dataInputStream = new DataInputStream(session.getInputStream()); body = new byte[contentLength]; dataInputStream.readFully(body, 0, contentLength); - } - catch(IOException e) { + } catch (IOException e) { return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, e.getMessage()); } |