Java Doc for Httpd.java in  » Web-Server » HttpdBase4J » net » homeip » donaldm » httpdbase4j » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Web Server » HttpdBase4J » net.homeip.donaldm.httpdbase4j 
Source Cross Reference  Class Diagram Java Document (Java Doc) 


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

Field Summary
public static  StringEOL
    
protected  HttpContextm_context
    
protected static  Methodm_debugMethod
    
protected  ArrayList<String>m_defaultFiles
     The file names recognised as default to use if no filename is specified in the URI.
protected static  Methodm_errorMethod
    
protected  ExecutorServicem_executor
    
protected  Map<String, HttpHandleable>m_handlerMap
    
protected  HttpServerm_http
     The HTTP server class.
protected static  Methodm_infoMethod
    
protected  booleanm_isStarted
    
protected  booleanm_isVerbose
    
protected static  Objectm_logger
    
protected  booleanm_mustCache
    
protected  intm_poolMax
    
protected  intm_poolSize
    
protected  intm_port
    
protected  Map<String, Postable>m_postHandlerMap
     Maps POST handlers onto URLs or extensions.
protected  HttpHandlerm_requestHandler
    
protected  ThreadModelm_threadModel
    

Constructor Summary
public  Httpd()
    

Method Summary
protected static  voidLog(LogLevel level, String message, Throwable e)
     Log errors, information or warnings.
public  voidaddDefaultFile(String file)
    
public  voidaddHandler(String extension, HttpHandleable handler)
     Add a handler for an extension.
public  voidaddPostHandler(String name, Postable handler)
     Add a POST handler.
public  booleangetCaching()
    
public  HttpHandleablegetHandler(String extension)
     Add a handler for an extension.
abstract public  StringgetHomePath()
    
public static  longgetNextSequence()
    
public  intgetPort()
    
public  booleangetVerbose()
    
public  booleanisStarted()
    
public  booleanonAllowDirectoryBrowse(String directory)
    
protected  ExecutorServiceonCreateExecutor()
     Overide to create the thread executor.
abstract protected  HttpHandleronCreateRequestHandler()
    
protected  SSLContextonCreateSSLConfiguration(String keystore, String password)
     Overide to create SSLContext.
public  RequestonFileNotFound(long id, HttpExchange ex, Request request)
    
public  java.io.FileonGetCachedFile(long id, HttpExchange ex, Request request)
    
public  ObjectonHandlePost(long id, HttpExchange ex, Request request, HttpResponse response, java.io.File dir, Object... extraParameters)
    
public  booleanonIsCacheable(long id, HttpExchange ex, Request request)
    
public  StringonListDirectory(Request request)
     Default directory list.
public  voidonPostServe(long id, HttpExchange ex, Request request, boolean isOK)
    
public  booleanonPreServe(long id, HttpExchange ex, Request request)
    
public  InputStreamonServeBody(long id, HttpExchange ex, Request request)
    
public  HttpResponseonServeHeaders(long id, HttpExchange ex, Request request)
    
protected  voidonSetSSLParameters(SSLContext c, HttpsParameters params)
     Called every time a HTTPS connection is made to set the SSL parameters.
public  HttpHandleableremoveHandler(String extension)
     Remove a handler for an extension.
public  PostableremovePostHandler(String name)
     Remove a POST handler.
public  voidsetAuthenticator(Authenticator authenticator)
     Set the Authenticator class used for HTTP authentication.
public  voidsetCaching(boolean b)
    
protected  voidsetDefaultPoolSizes()
    
public  booleansetLogger(Object ologger)
     Set a logger to use.
public  voidsetThreadModel(ThreadModel threadModel)
     Should only be used before calling start.
public  voidsetThreadPool(int size)
     Sets thread model to POOL and sets the constant pool size to the specified value.
public  voidsetThreadPool(int size, int max)
     Sets thread model to POOL and sets the pool size and max pool size to the specified values.
public  voidsetVerbose(boolean b)
    
public  booleanstart(int port, String root)
     Start a standard (non HTTPS) server on the supplied port using the supplied path as the root URI path.
