Winstoneサーブレトコンテーナー v0.8.1

ダウンロード  ライセンスは更新しました


これはWinstoneサーブレトコンテナーのベタリリースです. プロジェクトのホームページは 'http://winstone.sourceforge.net' です。

作者: Rick Knowles (問い合わせは下記まで)

コンテンツ

About:

始めに:

使い方のヒント:

Winstoneとは ?

大きくないサーブレトコンテナーを欲しかったから、Winstoneを作りました。

全J2EE機能が有るコンテナーを作成するつもりではありませんでした 『JNDI、 JavaMail、EJBの機能は必要ではないので、入てないんです。 そんな機能が欲しかったら、 別なコンテナーを使ったほうがいいです。たとえば ResinやJettyやTomcatはそんな事 ができます』

シンプルコンテナーが要るケースがいろいろ有ります。そんなケースにはWinstoneが便利です。

最初のゴールはこうでした:

  • 1つのウェブ適用に速い安定したコンテナー機能を供給します。
  • 配信したJARファイルのサイズは最小限の物にしています『現在 160KB』
  • 設定ファイルを減らして、using command line options to optionally override sensible compiled in defaults.
  • Eventually compile with GCJ to make a 3-4Meg windows exe for local development/deployment of servlets. This has not happened yet, because of some GCJ class loading problems.
  • Optionally support JSP compilation using Apache's Jasper. (http://jakarta.apache.org)

何で Winstone と言うの ?

The short version (because the long version is way too politically incorrect) is as follows:

Winstone is the name of a rather large Jamaican man a friend of mine met one night, while he was out clubbing in the Roppongi area of Tokyo. He (my friend) was a little liquored up at the time, and when Winstone suggested they head to "this really cool club" he knew, he didn't think anything was wrong. It wasn't until Winstone led him down a dark stairwell and dropped his trousers that my friend clued in and ran like hell.

It was too good a story to let die, so I named this project Winstone so that said friend will continue to be reminded of it. Heheheh ....

ライセンス

The Web-App DTD files (everything in the src/javax/servlet/resources and src/javax/servlet/jsp/resources folders) are covered by the licenses described at the top of each file (usually as licensed by Sun Microsystems).

As of v0.8.1, all other files are dual-licensed, under either the Lesser GNU Public License (LGPL) as described in LICENSE-LGPL.txt, or the Common Development and Distribution License (CDDL) as decribed in LICENSE-CDDL.txt. Until v0.8, the license used was the GNU Public License (GPL).

The goal of dual-licensing is to make Winstone as attractive as possible to distributors of commercial webapps, while ensuring everyone benefits from any improvements. The CDDL allows free distribution with any commercial applications, while distribution with a GPL licensed webapp is also possible under the LGPL. If you are unclear about which license applies to an application you wish to distribute or sell, please contact me.

作者への問い合わせ

You can contact me through the Winstone development list at sourceforge (winstone-devel AT lists DOT sourceforge DOT net). If you have any general comments or questions about Winstone please mail me on that list - I'll try to start a faq soon.

I'm open to help from anyone who's willing to help me meet the above goals for Winstone. Just mail me at the list (winstone-devel AT lists DOT sourceforge DOT net)

最初にする事

