| java.lang.Object net.homeip.donaldm.httpdbase4j.Httpd
All known Subclasses: net.homeip.donaldm.httpdbase4j.ArchiveHttpd, net.homeip.donaldm.httpdbase4j.FileHttpd,
Httpd | abstract public class Httpd implements HttpHandleable,Postable(Code) | | An embeddable Java web server that supports HTTP, HTTPS, templated
content and serving content from inside a jar or archive (Supported types: jar, zip,
tar, tar.gz, tar.bz2).
Based on the com.sun.net.httpserver.classes only available in Java 1.6.
(@see com.sun.net.httpserver or @link http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/overview-summary.html
Also supports templated generation of content using the StringTemplate
library @link http://www.stringtemplate.org
Usage
To create a simple embedded web server on port 8088 with a home directory
at homeDir in the local filesystem and a root url at / ie / maps onto homeDir:
homeDir = new java.io.File("./htdocs");
httpd = new FileHttpd(homeDir, 10); // Creates a server with a threadpool of 10
httpd.setLogger(System.err); // Log to console
httpd.start(8088, "/");
To create a HTTPS embedded web server on port 8088 with a home directory
at homeDir in the local filesystem and a root url at / ie / maps onto homeDir:
homeDir = new java.io.File("./htdocs");
httpd = new FileHttpd(homeDir, 10);
m_httpd.start(8089, "/", keystore, password);
HttpdBase4J also supports serving content from inside the class path ie from
in the jar file.
The code below creates a server with content located in directory
resources/htdocs in a jar in the classpath (normally the main jar).
httpd = new ArchiveHttpd("/resources/htdocs", 10);
httpd.start(8088, "/");
HttpdBase4J also supports serving content from a specified archive file
Supported formats: jar, zip, tar, tar.gz and tar.bz2.
The code below creates a server with content located in directory
resources/htdocs in archive file content.zip.
httpd = new ArchiveHttpd(new File("content.zip"), "/resources/htdocs", 10);
httpd.start(8088, "/");
Templated content can also be created. Currently the StringTemplate library
(@see http://www.stringtemplate.org) is used but it should be relatively
easy to create user derived classes for other template implementations.
To create an HTTP embedded web server on port 8088 serving templated content
from resources/htdocs in the classpath and having template file handler
(A Java class implenting the Templatable interface that is used to fill the
templates) in net.homeip.donaldm.test.templates:
httpd = new ArchiveHttpd("resources/htdocs", 10);
StringTemplateHandler stHandler = new ArchiveStringTemplateHandler(httpd,
"net.homeip.donaldm.test.templates");
httpd.addHandler(".st", stHandler); // .st extension = template files
httpd.start(m_port, "/");
To implement a embedded web server with POST handler for URL /post:
m_httpd = new FileHttpd(homeDir, 10);
httpd.addPostHandler("/post", postHandler); postHandler implements Postable
httpd.start(8088, "/");
The Httpd class also provides many overidable methods:
httpd = new TestOverideHttpd(m_homeDir, 10);
httpd.start(m_port, "/");
class TestOverideHttpd
{
public HttpResponse onServeHeaders(long id, HttpExchange ex, Request request)
{
//Create or amend content
}
public InputStream onServeBody(long id, HttpExchange ex, Request request)
{
// Return amended or created content
}
}
Some of the overidable methods include: onAllowDirectoryBrowse, onCreateExecutor,
onCreateRequestHandler, onFileNotFound, onAllowDirectoryBrowse, onListDirectory,
onPreServe, onPostServe etc. See the documention of HttpHandleable
See Also: FileHttpd See Also: ArchiveHttpd See Also: HttpHandleable See Also: Postable author: Donald Munro |
Inner Class :public enum ThreadModel | |
Inner Class :protected static enum LogLevel | |
Constructor Summary | |
public | Httpd() |
Method Summary | |
protected static void | Log(LogLevel level, String message, Throwable e) Log errors, information or warnings. | public void | addDefaultFile(String file) | public void | addHandler(String extension, HttpHandleable handler) Add a handler for an extension. | public void | addPostHandler(String name, Postable handler) Add a POST handler. | public boolean | getCaching() | public HttpHandleable | getHandler(String extension) Add a handler for an extension. | abstract public String | getHomePath() | public static long | getNextSequence() | public int | getPort() | public boolean | getVerbose() | public boolean | isStarted() | public boolean | onAllowDirectoryBrowse(String directory) | protected ExecutorService | onCreateExecutor() Overide to create the thread executor. | abstract protected HttpHandler | onCreateRequestHandler() | protected SSLContext | onCreateSSLConfiguration(String keystore, String password) Overide to create SSLContext. | public Request | onFileNotFound(long id, HttpExchange ex, Request request) | public java.io.File | onGetCachedFile(long id, HttpExchange ex, Request request) | public Object | onHandlePost(long id, HttpExchange ex, Request request, HttpResponse response, java.io.File dir, Object... extraParameters) | public boolean | onIsCacheable(long id, HttpExchange ex, Request request) | public String | onListDirectory(Request request) Default directory list. | public void | onPostServe(long id, HttpExchange ex, Request request, boolean isOK) | public boolean | onPreServe(long id, HttpExchange ex, Request request) | public InputStream | onServeBody(long id, HttpExchange ex, Request request) | public HttpResponse | onServeHeaders(long id, HttpExchange ex, Request request) | protected void | onSetSSLParameters(SSLContext c, HttpsParameters params) Called every time a HTTPS connection is made to set the SSL
parameters. | public HttpHandleable | removeHandler(String extension) Remove a handler for an extension. | public Postable | removePostHandler(String name) Remove a POST handler. | public void | setAuthenticator(Authenticator authenticator) Set the Authenticator class used for HTTP authentication. | public void | setCaching(boolean b) | protected void | setDefaultPoolSizes() | public boolean | setLogger(Object ologger) Set a logger to use. | public void | setThreadModel(ThreadModel threadModel) Should only be used before calling start. | public void | setThreadPool(int size) Sets thread model to POOL and sets the constant pool size to the specified
value. | public void | setThreadPool(int size, int max) Sets thread model to POOL and sets the pool size and max pool size to the
specified values. | public void | setVerbose(boolean b) | public boolean | start(int port, String root) Start a standard (non HTTPS) server on the supplied port using the
supplied path as the root URI path. | public boolean | start(int port, String root, Authenticator authenticator) Start a standard (non HTTPS) server on the supplied port using the
supplied path as the root URI path and the supplied Authenticator class
for HTTP authentication. | public boolean | start(int port, String root, String keystore, String password) Start an HTTPS server on the supplied port using the
supplied root as the root URI path and the supplied keystore and password
for SSL certificates.
Parameters: port - The TCP port for the server Parameters: root - The root URI path. | public boolean | start(int port, String root, Authenticator authenticator, String keystore, String password) Start an HTTPS server on the supplied port using the
supplied root as the root URI path and the supplied keystore and password
for SSL certificates.
Parameters: port - The TCP port for the server Parameters: root - The root URI path. | public boolean | stop(int timeout) Attempt to stop this server.
Parameters: timeout - Amount of time (in seconds) to wait for the server to stop. |
m_context | protected HttpContext m_context(Code) | | |
m_defaultFiles | protected ArrayList<String> m_defaultFiles(Code) | | The file names recognised as default to use if no filename is
specified in the URI. Defaults to index.html, index.htm
|
m_http | protected HttpServer m_http(Code) | | The HTTP server class. May be either HttpServer or HttpsServer
|
m_isStarted | protected boolean m_isStarted(Code) | | |
m_isVerbose | protected boolean m_isVerbose(Code) | | Verbose logging switch
|
m_mustCache | protected boolean m_mustCache(Code) | | |
m_poolMax | protected int m_poolMax(Code) | | |
m_poolSize | protected int m_poolSize(Code) | | |
m_port | protected int m_port(Code) | | |
m_requestHandler | protected HttpHandler m_requestHandler(Code) | | |
m_threadModel | protected ThreadModel m_threadModel(Code) | | |
Log | protected static void Log(LogLevel level, String message, Throwable e)(Code) | | Log errors, information or warnings.
Parameters: level - The log level chosen from the LogLevelenum viz ERROR, INFO orDEBUG Parameters: message - - The message to be logged Parameters: e - - The Java exception to be logged. Can be null. |
addHandler | public void addHandler(String extension, HttpHandleable handler)(Code) | | Add a handler for an extension.
Parameters: extension - The file extension (including the .) Parameters: handler - A class implementing the HttpHandleable interface. |
addPostHandler | public void addPostHandler(String name, Postable handler)(Code) | | Add a POST handler. If the name parameter starts with a full stop ('.')
then it is assumed to be a file extension and maps all requests with that
extension to the supplied handler. If name does not start with a . then
it maps a specific request URI onto the supplied handler.
EG httpd.addPostHandler(".st", myHandler);
httpd.addPostHandler("/invoices/new.st", myHandler);
Parameters: name - A file extension (including the .) or a full request uri Parameters: handler - A class implementing the Postable interface. |
getCaching | public boolean getCaching()(Code) | | |
getHandler | public HttpHandleable getHandler(String extension)(Code) | | Add a handler for an extension.
Parameters: extension - The file extension (including the .) The handler for extension or null if no handler found |
getNextSequence | public static long getNextSequence()(Code) | | The next id to use as a transaction id |
getPort | public int getPort()(Code) | | The TCP port for this server |
getVerbose | public boolean getVerbose()(Code) | | verbose mode |
isStarted | public boolean isStarted()(Code) | | |
onAllowDirectoryBrowse | public boolean onAllowDirectoryBrowse(String directory)(Code) | | |
onCreateRequestHandler | abstract protected HttpHandler onCreateRequestHandler()(Code) | | Overide to create the request handler
The request handler |
onIsCacheable | public boolean onIsCacheable(long id, HttpExchange ex, Request request)(Code) | | |
onListDirectory | public String onListDirectory(Request request)(Code) | | Default directory list. Overide to customise the directory listing
output.
Parameters: request - The Request instance A String ncontaining the HTML for the directory listing output. |
onPostServe | public void onPostServe(long id, HttpExchange ex, Request request, boolean isOK)(Code) | | |
onPreServe | public boolean onPreServe(long id, HttpExchange ex, Request request)(Code) | | |
onSetSSLParameters | protected void onSetSSLParameters(SSLContext c, HttpsParameters params)(Code) | | Called every time a HTTPS connection is made to set the SSL
parameters. Overide to customize these parameters.
Parameters: c - The SSLContext for this connection Parameters: params - The HTTPS paramaters for this connection |
removeHandler | public HttpHandleable removeHandler(String extension)(Code) | | Remove a handler for an extension.
Parameters: extension - The file extension (including the .) The handler that was removed |
removePostHandler | public Postable removePostHandler(String name)(Code) | | Remove a POST handler.
See Also: Httpd.addPostHandler Parameters: name - A file extension (including the .) or a full request uri The POST handler that was removed |
setAuthenticator | public void setAuthenticator(Authenticator authenticator)(Code) | | Set the Authenticator class used for HTTP authentication.
Parameters: authenticator - The authenticator to use |
setCaching | public void setCaching(boolean b)(Code) | | |
setDefaultPoolSizes | protected void setDefaultPoolSizes()(Code) | | |
setLogger | public boolean setLogger(Object ologger)(Code) | | Set a logger to use. The logger must either implement the slf4j interface
(@link http://www.slf4j.org) or be a PrintStream instance for logging.
This method uses reflection to invoke logging methods so applications
which don't require logging don't need any logging jar files in their
classpath. Note: this probably won't be a good idea in high volume
applications.
Parameters: ologger - The logger to use (must implement the slf4j interface (http://www.slf4j.org) (or be an instance of PrintStream for simple"logging" to the console. Note if setLogger is called twice, once with aPrintStream and once with an slf4j logger then it will print to the stream and log although the same effect can normally be achieved by configuring the logger. true if logger successfully set otherwise false. |
setThreadModel | public void setThreadModel(ThreadModel threadModel)(Code) | | Should only be used before calling start.
Parameters: threadModel - The threading model to use |
setThreadPool | public void setThreadPool(int size)(Code) | | Sets thread model to POOL and sets the constant pool size to the specified
value.
Should only be used before calling start.
Parameters: size - The size of the fixed size thread pool |
setThreadPool | public void setThreadPool(int size, int max)(Code) | | Sets thread model to POOL and sets the pool size and max pool size to the
specified values.
Should only be used before calling start.
Parameters: size - The size of the thread pool Parameters: max - The maximum size of the thread pool |
setVerbose | public void setVerbose(boolean b)(Code) | | Parameters: b - true to set verbose mode on otherwise false |
start | public boolean start(int port, String root, Authenticator authenticator) throws IOException, NoSuchFieldException(Code) | | Start a standard (non HTTPS) server on the supplied port using the
supplied path as the root URI path and the supplied Authenticator class
for HTTP authentication.
Parameters: port - The TCP port for the server Parameters: root - The root URI path. The first character of path must be '/'. Parameters: authenticator - The Authenticator derived class to use for authentication. See Also: com.sun.net.httpserver.Authenticator See Also: or http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/overview-summary.html true if the server started successfully otherwise false throws: java.io.IOException - throws: java.lang.NoSuchFieldException - |
start | public boolean start(int port, String root, String keystore, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, NoSuchFieldException, FileNotFoundException, IOException(Code) | | Start an HTTPS server on the supplied port using the
supplied root as the root URI path and the supplied keystore and password
for SSL certificates.
Parameters: port - The TCP port for the server Parameters: root - The root URI path. The first character of path must be '/'. Parameters: keystore - SSL certificate keystore Parameters: password - SSL certificate true if the server started successfully otherwise false throws: java.security.KeyStoreException - throws: java.security.NoSuchAlgorithmException - throws: java.security.cert.CertificateException - throws: java.security.UnrecoverableKeyException - throws: java.security.KeyManagementException - throws: java.lang.NoSuchFieldException - throws: java.io.FileNotFoundException - throws: java.io.IOException - See Also: javax.net.ssl.SSLContext |
start | public boolean start(int port, String root, Authenticator authenticator, String keystore, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, NoSuchFieldException, FileNotFoundException, IOException(Code) | | Start an HTTPS server on the supplied port using the
supplied root as the root URI path and the supplied keystore and password
for SSL certificates.
Parameters: port - The TCP port for the server Parameters: root - The root URI path. The first character of path must be '/'. Parameters: authenticator - The Authenticator derived class to use for authentication. See Also: com.sun.net.httpserver.Authenticator See Also: or http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/overview-summary.html Parameters: keystore - SSL certificate keystore Parameters: password - SSL certificate true if the server started successfully otherwise false throws: java.security.KeyStoreException - throws: java.security.NoSuchAlgorithmException - throws: java.security.cert.CertificateException - throws: java.security.UnrecoverableKeyException - throws: java.security.KeyManagementException - throws: java.lang.NoSuchFieldException - throws: java.io.FileNotFoundException - throws: java.io.IOException - See Also: javax.net.ssl.SSLContext |
stop | public boolean stop(int timeout)(Code) | | Attempt to stop this server.
Parameters: timeout - Amount of time (in seconds) to wait for the server to stop. true if stopped succesfully, otherwise false |
|
|