public  booleanstart(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  booleanstart(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  booleanstart(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  booleanstop(int timeout)
     Attempt to stop this server.
Parameters:
  timeout - Amount of time (in seconds) to wait for the server to stop.

Field Detail
EOL
public static String EOL(Code)



m_context
protected HttpContext m_context(Code)



m_debugMethod
protected static Method m_debugMethod(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_errorMethod
protected static Method m_errorMethod(Code)



m_executor
protected ExecutorService m_executor(Code)



m_handlerMap
protected Map<String, HttpHandleable> m_handlerMap(Code)
Maps file extensions onto handlers
See Also:   Httpd.addHandler



m_http
protected HttpServer m_http(Code)
The HTTP server class. May be either HttpServer or HttpsServer



m_infoMethod
protected static Method m_infoMethod(Code)



m_isStarted
protected boolean m_isStarted(Code)



m_isVerbose
protected boolean m_isVerbose(Code)
Verbose logging switch



m_logger
protected static Object m_logger(Code)



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_postHandlerMap
protected Map<String, Postable> m_postHandlerMap(Code)
Maps POST handlers onto URLs or extensions.
See Also:   Httpd.addPostHandler



m_requestHandler
protected HttpHandler m_requestHandler(Code)



m_threadModel
protected ThreadModel m_threadModel(Code)




Constructor Detail
Httpd
public Httpd()(Code)




Method Detail
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.



addDefaultFile
public void addDefaultFile(String file)(Code)



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



getHomePath
abstract public String getHomePath()(Code)



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)



onCreateExecutor
protected ExecutorService onCreateExecutor() throws NoSuchFieldException(Code)
Overide to create the thread executor. The ExecutorService thread executor service to use for threadcreation.
throws:
  java.lang.NoSuchFieldException -



onCreateRequestHandler
abstract protected HttpHandler onCreateRequestHandler()(Code)
Overide to create the request handler The request handler



onCreateSSLConfiguration
protected SSLContext onCreateSSLConfiguration(String keystore, String password) throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, IOException, CertificateException, UnrecoverableKeyException, KeyManagementException(Code)
Overide to create SSLContext.
Parameters:
  keystore - SSL certificate keystore
Parameters:
  password - SSL certificate The SSLContext to use for HTTPS connections.
throws:
  java.security.NoSuchAlgorithmException -
throws:
  java.security.KeyStoreException -
throws:
  java.io.FileNotFoundException -
throws:
  java.io.IOException -
throws:
  java.security.cert.CertificateException -
throws:
  java.security.UnrecoverableKeyException -
throws:
  java.security.KeyManagementException -



onFileNotFound
public Request onFileNotFound(long id, HttpExchange ex, Request request)(Code)



onGetCachedFile
public java.io.File onGetCachedFile(long id, HttpExchange ex, Request request)(Code)



onHandlePost
public Object onHandlePost(long id, HttpExchange ex, Request request, HttpResponse response, java.io.File dir, Object... extraParameters)(Code)



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)



onServeBody
public InputStream onServeBody(long id, HttpExchange ex, Request request)(Code)



onServeHeaders
public HttpResponse onServeHeaders(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) throws IOException, NoSuchFieldException(Code)
Start a standard (non HTTPS) server on the supplied port using the supplied path as the root URI path.
Parameters:
  port - The TCP port for the server
Parameters:
  root - The root URI path. The first character of path must be '/'. true if the server started successfully otherwise false
throws:
  java.io.IOException -
throws:
  java.lang.NoSuchFieldException -



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



Methods inherited from java.lang.Object
native protected Object clone() throws CloneNotSupportedException(Code)(Java Doc)
public boolean equals(Object obj)(Code)(Java Doc)
protected void finalize() throws Throwable(Code)(Java Doc)
final native public Class getClass()(Code)(Java Doc)
native public int hashCode()(Code)(Java Doc)
final native public void notify()(Code)(Java Doc)
final native public void notifyAll()(Code)(Java Doc)
public String toString()(Code)(Java Doc)
final native public void wait(long timeout) throws InterruptedException(Code)(Java Doc)
final public void wait(long timeout, int nanos) throws InterruptedException(Code)(Java Doc)
final public void wait() throws InterruptedException(Code)(Java Doc)

www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.