If you want to build from source code, you will need to download and install Apache Maven (v1.x). The following instructions assume you have already installed Maven and have the maven shell script in your path (to get Maven, see http://maven.apache.org/).

To build Winstone, unpack the tree:

  tar zxf winstone-src-0.8.1.tar.gz

Then build it:

  cd winstone
  maven clean jar

To run it:

  java -jar target/winstone-0.8.1.jar --webroot=<location of webroot> (+ other options)

- OR -

  java -jar target/winstone-0.8.1.jar --warfile=<location of warfile> (+ other options)

- OR -

  java -jar target/winstone-0.8.1.jar --webappsDir=<location of webapps directory> (+ other options)

- OR -

  java -jar target/winstone-0.8.1.jar --hostsDir=<location of hosts directory> (+ other options)

The winstone.jar file will be in the target directory after the build is complete.

コマンドラインオプション

Syntax:
  java -jar winstone-0.8.1.jar [--option=value] [--option=value] etc

Required options: either --webroot OR --warfile OR --webappsDir OR --hostsDir
   --webroot                = set document root folder.
   --warfile                = set location of warfile to extract from.
   --webappsDir             = set directory for multiple webapps to be deployed from
   --hostsDir               = set directory for name-based virtual hosts to be deployed from

Other options:
   --javaHome               = Override the JAVA_HOME variable
   --toolsJar               = The location of tools.jar (default is JAVA_HOME/lib/tools.jar) 
   --config                 = load configuration properties from here(if supplied).
   --prefix                 = add this prefix to all URLs. (eg http://host/prefix/etc).
   --commonLibFolder        = folder for additional jar files. Default is ./lib
    
   --logfile                = redirect winstone log messages to this file
   --logThrowingLineNo      = show the line no that logged the message (slow). Default is false
   --logThrowingThread      = show the thread that logged the message. Default is false
   --debug                  = set the level of debug msgs (1-9). Default is 5 (INFO level)

   --httpPort               = set the http listening port. -1 to disable, Default is 8080
   --httpListenAddress      = set the http listening address. Default is all interfaces
   --httpDoHostnameLookups  = enable host name lookups on http connections. Default is false
   --httpsPort              = set the https listening port. -1 to disable, Default is disabled
   --httpsListenAddress     = set the https listening address. Default is all interfaces
   --httpsDoHostnameLookups = enable host name lookups on https connections. Default is false
   --httpsKeyStore          = the location of the SSL KeyStore file. Default is ./winstone.ks
   --httpsKeyStorePassword  = the password for the SSL KeyStore file. Default is null
   --httpsKeyManagerType    = the SSL KeyManagerFactory type (eg SunX509, IbmX509). Default is SunX509
   --ajp13Port              = set the ajp13 listening port. -1 to disable, Default is 8009
   --ajp13ListenAddress     = set the ajp13 listening address. Default is all interfaces
   --controlPort            = set the shutdown/control port. -1 to disable, Default disabled

   --handlerCountStartup    = set the no of worker threads to spawn at startup. Default is 5
   --handlerCountMax        = set the max no of worker threads to allow. Default is 300
   --handlerCountMaxIdle    = set the max no of idle worker threads to allow. Default is 50

   --directoryListings      = enable directory lists (true/false). Default is true
   --useJasper              = enable jasper JSP handling (true/false). Default is false
   --useServletReloading    = enable servlet reloading (true/false). Default is false
   --preferredClassLoader   = override the preferred webapp class loader.
   --useInvoker             = enable the servlet invoker (true/false). Default is true
   --invokerPrefix          = set the invoker prefix. Default is /servlet/
   --simulateModUniqueId    = simulate the apache mod_unique_id function. Default is false
   --usage / --help         = show this message
    
Cluster options:
   --useCluster             = enable cluster support (true/false). Default is false
   --clusterClassName       = Set the cluster class to use. Defaults to SimpleCluster class
   --clusterNodes           = a comma separated list of node addresses (IP:ControlPort,IP:ControlPort,etc)

JNDI options:
   --useJNDI                      = enable JNDI support (true/false). Default is false
   --containerJndiClassName       = Set the container wide JNDI manager class to use. Defaults to ContainerJNDIManager
   --webappJndiClassName          = Set the web-app JNDI manager class to use. Defaults to WebAppJNDIManager
   --jndi.resource.<name>         = set the class to be used for the resource marked <name>
   --jndi.param.<name>.<att>      = set an attribute <att> for the resource marked <name>

Security options:
   --realmClassName               = Set the realm class to use for user authentication. Defaults to ArgumentsRealm class

   --argumentsRealm.passwd.<user> = Password for user <user>. (for ArgumentsRealm)
   --argumentsRealm.roles.<user>  = Roles for user <user> (comma-separated) (for ArgumentsRealm)

   --fileRealm.configFile         = File containing users/passwds/roles. Only valid for the FileRealm realm class

Access logging:
   --accessLoggerClassName        = Set the access logger class to use for user authentication. Defaults to disabled
   --simpleAccessLogger.format    = The log format to use. Supports combined/common/resin/custom (SimpleAccessLogger only)
   --simpleAccessLogger.file      = The location pattern for the log file(SimpleAccessLogger only)

設定ファイル

You don't really need a config file, but sometimes it's handy to be able to use the same settings each time without running through the command history.

Winstone looks for a config file winstone.properties in the current directory (or in the location specified with --config) at startup. It loads the properties in this file, overrides them with any supplied command line properties, and then starts itself.

This is just intended as a handy feature for people who want to cache regular startup options, rather than using batch files.

デプロイーの選択

The simplest way to use winstone is with a single webapp. To do this, just supply the warfile or webroot directory as an argument:

  • java -jar winstone.jar <webroot or warfile>, (this method auto-detects the type) or
  • java -jar winstone.jar --webroot=<webroot>, or
  • java -jar winstone.jar --warfile=<warfile>

If you need to support multiple webapps, use the --webappsDir switch, to which you pass a directory that contains multiple warfiles/webroots.

  • java -jar winstone.jar --webappsDir=<dir containing multiple webroots>

The directory becomes the prefix name for that webapp (so hello becomes /hello, etc). The directory named ROOT becomes the no-prefix webapp.

So, for example, if you had a directory /usr/local/webapps which contained sub-directories ROOT and test, if you executed java -jar winstone.jar --webappsDir=/usr/local/webapps, you would find that the test folder would act as a webroot for requests prefixed with /test, while other requests would go to the webapp in the ROOT folder

From v0.8, if you need multiple hosts (sometimes called name-based virtual hosting), there is a new option --hostsDir. This acts in a similar way to the --webappsDir switch, but it defines an extra level of sub-directories, the top being a per-host directory and the second a per-webapp directory as with --webappsDir.

The directory name becomes the host name: that is, a directory named "www.blah.com" will only serve requests with the host header www.blah.com, unless it is the default host. If a directory named "default" is found, it becomes the default host. If no default directory is found, the first directory in the list (alphabetically) becomes the default host.

  • java -jar winstone.jar --hostsDir=<dir containing multiple host directories>

Winstoneにない機能

As a result of the design goals, there are some things Winstone doesn't do

  • There are now three connectors supplied with Winstone:
    1. An internal HTTP connector - allows plain HTTP/1.1 connections only
    2. An internal HTTPS connector - allows HTTP/1.1 connections over SSL
    3. An AJP13 connector - allows connection to Apache/IIS/iPlanet, etc
    While there is an internal HTTPS/SSL connector included, I recommend using Apache 2.0 with the AJP13 connector (instructions below). It has way more configuration options than Winstone's connector does.
  • HttpSession support is cookie-based only (no URL rewriting). URL rewriting introduces a lot of unnecessary complex request body processing, and given that browser cookie support is common these days (and no-one I know uses URL rewriting), I plan not to implement this.
  • The messages are all in English only. These have been updated to use resource bundles, but no translations yet.

セキュリティ上の注意

If you enable the controlPort, be aware that there is no password protection at all on this port. Anyone who can get access to this port can stop or restart the server. I plan to add some simple authentication to this at some point, but not just yet.

The controlPort is disabled by default. If you choose not to enable it, the only way to shut Winstone down is to kill the process (either by Ctrl-C or kill command).

最近追加した機能

New features in v0.8:

  • Expanded the features of the JDBC connection pool to include keep-alive queries and block-and-retry behaviour when the pool has been exhausted.
  • Added filter match caching (performance improvement)
  • Name-based virtual hosting. Using the --hostsDir switch, you can define a directory that contains directories named by hostname, each of which acts like a --webappsDir. See above for more details.
  • Access logging. Disabled by default, but enabled with the switch --accessLoggerClassName=winstone.accesslog.SimpleAccessLogger. You can provide your own logging implementation, but the simple access logger contains Apache Combined/Common format logging and Resin format logging, so it should suffice for most cases. See below for more details.
  • Better embedding support. You can now embed warfiles and properties file inside the winstone jar itself, for an all-in-one application jar. See below for more details.
  • Tested with WebDAV applications. Winstone has now been tested/debugged with Jakarta Slide and Davenport WebDAV applications, and works correctly (previous versions had some obscure bugs that caused WebDAV to fail)

New features in v0.7:

  • Updated build process to use Apache Maven (see http://maven.apache.org. Build instructions have been updated to match.
  • Source code has been reformatted - a fair bit easier to read now
  • Multiple webapp support has been added. There's no auto-deploy features yet, but that will come soon. Use the --webappsDir=<webapps directory> to declare a folder that will have any directories auto-mounted and any warfiles auto-deployed. (I originally said this was not going to be included, but changed my mind when I realised it could be done with only 10K additional jarfile size).
  • Fixed the bugs in the exception handling and error servlet redirection, as well as in web xml parsing, and more other places that I can possibly list here. If you had some strange bug or incompatibility before, chances are it's been fixed now.
  • Passed the Sun JSR-154 Servlet Test Compatibility Kit (TCK) tests.
  • I also ran the JSR-152 JSP TCK on winstone with Apache Jasper support enabled, and while it didn't pass all tests, the tests it failed were the same ones the Tomcat failed, so I notified the Tomcat/Jasper developers of the test failures. Currently waiting on a response ... in any case I suspect these are actually test errors rather than implementation errors.
  • Better support for open source JVMs. Martin Cordova has been very helpful in testing winstone under a wider range of JVMs, as well as providing some really good feedback on needed features. His tests included JamVM and CacaoVM, as well as IBM's JDK. Jim Huang also reported that winstone works well under Kaffe.
  • User definable webapp class loader: This is likely to be of interest to the Aspect Oriented Programming crowd. It allows you to write your own class loader class (conforming to the same contructor signature as URLClassLoader), and then to use it in place of the normal web app class loader with --preferredClassLoader. This allows AspectWerkz style weaving classloaders to be used on webapps where it wouldn't have been otherwise possible (eg JDKs that don't support the profiler option, such as 1.4 and before), or anything else you can think of doing with a custom classloader.

New features in v0.6:

  • Updated to Servlet 2.4 specification compliance, although I haven't yet run Sun's Test Compatibility Kit on it - I'm still waiting for that. It works with all of the v2.4 webapps I've tried. The only caveat is that you will need Apache Xerces in the system classpath to make it work (see below).
  • Updated to JSP 2.0 specification compliance. This is the main cause for the blowout in size of the larger jar file, but it does result in much simpler set up for Jasper (see below).
  • Added a command-line tool for accessing control port options, such as shutdown and restart. Restart is new to this version, and causes a shutdown and redeploy from scratch.
  • Added a lib folder for additional jars. This defaults to "lib" under the current directory, with any jar or zip files in this folder being added to the webapp classpath.
  • Extensively tested with the Apache Struts and JSTL frameworks. This highlighted a number of bugs related to internationalisation I wouldn't have found otherwise.
  • Many minor features such as range downloads on static resources, a logfile directive for writing log messages to a file, and many MANY performance enhancements and bugfixes. See the TODO.txt file in the source distribution for a full list.
  • Update: June 28, 2004 - Added HTTPS support to version v0.6.4

New features in v0.5:

  • Implemented DIGEST and CERT authentication methods. The CERT type is largely untested (due to lack of A: access to certificates and B: knowledge of browser configuration for client certificates) - if anyone wants to help with testing this, I'd appreciate it.
  • Implemented simple clustering (ie sharing of sessions between multiple Winstone instances). See below for cluster configuration details.
  • Implemented optional JNDI support. This is just a memory-based Context intended for storing lookups on <env-entry> and <resource-ref> references, but it also includes a pooling JDBC DataSource object .... it's funny how you don't realise how important some things are until you go without them ....
  • The control port has been modified to be more useful. See below for usage instructions.
  • The distribution jar is now available in two forms:
    1. Complete version (winstone.jar): This contains the complete winstone feature-set, including AJP13 Apache connectors, Authentication/Realm support and Clustering support.
    2. Lite version (winstone-lite.jar): This is the core winstone feature-set only, ie commonly used servlet features, as fast and reliable as possible, with unnecessary options removed.

New features in v0.4:

  • Implemented the <error-page> directive
  • Added object pools for request/response objects for performance reasons
  • The handler pools are now controllable via startup properties
  • Servlet reloading is now supported (optionally - include --useServletReloading=true at startup)
  • The initial Authentication Model is in place (see below for help). There are two base classes that make it work: AuthenticationRealm and AuthenticationHandler. Currently Argument-based and File-based realms (ie user/password details supplied via command-line args or XML files) and HTTP BASIC and FORM authentication are implemented, but the others (DIGEST and CERT authentication forms) will come soon.

New features in v0.3:

  • The request handler threads now use monitors, which allows them to exist beyond a single request/response cycle. The benefit here is performance - it removes a serious bottleneck.
  • WAR files are now supported via the --warfile attribute. If you specify a warfile in this manner, it will be automatically extracted by the container to a temp directory, overwriting only files that are older than the archive date.
  • Servlet attribute, session, and context listeners (Servlet spec v2.3) are now fully supported. The HttpSessionActivationListener class will be fully supported once the session transfer is implemented.
  • Servlet Filters (Servlet spec v2.3) are now fully supported.
  • There is now an AJP13 connector, which means Winstone will now work behind Apache/IIS/etc using Tomcat's mod_jk. Try it out and see ... there's a section below on using the mod_jk connector.

XMLパーザーでXercesを使ってる (バージョン2.4)

As part of the upgrade in the servlet specification, the v2.4 incarnation of the web.xml file is validated using XML Schema Documents (XSD) as opposed to Document Type Definitions (DTD). While I still have no idea why such a change was necessary - especially given that DTD validation seems to be more than enough in this case - I did implement it. Perhaps the people on the specification committee might want to give a thought to container size next time round, as this one change multiplies the size of the distribution by five.

Anyway, to use Xerces, you'll need to download the latest Xerces-J parser from here, and copy xercesImpl.jar and xml-apis.jar into a folder somewhere (name it "endorsed"). Putting them in the winstone/lib folder will not work, because they must be in the system endorsed classpath to override the JDK internal XML parser.

Then add -Djava.endorsed.dirs=<endorsed dir name> as a JVM arg to your command line for starting winstone, eg:

  java -Djava.endorsed.dirs=/jdk/endorsed -jar winstone.jar --webroot=...

JSP (ApacheのJasperを使ってる)

Winstone supports JSPs using Apache's Jasper JSP compiler. Thanks to a rather clever design by the Jasper team, this was much less work than I expected - well done Jasper guys.

Required steps:

  1. Add --useJasper to your startup command line, since JSPs are disabled by default
  2. Both the v1.1 and v2.0 versions of Jasper are supported. In order to turn on JSP compilation in Winstone, you'll need to place the following jar files into the lib folder under the current directory (or the folder identified by the --commonLibFolder directive).

    • jasper-compiler.jar, jasper-runtime.jar, ant.jar - Not supplied with Winstone. You can get this from the standard Tomcat binary download location. Just download the latest Tomcat, and copy these three files into the lib folder for Winstone. They will be in the tomcat_home/common/lib folder.
    • commons-logging-api.jar, commons-el.jar (Jasper 2 only) - These are required if you are using Jasper 2.0. You can get them from the tomcat binary distribution or separately from the link below.

    All of these are available from the Jakarta download site

  3. You'll also need tools.jar, and this is handled a little differently. The ant javac compile task needs this to turn the generated .java files into .class files at runtime. You should already have this in the <java_home>/lib folder of your jdk.

    There are two new startup arguments for Winstone --javaHome and --toolsJar. You should only need to set --javaHome to make Jasper work properly. Your startup might look like this:

      java -jar winstone.jar --useJasper \
                             --javaHome=c:\java\jdk1.4.2 \
                             --webroot=...

    Additionally, you can specify the exact location of the toolsJar file like this:

      java -jar winstone.jar --useJasper \
                             --javaHome=c:\java\jdk1.4.2 \
                             --toolsJar=c:\tools.jar \
                             --webroot=...

Apacheに繋がってる

These instructions are for beginners: if you know your way around Apache and Tomcat, you'll know what's going on here.

Download and install Apache for your platform (and obviously Winstone too), then follow these steps:

  1. Download mod_jk2.dll/so into the apache modules directory
  2. Add the following to the apache conf file (httpd.conf):
    LoadModule jk2_module modules/mod_jk2.dll
    
    <Location "/<Winstone Prefix>/*">
      JkUriSet worker ajp13:localhost:8009 
    </Location>
    
  3. Create a new file called workers2.properties in the apache conf directory, with the following contents
    # only in the beginning. In production comment out
    [logger.apache2]
    level=DEBUG
    
    # Example socket channel, override port and host.
    [channel.socket:localhost:8009]
    port=8009
    host=127.0.0.1
    
    # define the worker
    [ajp13:localhost:8009]
    channel=channel.socket:localhost:8009
    
  4. Start up Winstone and Apache and try connecting to the your webapp on the apache port, with the winstone prefix. If it doesn't work, try looking at the apache error.log file for hints. If you get hex dumps, mail them to the winstone-devel list, together with any stack traces winstone generated.

Please note this is not an optimal configuration for production uses. This is provided purely for those who need some help to get started. Read the mod_jk documentation with Tomcat for more detailed info.

認証の設定

The process here is almost identical to that of Tomcat (I know this because I used the Tomcat examples webapp to develop against). There are two components - the web.xml component and selecting/configuring an AuthenticationRealm class.

  • The web.xml part is the same for all webapps - you include the <security-constraint> and <login-config> elements as required, eg (from the Tomcat examples web.xml):
    <security-constraint>
      <display-name>Example Security Constraint</display-name>
      <web-resource-collection>
        <web-resource-name>Protected Area</web-resource-name>
        <url-pattern>/jsp/security/protected/*</url-pattern>
        <http-method>DELETE</http-method>
        <http-method>GET</http-method>
        <http-method>POST</http-method>
        <http-method>PUT</http-method>
      </web-resource-collection>
      <auth-constraint>
        <role-name>tomcat</role-name>
        <role-name>role1</role-name>
      </auth-constraint>
    </security-constraint>
    
    <login-config>
      <auth-method>FORM</auth-method>
      <realm-name>Example Form-Based Authentication Area</realm-name>
      <form-login-config>
        <form-login-page>/jsp/security/protected/login.jsp</form-login-page>
        <form-error-page>/jsp/security/protected/error.jsp</form-error-page>
      </form-login-config>
    </login-config>
    
  • The AuthenticationRealm part is Winstone specific. Here you currently have three options:
    1. ArgumentsRealm: Here you simply add additional command line args for each user's password and role list. Passwords are added with --argumentsRealm.passwd.<username>=<password>, and roles are added with --argumentsRealm.roles.<username>=<role1>,<role2>
    2. FileRealm: This is the same as the Tomcat tomcat-users.xml file. Pass in the command line arguments --realmClass=winstone.realm.FileRealm --fileRealm.configFile=<filename>, and it should work exactly the way Tomcat does by default.
    3. Write your own: You just have to extend the winstone.AuthenticationRealm class, and override the appropriate methods (as the File and Arguments Realms do), and specify the class name in --realmClass.

This component is left intentionally fairly simple, and relatively extracted. I'm planning to break the realm and authentication stuff into an optional jar later, since not many webapps I've seen use it.

クラスターの機能

It should be pointed out in the beginning that the Cluster support currently implemented in Winstone is actually just session sharing. If a request comes to a node in the cluster that doesn't recognise the session ID supplied, that node simply asks the others "Do you know this session ?". If one does know it, it transfers the session to the requesting node, and the requesting node carries on as if it had always had the session in the first place.

If a specific node in the cluster goes offline, so do all the sessions that it was holding. There is no active "push" of sessions to other nodes, so as far as resilience to failure goes, this cluster is fairly weak. The clustering provided here is meant to allow a dumb load balancer to redirect requests randomly across a cluster of Winstone instances without requiring it to be "session sticky".

That said, the configuration is fairly simple. The only information you need is the IP address and control port of at least one other active node in the cluster. Once you have that, add the following options to the command line startup:

java -jar winstone.jar ...< other options > ... \
                       --controlPort=<myControlPort> \
                       --useCluster \
                       --clusterNodes=<IP1:controlPort1>

where IP1 is the IP address of the other node in the cluster, and myControlPort and controlPort1 are the port numbers to use for the control ports of this instance and the other node respectively. Note that it is necessary to actively set the controlPort on this instance, since it is disabled by default.

You would likewise set up the other instance with reciprocal options (ie changing the IPs and controlPort values appropriately.

NOTE: There are some additional requirements on your web application for Clustering of sessions to be successful.

  1. You need to include the <distributable/> element in your web.xml file. This tells Winstone that your webapp is programmed correctly to support clustering. If this is missing, clustering will be disabled.
  2. Any objects you add to the session must implement java.io.Serializable. This is required because Winstone serializes the objects in the session over the controlPort to other nodes, and reconstructs the serialized session at the destination. If you try to put a non-serializable object into the session, Winstone will throw an exception reminding you to make all session objects serializable.

コントロールポートの機能とプロトコール

From v0.5, the behaviour of the control port changes slightly. Due to increased usage of the control port by the clustering function, a rudimentary protocol has been added.

The protocol is very simple. The first byte sent to the server is a flag indicating what type of request is being issued. Beyond that the protocol varies for each request type, but the request type flag options are listed below:

  • 0 (ASCII 48) = shutdown
  • 1 (ASCII 49) = request search for a session
  • 2 (ASCII 50) = request list of currently connected cluster nodes
  • 3 (ASCII 51) = cluster node heartbeat
  • 4 (ASCII 52) = request reload of web application context

Obviously, unless you're planning to write your own cluster extensions, the only two you will be interested in are the shutdown and reload options. Luckily there is a wrapper class for accessing these functions, named winstone.tools.WinstoneControl. Try the following to get a usage statement:

  java -cp winstone.jar winstone.tools.WinstoneControl

JNDIの設定

I know that in the introduction I said that Winstone was only going to support the core servlet APIs, but I've since discovered that most people use just a little more than the core servlet API offers. For example, some people use just a JNDI JavaMail session to send administrator error mails, while others want to offer a simple servlet over SSL (and hence need Apache), still others use just a JNDI DataSource to keep a reference to the connection pool.

For this reason I've included a really basic optional JNDI service within Winstone. For the moment, it supports simple operations (such as bind, lookup, rebind, etc) and allows you to store references to environment variables (drawn from the env-entry elements in web.xml and/or command line arguments).

NOTE: JNDI support is disabled by default. It must be enabled using --useJNDI=true

Configuration can be done in two ways:

  • <env-entry> elements - This is the standard way to add simple objects, such as sql strings or configuration integers/strings. For example:
      <env-entry>
        <env-entry-name>test/hello</env-entry-name>
        <env-entry-type>java.lang.Integer</env-entry-type>
        <env-entry-value>45</env-entry-value>
      </env-entry>
    
  • Command line arguments - This is for more complex objects that require attributes to be created (JDBC DataSources for example). The syntax here involves adding a clause of the kind --jndi.resource.<resName>=<className> for each object to create, followed by --jndi.param.<resName>.<attName>=<attValue> for each attribute required. For example:
    java -jar winstone.jar ...< other options > ... \
                            --useJNDI=true \
                            --jndi.resource.test=java.lang.Float \
                            --jndi.param.test.value=45.56
    

Additionally, it includes a JDBC DataSource object which can be used as a wrapper around normal JDBC drivers. This is fairly simple for now, but it meets the requirements I mentioned above. Options are as follows:

  1. url (REQUIRED) - JDBC URL (jdbc:mysql://db.widgets.com/db)
  2. driverClassName (REQUIRED) - JDBC Driver name (eg com.mysql.jdbc.Driver)
  3. username - username for database authentication
  4. password - password for database authentication
  5. maxConnections - Maximum number of connections allowed in the pool. Default is 20
  6. maxIdle - Maximum number of idle connections allowed in the pool. Default is 10
  7. startConnections - The number of connections to open the pool with. Deafault is 2
  8. keepAliveSQL - The sql to execute on keep-alive (or checkBeforeGet) operations. Default is empty
  9. checkBeforeGet - If true, executes the keepAliveSQL before any connection is returned from the pool. Default is true if the keepAliveSQL is defined
  10. keepAlivePeriod - Execute the keepAliveSQL on all unused connection every n minutes. Default is disabled
  11. killInactivePeriod - Kills excess unused connections every n minutes. Default is disabled
  12. retryCount - When the pool is maxed out, block and retry n times. Default is 1 retry
  13. retryPeriod - The period (in ms) over which the retry blocks. Default is 1000ms

For example to create a DataSource object at the JNDI location java:/comp/env/jdbc/connPool, use the following command line (or config file) options:

java -jar winstone.jar ...< other options > ... \
                        --useJNDI=true \
                        --jndi.resource.jdbc/connPool=javax.sql.DataSource \
                        --jndi.param.jdbc/connPool.url=jdbc:mysql://db.widgets.com/db \
                        --jndi.param.jdbc/connPool.driverClassName=com.mysql.jdbc.Driver \
                        --jndi.param.jdbc/connPool.username=foo \
                        --jndi.param.jdbc/connPool.password=bar

HTTPSの設定

Somebody asked me to add HTTPS support, using the JDK 1.4 SSL socket classes, and so I decided to give it a try. It was a lot easier than expected - the API was really nice to use. Unfortunately the hard work seems to be in the configuration, rather than the programming.

I recommend using a shareware tool called KeyStore Explorer, available here. It's much easier than all that messy CLI stuff.

The steps are basically as follows:

  1. Create an empty keystore of type JKS
  2. Generate a key pair (Tools -> Generate Key Pair). I chose RSA 2048 bit, and used "MD5 with RSA" for the algorithm. Set a password and remember it.
  3. Generate a CSR (right click, Generate CSR).
  4. Send the CSR to a Certifying Authority (CA) for processing. I used FreeSSL.com, because it was only US$39 per year.
  5. Once you get the approved certificate back, import it into the key store you were using (Tools -> import CA reply). You should now have only a key pair and a certificate. Save the key store, using the same password you used before.
  6. Start winstone with the following command:
    java -jar winstone.jar --webroot=<webroot>
                           --httpsPort=443 
                           --httpsKeyStore=<keystore file> 
                           --httpsKeyStorePassword=<password>
  7. Set your hosts file (/etc/hosts or c:/Winnt/system32/drivers/etc/hosts) to point the name on your certificate to 127.0.0.1), then try to browse to https://hostname/

Access Logging

From v0.8, there's an option to allow access logging. It's disabled by default, but can be enabled by defining a logging implementation class, with --accessLoggerClassName. The class defined must be an implementation of the interface winstone.AccessLogger, and is defined container wide, but instantiated once per webapp.

The supplied logger is called winstone.accesslog.SimpleAccessLogger. It supports Apache style combined/common format logs, as well as Resin format (which is actually just Apache common style plus a user agent). Configuration options are:

  • --simpleAccessLogger.format: Either "combined", "common", "resin" or a pattern made up of wildcards. For example, the combined format string is:
    ###ip### - ###user### ###time### "###uriLine###" ###status### ###size### "###referer###" "###userAgent###"
    but you can re-arrange this to be any pattern of the above wildcards with the --accessLoggerFormat switch. Defaults to "combined"
  • --simpleAccessLogger.file: A pattern for defining the files to log to. The default value is logs/###host###/###webapp###_access.log, which splits the log files for different webapps and hosts into directories. The wildcards ###host### and ###webapp### can be moved around or even omitted. Omitting the wildcard will mean the access logs will be combined into shared files (since the file name will be the same)

For example, to enable Apache Combined style logging to separate files, use a command line like:

java -jar winstone.jar --hostsDir=<vhostsDir>
                       --accessLoggerClassName=winstone.accesslog.SimpleAccessLogger

Or to log just the date and URI for all hosts/webapps to a single file, use a command line like:

java -jar winstone.jar --hostsDir=<vhostsDir>
                       --accessLoggerClassName=winstone.accesslog.SimpleAccessLogger
                       --simpleAccessLogger.format=###date###\ ###uriLine###
                       --simpleAccessLogger.file=/mylogs/access_log.txt

Embedding Winstone

The design of Winstone has always allowed its easy embedding within another application. It's as simple as:

 // at startup
Map args = new HashMap();
args.put("webroot", "<my webroot dir>"); // or any other command line args, eg port
Launcher.initLogger(args);
Launcher winstone = new Launcher(args); // spawns threads, so your application doesn't block

... (your application code)

// before shutdown
winstone.shutdown(); 

From v0.8 though, there is also the ability to embed in the opposite direction: that is, to embed your warfile into the winstone JAR itself. This allows an all-in-one container plus web-application JAR file to be downloaded, and then unpacked at execution time.

To use this, simply unpack the winstone JAR, and place your WAR file inside the unpacked folder at the top level (with the same parent as the folder named "winstone"). Then rename your WAR file to "embedded.war", and repack the jar as before (make sure to preserve the META-INF and manifest).

Now if you type: "java -jar winstone.jar", your application should automatically deploy as the ROOT web application. Try http://localhost:8080/ to check it out.

If you need to add any default command-line arguments (eg ports or prefixes), you can embed a properties file in exactly the same way, except that the file must be named "embedded.properties".


SourceForge.net Logo    Jars Registered Java.net Linked Project