Merge branch 'jetty-9.4.x'

This commit is contained in:
Jesse McConnell 2016-04-29 14:32:26 -05:00
commit 6a07c7fd3a
284 changed files with 35061 additions and 0 deletions

256
jetty-documentation/pom.xml Normal file
View File

@ -0,0 +1,256 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-project</artifactId>
<version>9.3.9-SNAPSHOT</version>
</parent>
<artifactId>jetty-documentation</artifactId>
<name>Jetty :: Documentation</name>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<asciidoctor.version>1.5.3</asciidoctor.version>
<html.directory>${project.build.directory}/current</html.directory>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.0.1</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-assets</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**</include>
</includes>
</resource>
</resources>
<outputDirectory>${html.directory}</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>${asciidoctor.version}</version>
<executions>
<execution>
<id>output-html</id>
<phase>compile</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>docbook</backend>
<doctype>book</doctype>
<sourceDocumentName>index.adoc</sourceDocumentName>
<attributes>
<imagesdir></imagesdir>
<version>${project.version}</version>
<linkcss>true</linkcss>
<allow-uri-read>true</allow-uri-read>
<toc>true</toc>
<revnumber>${project.version}</revnumber>
<JDURL>http://download.eclipse.org/jetty/stable-9/apidocs</JDURL>
<JXURL>http://download.eclipse.org/jetty/stable-9/xref</JXURL>
<SRCDIR>${basedir}/..</SRCDIR>
<GITBROWSEURL>https://github.com/eclipse/jetty.project/master</GITBROWSEURL>
</attributes>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.agilejava.docbkx</groupId>
<artifactId>docbkx-maven-plugin</artifactId>
<version>2.0.14</version>
<executions>
<execution>
<id>html</id>
<phase>compile</phase>
<goals>
<goal>generate-html</goal>
</goals>
<configuration>
<htmlStylesheet>css/docbook.css</htmlStylesheet>
<htmlCustomization>${basedir}/src/main/docbkx-stylesheet/html/docbook.xsl</htmlCustomization>
<preProcess>
<!-- pull over the images from the source material -->
<copy todir="target/docbkx/html/index/images" flatten="true">
<fileset dir="src/main/asciidoc">
<include name="**/*.png"/>
<include name="**/*.jpg"/>
<include name="**/*.svg"/>
<include name="**/*.dot"/>
</fileset>
</copy>
<copy todir="target/docbkx/html/index/images">
<fileset dir="src/main/docbkx-resources/images" />
</copy>
<copy todir="target/docbkx/html/index/css">
<fileset dir="src/main/docbkx-resources/css" />
</copy>
<copy todir="target/docbkx/html/index/fonts">
<fileset dir="src/main/docbkx-resources/fonts" />
</copy>
<copy todir="target/docbkx/html/index/js">
<fileset dir="src/main/docbkx-resources/js" />
</copy>
</preProcess>
</configuration>
</execution>
</executions>
<configuration>
<!-- shared configuration -->
<sourceDirectory>${project.build.directory}/generated-docs</sourceDirectory>
<includes>index.xml</includes>
<generatedSourceDirectory>${project.build.directory}/docbkx/generated</generatedSourceDirectory>
<chunkedOutput>true</chunkedOutput>
<highlightSource>true</highlightSource>
</configuration>
<dependencies>
<dependency>
<groupId>net.sf.docbook</groupId>
<artifactId>docbook-xml</artifactId>
<version>5.0-all</version>
<classifier>resources</classifier>
<type>zip</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>net.sf.xslthl</groupId>
<artifactId>xslthl</artifactId>
<version>2.0.1</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-xslt-tools</artifactId>
<version>1.3</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<descriptors>
<descriptor>src/main/assembly/html.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<!--
Couple of different approaches to generating pdf's
-->
<profile>
<id>generate-pdf</id>
<build>
<plugins>
<plugin>
<groupId>com.agilejava.docbkx</groupId>
<artifactId>docbkx-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-pdf</id>
<phase>compile</phase>
<goals>
<goal>generate-pdf</goal>
</goals>
<configuration>
<includes>index.xml</includes>
<fop1Extensions>1</fop1Extensions>
<paperType>A4</paperType>
<foCustomization>src/main/docbkx-stylesheet/fo/docbook.xsl</foCustomization>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>net.sf.offo</groupId>
<artifactId>fop-hyph</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>${asciidoctor.version}</version>
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.11</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>output-pdf</id>
<phase>generate-sources</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>pdf</backend>
<sourceHighlighter>rouge</sourceHighlighter>
<sourceDocumentName>index.adoc</sourceDocumentName>
<attributes>
<imagesdir></imagesdir>
<version>${project.version}</version>
<linkcss>true</linkcss>
<allow-uri-read>true</allow-uri-read>
<toc>true</toc>
<revnumber>${project.version}</revnumber>
<JDURL>http://download.eclipse.org/jetty/stable-9/apidocs</JDURL>
<JXURL>http://download.eclipse.org/jetty/stable-9/xref</JXURL>
<SRCDIR>${basedir}/../jetty.project/</SRCDIR>
<GITBROWSEURL>https://github.com/eclipse/jetty.project/master</GITBROWSEURL>
<icons>font</icons>
<pagenums/>
<toc/>
<idprefix/>
<idseparator>-</idseparator>
</attributes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,277 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[alpn]]
=== Introducing ALPN
The development of new web protocols such as HTTP/2 raised the need of protocol negotiation within a Transport Layer Security (TLS) handshake.
A protocol negotiation called https://tools.ietf.org/html/rfc7301[ALPN] (Application Layer Protocol Negotiation) RFC7301 has been defined to accomplish this.
ALPN has now replaced the older (and now fully deprecated) NPN in the general Web of 2016.
For those browsers that support HTTP/2, they all now support the ALPN negotiation layers for TLS.
Starting with Jetty 9.3.0, only ALPN is supported by Jetty.
The Jetty project provides an implementation of the TLS extension for ALPN for OpenJDK 7 and OpenJDK 8.
ALPN allows the application layer to negotiate which protocol to use over the secure connection.
Any protocol can be negotiated by ALPN within a TLS connection.
The protocols that are most commonly negotiated are HTTP/2 (for browsers that support it) and, historically, SPDY.
The ALPN implementation is therefore not HTTP/2 or SPDY specific in any way.
Jetty's ALPN implementation, although hosted under the umbrella of the Jetty project, is independent of Jetty (the Servlet Container); you can use the ALPN implementation in any other Java network server.
The Jetty distribution will automatically enable ALPN when it is needed to by a HTTP/2 connector, so for the most part ALPN is transparent to the average deployer.
This section provides the detail required for unusual deployments or developing to the ALPN API.
[[alpn-starting]]
==== Starting the JVM
To enable ALPN support, start the JVM as follows:
[source,plain]
----
java -Xbootclasspath/p:<path_to_alpn_boot_jar> ...
----
where `path_to_alpn_boot_jar` is the path on the file system for the ALPN Boot Jar file, for example, one at the Maven coordinates `org.mortbay.jetty.alpn:alpn-boot`.
Be certain link:#alpn-versions[to get the ALPN Boot Jar version which matches the version of your JRE].
[[alpn-osgi]]
===== Starting in OSGi
To use ALPN in an OSGi environment, in addition to putting the ALPN jar on the boot classpath for the container, you will also need to deploy the jetty-osgi-alpn jar.
This jar contains a Fragment-Host directive that ensures the ALPN classes will be available from the system bundle.
You can download the http://central.maven.org/maven2/org/eclipse/jetty/osgi/jetty-osgi-alpn/[jetty-osgi-alpn jar] from Maven Central.
[[alpn-understanding]]
==== Understanding the ALPN API
Applications need to interact with ALPN TLS extension protocol negotiations.
For example, server applications need to know whether the client supports ALPN, and client applications needs to know whether the server supports ALPN.
To implement this interaction, Jetty's ALPN implementation provides an API to applications, hosted at Maven coordinates
`org.eclipse.jetty.alpn:alpn-api`.
You need to declare this dependency as provided, because the `alpn-boot` Jar already includes it (see the previous section), and it is therefore available from the boot classpath.
The API consists of a single class, `org.eclipse.jetty.alpn.ALPN`, and applications need to register instances of `SSLSocket` or `SSLEngine` with a `ClientProvider` or `ServerProvider` (depending on whether the application is a client application or server application).
Refer to `ALPN` Javadocs and to the examples below for further details about client and server provider methods.
[[alpn-client-example]]
==== Client Example
[source,java]
----
SSLContext sslContext = ...;
final SSLSocket sslSocket = (SSLSocket)context.getSocketFactory().createSocket("localhost", server.getLocalPort());
ALPN.put(sslSocket, new ALPN.ClientProvider()
{
@Override
public boolean supports()
{
return true;
}
@Override
public List<String> protocols()
{
return Arrays.asList("h2", "http/1.1");
}
@Override
public void unsupported()
{
ALPN.remove(sslSocket);
}
@Override
public void selected(String protocol)
{
ALPN.remove(sslSocket);
System.out.println("Protocol Selected is: " + protocol);
}
});
----
The ALPN implementation calls `ALPN.ClientProvider` methods `supports()`, `protocols()`, `unsupported()` and `selected(String)`, so that the client application can:
* decide whether to support ALPN.
* provide the protocols supported.
* know whether the server supports ALPN.
* know the protocol chosen by the server.
[[alpn-server-example]]
==== Server Example
The example for SSLEngine is identical, and you just need to replace the SSLSocket instance with an SSLEngine instance.
[source,java]
----
final SSLSocket sslSocket = ...;
ALPN.put(sslSocket, new ALPN.ServerProvider()
{
@Override
public void unsupported()
{
ALPN.remove(sslSocket);
}
@Override
public String select(List<String> protocols);
{
ALPN.remove(sslSocket);
return protocols.get(0);
}
});
----
The ALPN implementation calls `ALPN.ServerProvider` methods `unsupported()`, and `select(List<String>),` so that the server application can:
* know whether the client supports ALPN.
* select one of the protocols the client supports.
[[alpn-implementation]]
==== Implementation Details
It is important that implementations of `ALPN.ServerProvider` and `ALPN.ClientProvider` remove the `sslSocket` or `sslEngine` when the negotiation is complete, like shown in the examples above.
Failing to do so will cause a memory leak.
[[alpn-tests]]
==== Unit Tests
You can write and run unit tests that use the ALPN implementation.
The solution that we use with Maven is to specify an additional command line argument to the Surefire plugin:
[source,xml]
----
<project>
<properties>
<alpn-boot-version>8.1.4.v20150727</alpn-boot-version>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
-Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/alpn/alpn-boot/${alpn-boot-version}/alpn-boot-${alpn-boot-version}.jar
</argLine>
</configuration>
</plugin>
...
</plugins>
</build>
...
</project>
----
[[alpn-debugging]]
==== Debugging
You can enable debug logging for the ALPN implementation in this way:
....
ALPN.debug = true;
....
Since the ALPN class is in the boot classpath, we chose not to use logging libraries because we do not want to override application logging library choices; therefore the logging is performed directly on `System.err.`
[[alpn-license-details]]
==== License Details
The ALPN implementation relies on modification of a few OpenJDK classes and on a few new classes that need to live in the `sun.security.ssl` package.
These classes are released under the same GPLv2+exception license of OpenJDK.
The ALPN class and its nested classes are released under same license as the classes of the Jetty project.
[[alpn-versions]]
==== Versions
The ALPN implementation, relying on modifications of OpenJDK classes, updates every time there are updates to the modified OpenJDK classes.
.ALPN vs. OpenJDK versions
[cols=",",options="header",]
|=============================
|OpenJDK version |ALPN version
|1.7.0u40 |7.1.0.v20141016
|1.7.0u45 |7.1.0.v20141016
|1.7.0u51 |7.1.0.v20141016
|1.7.0u55 |7.1.0.v20141016
|1.7.0u60 |7.1.0.v20141016
|1.7.0u65 |7.1.0.v20141016
|1.7.0u67 |7.1.0.v20141016
|1.7.0u71 |7.1.2.v20141202
|1.7.0u72 |7.1.2.v20141202
|1.7.0u75 |7.1.3.v20150130
|1.7.0u76 |7.1.3.v20150130
|1.7.0u79 |7.1.3.v20150130
|1.7.0u80 |7.1.3.v20150130
|1.8.0 |8.1.0.v20141016
|1.8.0u05 |8.1.0.v20141016
|1.8.0u11 |8.1.0.v20141016
|1.8.0u20 |8.1.0.v20141016
|1.8.0u25 |8.1.2.v20141202
|1.8.0u31 |8.1.3.v20150130
|1.8.0u40 |8.1.3.v20150130
|1.8.0u45 |8.1.3.v20150130
|1.8.0u51 |8.1.4.v20150727
|1.8.0u60 |8.1.5.v20150921
|1.8.0u65 |8.1.6.v20151105
|1.8.0u66 |8.1.6.v20151105
|1.8.0u71 |8.1.7.v20160121
|1.8.0u72 |8.1.7.v20160121
|1.8.0u73 |8.1.7.v20160121
|1.8.0u74 |8.1.7.v20160121
|1.8.0u77 |8.1.7.v20160121
|=============================
[[alpn-build]]
==== How to build ALPN
This section is for Jetty developers that need to update the ALPN implementation with the OpenJDK versions.
Clone the OpenJDK repository with the following command:
....
$ hg clone http://hg.openjdk.java.net/jdk7u/jdk7u jdk7u # OpenJDK 7
$ hg clone http://hg.openjdk.java.net/jdk8u/jdk8u jdk8u # OpenJDK 8
$ cd !$
$ ./get_source.sh
....
To update the source to a specific tag, use the following command:
....
$ ./make/scripts/hgforest.sh update <tag-name>
....
The list of OpenJDK tags can be obtained from these pages:
http://hg.openjdk.java.net/jdk7u/jdk7u/tags[OpenJDK 7] /
http://hg.openjdk.java.net/jdk8u/jdk8u/tags[OpenJDK 8].
Then you need to compare and incorporate the OpenJDK source changes into the modified OpenJDK classes at the https://github.com/jetty-project/jetty-alpn[ALPN GitHub Repository], branch `openjdk7` for OpenJDK 7 and branch `master` for OpenJDK 8.

View File

@ -0,0 +1,20 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[alpn-chapter]]
== ALPN
include::alpn.adoc[]

View File

@ -0,0 +1,25 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[annotations]]
== Annotations
Jetty supports the servlet specification annotations.
It is not enable by default, so the following sections show you how to enable it, and how to use them.
include::quick-annotations-setup.adoc[]
include::using-annotations.adoc[]
include::using-annotations-embedded.adoc[]

View File

@ -0,0 +1,43 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[annotations-quick-setup]]
=== Quick Setup
==== Jetty Distribution
If you are using the jetty distribution, then annotations are enabled by default.
The *annotations* link:#startup-modules[module] and its transitive dependencies are responsible for making annotation processing available.
Note that annotations that relate to link:#jndi[JNDI], such as @Resource and @Resources are enabled via the *jndi* module, which is a transitive dependency on the annotations module, and thus is also enabled by default for the distribution.
==== Jetty Maven Plugin
Annotations and JNDI are pre-enabled for the maven plugin.
==== Embedding
To use annotations in an embedded scenario, you will need to include the jetty-annotations jar and all its dependencies onto your classpath.
You will also need to include the org.eclipse.jetty.annotations.AnnotationConfiguration into the list of link:#webapp-configurations[Configuration classes] applied to the org.eclipse.jetty.webapp.WebAppContext representing your webapp.
Here is an example application that sets up the standard test-spec.war webapp from the distribution in embedded fashion.
It can be found in the jetty git repository in the examples/embedded project.
Note that the test-spec.war uses not only annotations, but also link:#jndi[JNDI], so this example also enables their processing (via the link:#jndi-configuration-classes[org.eclipse.jetty.plus.webapp.EnvConfiguration], link:#jndi-configuration-classes[org.eclipse.jetty.plus.webapp.PlusConfiguration] and their related jars).
[source,java]
----
include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ServerWithAnnotations.java[]
----

View File

@ -0,0 +1,190 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[using-annotations-embedded]]
=== Using Annotations with Jetty Embedded
==== Setting up the Classpath
You will need to place the following jetty jars onto the classpath of your application. You can obtain them from the http://download.eclipse.org/jetty/stable-9/dist/[jetty distribution], or the http://central.maven.org/maven2/org/eclipse/jetty/jetty-annotations[maven repository]:
....
jetty-plus.jar
jetty-annotations.jar
....
You will also need the http://asm.ow2.org/[asm] jar, which you can obtain from the http://download.eclipse.org/jetty/orbit/[Jetty dependencies site].
==== Example
Here's an example application that sets up a Jetty server, does some setup to ensure that annotations are scanned and deploys a webapp that uses annotations.
This example also uses the @Resource annotation which involves JNDI, so we would also link:#jndi-embedded[add the necessary jndi jars to the classpath]., and we also add in the configuration classes that are responsible for JNDI (see line 19).
Here is the embedding code:
[source,java]
----
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* ServerWithAnnotations
*
*
*/
public class ServerWithAnnotations
{
public static final void main(String args[]) throws Exception
{
//Create the server
Server server = new Server(8080);
//Enable parsing of jndi-related parts of web.xml and jetty-env.xml
org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration", "org.eclipse.jetty.annotations.AnnotationConfiguration");
//Create a WebApp
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("../../tests/test-webapps/test-servlet-spec/test-spec-webapp/target/test-spec-webapp-9.0.4-SNAPSHOT.war");
server.setHandler(webapp);
//Register new transaction manager in JNDI
//At runtime, the webapp accesses this as java:comp/UserTransaction
org.eclipse.jetty.plus.jndi.Transaction transactionMgr = new org.eclipse.jetty.plus.jndi.Transaction(new com.acme.MockUserTransaction());
//Define an env entry with webapp scope.
org.eclipse.jetty.plus.jndi.EnvEntry maxAmount = new org.eclipse.jetty.plus.jndi.EnvEntry (webapp, "maxAmount", new Double(100), true);
// Register a mock DataSource scoped to the webapp
org.eclipse.jetty.plus.jndi.Resource mydatasource = new org.eclipse.jetty.plus.jndi.Resource(webapp, "jdbc/mydatasource", new com.acme.MockDataSource());
// Configure a LoginService
HashLoginService loginService = new HashLoginService();
loginService.setName("Test Realm");
loginService.setConfig("src/test/resources/realm.properties");
server.addBean(loginService);
server.start();
server.join();
}
}
----
On line 19 we add in the configuration classes responsible for setting up JNDI and java:comp/env.
On line 20 we add in the configuration class that ensures annotations are inspected.
On lines 30, 33 and 37 we set up some JNDI resources that we will be able to reference with @Resource annotations.
With the setup above, we can create a servlet that uses annotations and Jetty will honour the annotations when the webapp is deployed:
[source,java]
----
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RunAs;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.transaction.UserTransaction;
/**
* AnnotationTest
*
* Use servlet 3.0 annotations from within Jetty.
*
* Also uses servlet 2.5 resource injection and lifecycle callbacks
*/
@RunAs("special")
@WebServlet(urlPatterns = {"/","/test/*"}, name="AnnotationTest", initParams={@WebInitParam(name="fromAnnotation", value="xyz")})
@DeclareRoles({"user","client"})
public class AnnotationTest extends HttpServlet
{
private DataSource myDS;
@Resource(mappedName="UserTransaction")
private UserTransaction myUserTransaction;
@Resource(mappedName="maxAmount")
private Double maxAmount;
@Resource(mappedName="jdbc/mydatasource")
public void setMyDatasource(DataSource ds)
{
myDS=ds;
}
@PostConstruct
private void myPostConstructMethod ()
{
System.err.println("PostConstruct called");
}
@PreDestroy
private void myPreDestroyMethod()
{
System.err.println("PreDestroy called");
}
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
out.println("<html>");
out.println("<body>");
out.println("<h1>Results</h1>");
out.println(myDS.toString());
out.println("<br/>");
out.println(maxAmount.toString());
out.println("</body>");
out.println("</html>");
out.flush();
}
catch (Exception e)
{
throw new ServletException(e);
}
}
}
----

View File

@ -0,0 +1,154 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[using-annotations]]
=== Working with Annotations
==== Which Annotations Are Supported
Jetty supports interpretation and application of the following annotations:
* @Resource
* @Resources
* @PostConstruct
* @PreDestroy
* @DeclaredRoles
* @RunAs
* @MultipartConfig
* @WebServlet
* @WebFilter
* @WebListener
* @WebInitParam
* @ServletSecurity, @HttpConstraint, @HttpMethodConstraint
* @HandlesTypes (on ServletContainerInitializers)
[[discoverable_introspectable_annotations]]
==== Discovered vs Introspected Annotations
Some types of annotation can be placed on any classes, not necessarily just those with which the container interacts directly.
We call these type of annotations "discovered" to indicate that the container must take proactive action to go out and find them.
The other type of annotation we call "introspected", meaning that they occur on classes with which the container interacts during their lifecycle (eg javax.servlet.Servlet, javax.servlet.Filter etc), and hence can be found by simple inspection of the class at that point.
Some examples of discovered annotations are:
* @WebServlet
* @WebFilter
* @WebListener
Some examples of introspected annotations are:
* @PostConstruct
* @PreDestroy
* @Resource
[[jars-scanned-for-annotations]]
==== Which Jars Are Scanned For Discovered Annotations
The web.xml file can contain the attribute `metadata-complete`.
If this is set to `true`, then _no_ scanning of discoverable annotations takes place.
However, scanning of classes may _still_ occur because of http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContainerInitializer.html[javax.servlet.ServletContainerInitializer]s.
Classes implementing this interface are found by Jetty using the http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html[javax.util.ServiceLoader] mechanism, and if one is present _and_ it includes the @HandlesTypes annotation, then Jetty must scan the class hierarchy of the web application.
This may be very time-consuming if you have many jars in the container's path or in the webapp's WEB-INF/lib.
If scanning is to take place - because either `metadata-complete` is `false` or missing, or because there are one or more http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContainerInitializer.html[javax.servlet.ServletContainerIntializer]s with @HandlesTypes - then Jetty must consider both the container's classpath and the webapp's classpath.
By default, Jetty will _not_ scan any classes that are on the container's classpath.
If you need to cause jars and classes that are on the container's classpath to be scanned, then you can use the link:#container-include-jar-pattern[org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern] link:#context_attributes[context attribute] to specify a pattern for jars and directories from the container's classpath to scan.
By default, Jetty will scan __all__classes from `WEB-INF/classes`, and all jars from `WEB-INF/lib` according to the order, if any, established by absolute or relative ordering clauses in web.xml.
If your webapp contains many jars, you can significantly speed up deployment by omitting them from scanning.
To do this, use the link:#web-inf-include-jar-pattern[org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern] link:#context_attributes[context attribute] to define the patterns of jars that you specifically want to be scanned.
Note that if you have configured an link:#using-extra-classpath-method[extraClasspath] for the webapp, then it participates in the scanning process too.
Any classes dirs are treated the same for scanning purposes as if they were in WEB-INF/classes and jars are treated as if they were in WEB-INF/lib.
See also the next section on link:#servlet-container-initializers[ServletContainerInitializers] if you need to link:#servlet-container-initializers[control the order in which they are applied].
==== Multi-threaded Annotation Scanning
Since jetty-9.1,link:#jars-scanned-for-annotations[if annotation scanning is to be performed], by default Jetty will do it in a multi-threaded manner in order to complete it in the minimum amount of time.
If for some reason you don't want to do it multi-threaded, you can configure Jetty to revert to single-threaded scanning.
You have several ways to configure this:
1. set the link:#context_attributes[context attribute] `org.eclipse.jetty.annotations.multiThreaded` to `false`
2. set the link:#server_attributes[Server attribute] `org.eclipse.jetty.annotations.multiThreaded` to `false`
3. set the System property `org.eclipse.jetty.annotations.multiThreaded` to `false`
Method 1 will only affect the current webapp.
Method 2 will affect all webapps deployed to the same Server instance.
Method 3 will affect all webapps deployed in the same jvm.
By default, Jetty will wait a maximum of 60 seconds for all of the scanning threads to complete.
You can set this to a higher or lower number of seconds by doing one of the following:
1. set the link:#context_attributes[context attribute] `org.eclipse.jetty.annotations.maxWait`
2. set the link:#server_attributes[Server attribute] `org.eclipse.jetty.annotations.maxWait`
3. set the System property `org.eclipse.jetty.annotations.maxWait`
Method 1 will only affect the current webapp.
Method 2 will affect all webapps deployed to the same Server instance.
Method 3 will affect all webapps deployed in the same jvm.
[[servlet-container-initializers]]
==== ServletContainerInitializers
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContainerInitializer.html[javax.servlet.ServletContainerInitializers] can exist in: the container's classpath, the webapp's WEB-INF/classes directory, the webapp's WEB-INF/lib jars, or any external link:#using-extra-classpath-method[extraClasspath] that you have configured on the webapp.
The http://jcp.org/aboutJava/communityprocess/final/jsr340/[Servlet Specification] does not define any order in which these ServletContainerInitializers must be called when the webapp starts.
Since jetty-9.1, by default Jetty will call them in the following order:
1. ServletContainerInitializers from the container's classpath
2. ServletContainerInitializers from WEB-INF/classes
3. ServletContainerInitializers from WEB-INF/lib jars __in the order established in web.xml__, or in the order that the SCI is returned by the http://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html[javax.util.ServiceLoader] if there is _no_ ordering
As is the case with annotation scanning, the link:#using-extra-classpath-method[extraClasspath] is fully considered for ServletContainerInitializer callbacks. ServletContainerInitializers derived from a classes dir on the extraClasspath and jars from an extraClasspath for the webapp are called in step 2 and 3 respectively.
===== Controlling the order of ServletContainerInitializer invocation
If you need ServletContainerInitializers called in a specific order that is different from that outlined above, then you can use the link:#context_attributes[context attribute] `org.eclipse.jetty.containerInitializerOrder`. Set it to a list of comma separated class names of ServletContainerInitializers in the order that you want them applied.
You may optionally use the wildcard character "*" *once* in the list.
It will match all ServletContainerInitializers not explicitly named in the list. Here's an example, setting the context attribute in code (although you can also do the link:#intro-jetty-configuration-webapps[same in xml]):
[source,java]
----
WebAppContext context = new WebAppContext();
context.setAttribute("org.eclipse.jetty.containerInitializerOrder",
"org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer, com.acme.Foo.MySCI, *");
----
In this example, we ensure that the WebSocketServerContainerInitializer is the very first ServletContainerInitializer that is called, followed by MySCI and then any other ServletContainerInitializers that were discovered but not yet called.
[[excluding-scis]]
===== Excluding ServletContainerInitializers
By default, as according to the Servlet Specification, all ServletContainerInitializers that are discovered are invoked (see above for how to control the invocation order).
Sometimes, you may need to prevent some being called at all.
In this case, you can define the `org.eclipse.jetty.containerInitializerExclusionPattern` link:#context_attributes[context attribute].
This is a regular expression that defines http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html[patterns] of classnames that you want to exclude.
Here's an example, setting the context attribute in code, although you may do exactly the link:#intro-jetty-configuration-webapps[same in xml]:
[source,java]
----
WebAppContext context = new WebAppContext();
context.setAttribute("org.eclipse.jetty.containerInitializerExclusionPattern",
"com.acme.*|com.corp.SlowContainerInitializer");
----
In this example we exclude *all* ServletContainerInitializers in the com.acme package, and the SlowContainerInitializer.
It is possible to use exclusion and ordering together to control ServletContainerInitializer invocation - the exclusions will be applied before the ordering.

View File

@ -0,0 +1,38 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[balancer-servlet]]
=== Balancer Servlet
[[balancer-servlet-metadata]]
==== Info
* Classname: `org.eclipse.jetty.proxy.BalancerServlet`
* Maven Artifact: org.eclipse.jetty:jetty-proxy
* Javadoc: {JDURL}/org/eclipse/jetty/proxy/BalancerServlet.html
* Xref: {JXURL}/org/eclipse/jetty/proxy/BalancerServlet.html
[[balancer-servlet-usage]]
==== Usage
The Balancer servlet allows for simple, sticky round robin load balancing leveraging the ProxyServlet that is distributed with Jetty.
In addition to the parameters for ProxyServlet, the following are available for the balancer servlet:
stickySessions::
true if sessions should be sticky for subsequent requests
balancerMember.<name>.proxyTo::
One of more of these are required and will be the locations that are used to proxy traffic to.

View File

@ -0,0 +1,44 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[cgi-servlet]]
=== CGI Servlet
[[cgi-servlet-metadata]]
==== Info
* Classname: `org.eclipse.jetty.servlets.CGI`
* Maven Artifact: org.eclipse.jetty:jetty-servlets
* Javadoc: {JDURL}/org/eclipse/jetty/servlets/CGI.html
* Xref: {JXURL}/org/eclipse/jetty/servlets/CGI.html
[[cgi-servlet-usage]]
==== Usage
The CGI servlet class extends the abstract HttpServlet class.
When the init parameter is called, the cgi bin directory is set with the cgibinResourceBase.
Otherwise, it defaults to the resource base of the context.
See CGI javadoc.
The cgi bin uses three parameters:
commandPrefix::
The init parameter obtained when there is a prefix set to all commands directed to the method exec.
Path::
An init parameter passed to the exec environment as a PATH.
This must be run unpacked somewhere in the filesystem.
ENV_::
An init parameter that points to an environment variable with the name stripped of the leading ENV_ and using the init parameter value.

View File

@ -0,0 +1,44 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[advanced-extras]]
== Provided Servlets, Filters, and Handlers
Jetty ships with a bundle of servlets that interact with the key classes.
Most are in the org.eclipse.jetty.servlets package.
These servlets and filters are among the principle elements of Jetty as a component-based infrastructure that holds and runs J2EE applications.
As described, they play a major role in running and maintaining the Jetty server.
Also included are a number of Jetty specific handlers that allow access to internals of jetty that would not normally be exposed and are very useful testing environments and many production scenarios.
include::default-servlet.adoc[]
include::proxy-servlet.adoc[]
include::balancer-servlet.adoc[]
include::cgi-servlet.adoc[]
include::qos-filter.adoc[]
include::dos-filter.adoc[]
include::gzip-filter.adoc[]
include::cross-origin-filter.adoc[]
include::resource-handler.adoc[]
include::debug-handler.adoc[]
include::statistics-handler.adoc[]
include::ipaccess-handler.adoc[]
include::moved-context-handler.adoc[]
include::shutdown-handler.adoc[]
include::default-handler.adoc[]
include::error-handler.adoc[]
include::rewrite-handler.adoc[]

View File

@ -0,0 +1,97 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[cross-origin-filter]]
=== Cross Origin Filter
[[cross-origin-filter-metadata]]
==== Info
* Classname: `org.eclipse.jetty.servlets.CrossOriginFilter`
* Maven Artifact: org.eclipse.jetty:jetty-servlets
* Javadoc: {JDURL}/org/eclipse/jetty/servlets/CrossOriginFilter.html
* Xref: {JXURL}/org/eclipse/jetty/servlets/CrossOriginFilter.html
[[cross-origin-filter-usage]]
==== Usage
HTTP requests made from a script are subject to well known restrictions, the most prominent being the same domain policy.
Firefox 3.5 introduced support for W3C's Access Control for Cross-Site Requests specification, which requires a compliant client (for example, Firefox 3.5) and a compliant server (via this servlet filter).
This filter implements the required bits to support the server-side contract of the specification, and will allow a compliant client to perform cross-domain requests via the standard XMLHttpRequest object.
If the client does not issue a compliant cross-domain request, this filter does nothing, and its overhead is the check of the presence of the cross-domain HTTP header.
This is extremely useful in CometD web applications where it is now possible to perform cross-domain long polling without using script injection (also known as the JSONP transport), and therefore removing all the downsides that the JSONP transport has (it's chattier, does not react quickly to failures, has a message size limit, uses GET instead of POST, etc.).
[[cross-origin-setup]]
==== Setup
You will need to put the jetty-servlets.jar file onto your classpath.
If you are creating a webapp, ensure that this jar is included in your webapp's WEB-INF/lib.
Or, if you are running jetty embedded you will need to ensure that jetty-servlets.jar is on the execution classpath.
You can download the jetty-servlets.jar from the Maven Central Repository at http://central.maven.org/maven2/org/eclipse/jetty/jetty-servlets/.
[[cross-origin-config]]
==== Configuration
This is a regular servlet filter that must be configured in web.xml.
It supports the following configuration parameters:
allowedOrigins::
a comma separated list of origins that are allowed to access the resources.
Default value is: * (all origins)
allowedMethods::
a comma separated list of HTTP methods that are allowed to be used when accessing the resources.
Default value is: GET,POST,HEAD
allowedHeaders::
a comma separated list of HTTP headers that are allowed to be specified when accessing the resources.
Default value is: X-Requested-With,Content-Type,Accept,Origin
allowCredentials::
a boolean indicating if the resource allows requests with credentials.
Default value is: true
preflightMaxAge::
the number of seconds that preflight requests can be cached by the client.
Default value is 1800 seconds (30 minutes)
chainPreflight::
if true preflight requests are chained to their target resource for normal handling (as an OPTION request).
Otherwise the filter will response to the preflight.
Default is true.
exposedHeaders::
a comma separated list of HTTP headers that are allowed to be exposed on the client.
Default value is the empty list.
A typical configuration could be:
[source,xml]
----
<web-app>
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/cometd/*</url-pattern>
</filter-mapping>
</web-app>
----

View File

@ -0,0 +1,70 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[debug-handler]]
=== Debug Handler
[[debug-handler-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.DebugHandler`
* Maven Artifact: org.eclipse.jetty:jetty-server
* Javadoc: {JDURL}/org/eclipse/jetty/server/handler/DebugHandler.html
* Xref: {JXURL}/org/eclipse/jetty/server/handler/DebugHandler.html
[[debug-handler-usage]]
==== Usage
A simple handler that is useful to debug incoming traffic.
It will log entry and exit points of http requests as well as the response code.
==== Usage in standard distribution
Simply include jetty-debug.xml in your *.ini configs.
For example in start.ini.
==== Embedded usage
[source,java]
----
Server server = new Server(8080);
RolloverFileOutputStream outputStream = new RolloverFileOutputStream("MeinLogPfad/yyyy_mm_dd.request.log", true,10);
DebugHandler debugHandler = new DebugHandler();
debugHandler.setOutputStream(outputStream);
debugHandler.setHandler(server.getHandler());
server.setHandler(debugHandler);
server.start();
----
==== Some example output
[source,bash]
----
15:14:05.838:qtp551889550-13-selector-0 OPENED HttpConnection@e910ee4{IDLE},g=HttpGenerator{s=START},p=HttpParser{s=START,0 of 0}
15:14:05.846:qtp551889550-57:http://0:0:0:0:0:0:0:1:8080/ REQUEST 0:0:0:0:0:0:0:1 GET __utma=111872281.10102721.1321534299.1369833564.1370447492.35; __utmz=111872281.1321534299.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _opt_vi_RPY720HZ=75E12E63-0CD0-4D6F-8383-C90D5C8397C7; Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0
15:14:05.894:qtp551889550-57:http://0:0:0:0:0:0:0:1:8080/ RESPONSE 200 null
15:14:05.959:qtp551889550-59:http://0:0:0:0:0:0:0:1:8080/jetty.css REQUEST 0:0:0:0:0:0:0:1 GET __utma=111872281.10102721.1321534299.1369833564.1370447492.35; __utmz=111872281.1321534299.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _opt_vi_RPY720HZ=75E12E63-0CD0-4D6F-8383-C90D5C8397C7; visited=yes; Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0
15:14:05.962:qtp551889550-59:http://0:0:0:0:0:0:0:1:8080/jetty.css RESPONSE 200 null
15:14:06.052:qtp551889550-57:http://0:0:0:0:0:0:0:1:8080/images/jetty-header.jpg REQUEST 0:0:0:0:0:0:0:1 GET __utma=111872281.10102721.1321534299.1369833564.1370447492.35; __utmz=111872281.1321534299.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _opt_vi_RPY720HZ=75E12E63-0CD0-4D6F-8383-C90D5C8397C7; visited=yes; Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0
15:14:06.055:qtp551889550-57:http://0:0:0:0:0:0:0:1:8080/images/jetty-header.jpg RESPONSE 200 null
15:14:07.248:qtp551889550-59:http://0:0:0:0:0:0:0:1:8080/favicon.ico REQUEST 0:0:0:0:0:0:0:1 GET __utma=111872281.10102721.1321534299.1369833564.1370447492.35; __utmz=111872281.1321534299.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _opt_vi_RPY720HZ=75E12E63-0CD0-4D6F-8383-C90D5C8397C7; visited=yes; Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0
15:14:07.251:qtp551889550-59:http://0:0:0:0:0:0:0:1:8080/favicon.ico RESPONSE 404 text/html;charset=ISO-8859-1
15:14:09.330:qtp551889550-57 CLOSED HttpConnection@e910ee4{INTERESTED},g=HttpGenerator{s=START},p=HttpParser{s=START,0 of -1}
----

View File

@ -0,0 +1,54 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[default-handler]]
=== Default Handler
[[default-handler-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.DefaultHandler`
* Maven Artifact: org.eclipse.jetty:jetty-server
* Javadoc: {JDURL}/org/eclipse/jetty/server/handler/DefaultHandler.html
* Xref: {JXURL}/org/eclipse/jetty/server/handler/DefaultHandler.html
[[default-handler-usage]]
==== Usage
A simple handler that is useful to terminate handler chains with a clean fashion.
As in the example below, if a resource to be served is not matched within the resource handler, the DefaultHandler will take care of producing a 404 page.
This class is a useful template to either extend and embrace or simply provide a similar implementation for customizing to your needs.
There is also an link:#error-handler[Error Handler] that services errors related to the servlet api specification so it is best to not get the two confused.
_____
[NOTE]
The DefaultHandler will also handle serving out the flav.ico file should a request make it through all of the other handlers without being resolved.
_____
[source,java]
----
Server server = new Server(8080);
HandlerList handlers = new HandlerList();
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setBaseResource(Resource.newResource("."));
handlers.setHandlers(new Handler[]
{ resourceHandler, new DefaultHandler() });
server.setHandler(handlers);
server.start();
----

View File

@ -0,0 +1,66 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[default-servlet]]
=== Default Servlet
[[default-servlet-metadata]]
==== Info
* Classname: `org.eclipse.jetty.servlet.DefaultServlet`
* Maven Artifact: org.eclipse.jetty:jetty-servlet
* Javadoc: {JDURL}/org/eclipse/jetty/servlet/DefaultServlet.html
* Xref: {JXURL}/org/eclipse/jetty/servlet/DefaultServlet.html
[[default-servlet-usage]]
==== Usage
The DefaultServlet implements the ResourceFactory interface and extends the HttpServlet abstract class.
It is usually mapped to / and provides handling for static content, OPTION and TRACE methods for the context.
The MOVE method is allowed if PUT and DELETE are allowed.
See DefaultServlet link:{JDURL}/org/eclipse/jetty/servlet/DefaultServlet.html[javadoc].
[[default-servlet-init]]
==== Init Parameters
Jetty supports the following initParameters:
acceptRanges::
If true, range requests and responses are supported.
dirAllowed::
If true, directory listings are returned if no welcome file is found.
Otherwise 403 Forbidden displays.
redirectWelcome::
If true, welcome files are redirected rather that forwarded.
gzip::
If set to true, then static content is served as gzip content encoded if a matching resource is found ending with ".gz".
resourceBase::
Set to replace the context resource base.
aliases::
If true, aliases of resources are allowed (that is, symbolic links and caps variations) and may bypass security constraints.
maxCacheSize::
Maximum total size of the cache or 0 for no cache.
maxCachedFileSize::
Maximum size of a file to cache.
maxCachedFiles::
Maximum number of files to cache.
useFileMappedBuffer::
If set to true, mapped file buffer serves static content.
Setting this value to false means that a direct buffer is used instead of a mapped file buffer.
By default, this is set to true.
otherGzipFileExtensions::
A comma separated list of other file extensions that signify that a file is gzip compressed.
If you don't explicitly set this, it defaults to ".svgz".

View File

@ -0,0 +1,117 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[dos-filter]]
=== Denial of Service Filter
[[dos-filter-metadata]]
==== Info
* Classname: `org.eclipse.jetty.servlets.DoSFilter`
* Maven Artifact: org.eclipse.jetty:jetty-servlets
* Javadoc: {JDURL}/org/eclipse/jetty/servlets/DoSFilter.html
* Xref: {JXURL}/org/eclipse/jetty/servlets/DoSFilter.html
[[dos-filter-usage]]
==== Usage
The Denial of Service (DoS) filter limits exposure to request flooding, whether malicious, or as a result of a misconfigured client.
The DoS filter keeps track of the number of requests from a connection per second.
If the requests exceed the limit, Jetty rejects, delays, or throttles the request, and sends a warning message.
The filter works on the assumption that the attacker might be written in simple blocking style, so by suspending requests you are hopefully consuming the attacker's resources.
The DoS filter is related to the QoS filter, using Continuations to prioritize requests and avoid thread starvation.
[[dos-filter-using]]
==== Using the DoS Filter
Jetty places throttled requests in a priority queue, giving priority first to authenticated users and users with an HttpSession, then to connections identified by their IP addresses.
Connections with no way to identify them have lowest priority.
To uniquely identify authenticated users, you should implement the The extractUserId(ServletRequest request) function.
===== Required JARs
To use the DoS Filter, these JAR files must be available in WEB-INF/lib:
* $JETTY_HOME/lib/ext/jetty-util.jar
* $JETTY_HOME/lib/ext/jetty-servlets.jar
===== Sample Configuration
Place the configuration in a webapp's web.xml or jetty-web.xml.
The default configuration allows 25 requests per connection at a time, servicing more important requests first, and queuing up the rest.
This example allow 30 requests at a time:
[source,xml]
----
<filter>
<filter-name>DoSFilter</filter-name>
<filter-class>org.eclipse.jetty.servlets.DoSFilter</filter-class>
<init-param>
<param-name>maxRequestsPerSec</param-name>
<param-value>30</param-value>
</init-param>
</filter>
----
[[dos-filter-init]]
===== Configuring DoS Filter Parameters
The following init parameters control the behavior of the filter:
maxRequestsPerSec::
Maximum number of requests from a connection per second.
Requests in excess of this are first delayed, then throttled.
Default is 25.
delayMs::
Delay imposed on all requests over the rate limit, before they are considered at all:
+
* 100 (ms) = Default
* -1 = Reject request
* 0 = No delay
* any other value = Delay in ms
maxWaitMs::
Length of time, in ms, to blocking wait for the throttle semaphore.
Default is 50 ms.
throttledRequests::
Number of requests over the rate limit able to be considered at once.
Default is 5.
throttleMs::
Length of time, in ms, to async wait for semaphore. Default is 30000L.
maxRequestMs::
Length of time, in ms, to allow the request to run. Default is 30000L.
maxIdleTrackerMs::
Length of time, in ms, to keep track of request rates for a connection, before deciding that the user has gone away, and
discarding it.
Default is 30000L.
insertHeaders::
If true, insert the DoSFilter headers into the response.
Defaults to true.
trackSessions::
If true, usage rate is tracked by session if a session exists.
Defaults to true.
remotePort::
If true and session tracking is not used, then rate is tracked by IP+port (effectively connection).
Defaults to false.
ipWhitelist::
A comma-separated list of IP addresses that will not be rate limited.
managedAttr::
If set to true, then this servlet is set as a ServletContext attribute with the filter name as the attribute name.
This allows a context external mechanism (for example, JMX via ContextHandler.MANAGED_ATTRIBUTES) to manage the configuration of the filter.

View File

@ -0,0 +1,33 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[error-handler]]
=== Error Handler
[[error-handler-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.ErrorHandler`
* Maven Artifact: org.eclipse.jetty:jetty-server
* Javadoc: {JDURL}/org/eclipse/jetty/server/handler/ErrorHandler.html
* Xref: {JXURL}/org/eclipse/jetty/server/handler/ErrorHandler.html
[[error-handler-usage]]
==== Usage
A handler that is used to report errors from servlet contexts and webapp contexts to report error conditions.
Primarily handles setting the various servlet spec specific response headers for error conditions.
Can be customized by extending, for more information on this see xref:custom-error-pages[].

View File

@ -0,0 +1,85 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[gzip-filter]]
=== Gzip Handler
[[gzip-filter-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.gzip.GzipHandler`
* Maven Artifact: org.eclipse.jetty:jetty-servlets
* Javadoc:
{JDURL}/org/eclipse/jetty/server/handler/gzip/GzipHandler.html
* Xref: {JXURL}/org/eclipse/jetty/server/handler/gzip/GzipHandler.html
[[gzip-filter-usage]]
==== Usage
The Jetty GzipHandler is a compression handler that you can apply to any dynamic resource (servlet).
It fixes many of the bugs in commonly available compression filters: it works with asynchronous servlets; it handles all ways to set content length.
We have tested it with Jetty continuations and suspending requests.
Some user-agents might be excluded from compression to avoid common browser bugs (yes, this means IE!).
The GzipHandler is added to the entire server by the etc/jetty-gzip.xml file from the gzip.mod module.
It may also be added to individual contexts in a context xml file.
[[gzip-filter-rules]]
==== Gzip Rules
GZIP Handler will gzip or deflate the content of a response if:
* It is mapped to a matching path
* The request method is configured to support gzip
* The request is not from an excluded User-Agent
* accept-encoding header is set to either gzip, deflate or a combination of those
* The response status code is >=200 and <300
* The content length is unknown or more than the minGzipSize initParameter or the minGzipSize is 0(default)
* The content-type does not match an excluded mime-type
* No content-encoding is specified by the resource
If both gzip and deflate are specified in the accept-encoding header, then gzip will be used.
Compressing the content can greatly improve the network bandwidth usage, but at a cost of memory and CPU cycles.
The link:#default-servlet[DefaultServlet] is capable of serving pre-compressed static content, which saves memory and CPU.
By default, the GzipHandler will check to see if pre-compressed content exists, and pass the request through to be handled by the DefaultServlet.
[[gzip-filter-init]]
==== Gzip Configuration
minGzipSize::
Content will only be compressed if content length is either unknown or greater than minGzipSize.
checkGzExists::
True by default. If set to false, the handler will not check for pre-compressed content.
compressionLevel::
The compression level used for deflate compression. (0-9).
includedMethods::
List of HTTP methods to compress. If not set, only GET requests are compressed.
includedMimeTypes::
List of mime types to compress.
excludedMimeTypes::
List of mime types not to compress.
excludedAgentPatterns::
A list of regex patterns for User-Agent names from which requests should not be compressed.
excludedPaths::
List of paths to exclude from compression.
Does a String.startsWith(String) comparison to check if the path matches.
If it does match -> no compression.
To match subpaths use excludePathPatterns instead.
includedPaths::
List of paths to consider for compression.
includePaths::
List of paths to definitely consider for compression.

View File

@ -0,0 +1,73 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[ipaccess-handler]]
=== IP Access Handler
[[ipaccess-handler-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.IPAccessHandler`
* Maven Artifact: org.eclipse.jetty:jetty-server
* Javadoc: {JDURL}/org/eclipse/jetty/server/handler/IPAccessHandler.html
* Xref: {JXURL}/org/eclipse/jetty/server/handler/IPAccessHandler.html
[[ipaccess-handler-usage]]
==== Usage
Controls access to the wrapped handler by the real remote IP.
Control is provided by white/black lists that include both internet addresses and URIs.
This handler uses the real internet address of the connection, not one reported in the forwarded for headers, as this cannot be as easily forged.
Typically, the black/white lists will be used in one of three modes:
* Blocking a few specific IPs/URLs by specifying several black list entries.
* Allowing only some specific IPs/URLs by specifying several white lists entries.
* Allowing a general range of IPs/URLs by specifying several general white list entries, that are then further refined by several specific black list exceptions.
An empty white list is treated as match all.
If there is at least one entry in the white list, then a request must match a white list entry.
Black list entries are always applied, so that even if an entry matches the white list, a black list entry will override it.
Internet addresses may be specified as absolute address or as a combination of four octet wildcard specifications (a.b.c.d) that are defined as follows.
* nnn - an absolute value (0-255)
* mmm-nnn - an inclusive range of absolute values, with following shorthand notations:
** nnn- => nnn-255
** -nnn => 0-nnn
** - => 0-255
* a,b,... - a list of wildcard specifications
Internet address specification is separated from the URI pattern using the "|" (pipe) character.
URI patterns follow the servlet specification for simple * prefix and suffix wild cards (e.g. /, /foo, /foo/bar, /foo/bar/*, *.baz).
Earlier versions of the handler used internet address prefix wildcard specification to define a range of the internet addresses (e.g. 127., 10.10., 172.16.1.).
They also used the first "/" character of the URI pattern to separate it from the internet address.
Both of these features have been deprecated in the current version.
Examples of the entry specifications are:
* 10.10.1.2 - all requests from IP 10.10.1.2
* 10.10.1.2|/foo/bar - all requests from IP 10.10.1.2 to URI /foo/bar
* 10.10.1.2|/foo/* - all requests from IP 10.10.1.2 to URIs starting with /foo/
* 10.10.1.2|*.html - all requests from IP 10.10.1.2 to URIs ending with .html
* 10.10.0-255.0-255 - all requests from IPs within 10.10.0.0/16 subnet
* 10.10.0-.-255|/foo/bar - all requests from IPs within 10.10.0.0/16 subnet to URI /foo/bar
* 10.10.0-3,1,3,7,15|/foo/* - all requests from IPs addresses with last octet equal to 1,3,7,15 in subnet 10.10.0.0/22 to URIs starting with /foo/
Earlier versions of the handler used internet address prefix wildcard specification to define a range of the internet addresses (e.g. 127., 10.10., 172.16.1.).
They also used the first "/" character of the URI pattern to separate it from the internet address.
Both of these features have been deprecated in the current version.

View File

@ -0,0 +1,74 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[moved-context-handler]]
=== Moved Context Handler
[[moved-context-handler-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.MovedContextHandler`
* Maven Artifact: org.eclipse.jetty:jetty-server
* Javadoc:
{JDURL}/org/eclipse/jetty/server/handler/MovedContextHandler.html
* Xref:
{JXURL}/org/eclipse/jetty/server/handler/MovedContextHandler.html
[[moved-context-handler-usage]]
==== Usage
You can use the MovedContextHandler to relocate or redirect a context that has changed context path and/or virtual hosts.
You can configure it to _permanently_ redirect the old URL to the new URL, in which case Jetty sends a Http Status code of 301 to the browser with the new URL.
Alternatively, you can make it non-permanent, in which case Jetty sends a 302 Http Status code along with the new URL.
In addition, as with any other context, you can configure a list of virtual hosts, meaning that this context responds only to requests to one of the listed host names.
Suppose you have a context deployed at /foo, but that now you want to deploy at the root context / instead.
* First you reconfigure and redeploy the context on Jetty.
* Next you need a way to redirect all the browsers who have bookmarked /foo to the new path.
You create a new context xml file in $JETTY_HOME/contexts and configure the MovedContextHandler to do the redirection from /foo to /.
Here's an example.
This is a permanent redirection, which also preserves pathinfo and query strings on the redirect:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.server.handler.MovedContextHandler">
<Set name="contextPath">/foo</Set>
<Set name="newContextURL">/</Set>
<Set name="permanent">true</Set>
<Set name="discardPathInfo">false</Set>
<Set name="discardQuery">false</Set>
<Set name="virtualHosts">
<Array type="String">
<Item>209.235.245.73</Item>
<Item>127.0.0.73</Item>
<Item>acme.org</Item>
<Item>www.acme.org</Item>
<Item>server.acme.org</Item>
</Array>
</Set>
</Configure>
----

View File

@ -0,0 +1,81 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[proxy-servlet]]
=== Proxy Servlet
[[proxy-servlet-metadata]]
==== Info
* Classname: `org.eclipse.jetty.proxy.ProxyServlet`
* Maven Artifact: org.eclipse.jetty:jetty-proxy
* Javadoc: {JDURL}/org/eclipse/jetty/proxy/ProxyServlet.html
* Xref: {JXURL}/org/eclipse/jetty/proxy/ProxyServlet.html
[[proxy-servlet-usage]]
==== Usage
An asynchronous servlet that forwards requests to another server either as a standard web reverse proxy (as defined by RFC2616) or as a transparent reverse proxy. Internally it uses the async jetty-client.
To facilitate JMX monitoring, the HttpClient instance is set as context attribute, prefixed with the servlet's name and exposed by the mechanism provided by ContextHandler.MANAGED_ATTRIBUTES.
[[proxy-servlet-init]]
==== Init Parameters
The following init parameters may be used to configure the servlet:
hostHeader::
forces the host header to a particular value
viaHost::
the name to use in the Via header: Via: http/1.1 <viaHost>
whiteList::
comma-separated list of allowed proxy hosts
blackList::
comma-separated list of forbidden proxy hosts
In addition, there are a number of init parameters that can be used to configure the HttpClient instance used internally for the proxy.
maxThreads::
Default Value: 256
+
The max number of threads of HttpClient's Executor
maxConnections::
Default Value: 32768
+
The max number of connections per destination.
RFC 2616 suggests that 2 connections should be opened per each destination, but browsers commonly open 6 or more. If this HttpClient is used for load testing, it is common to have only one destination (the server to load test), and it is recommended to set this value to a high value (at least as much as the threads present in the executor).
idleTimeout::
Default Value: 30000
+
The idle timeout in milliseconds that a connection can be idle, that is without traffic of bytes in either direction.
timeout::
Default Value: 60000
+
The total timeout in milliseconds for the request/response conversation.
requestBufferSize::
Default Value: 4096
+
The size of the request buffer the request is written into.
responseBufferSize::
Default Value: 4096
+
The size of the response buffer the response is written into.

View File

@ -0,0 +1,171 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[qos-filter]]
=== Quality of Service Filter
[[qos-filter-metadata]]
==== Info
* Classname: `org.eclipse.jetty.servlets.QoSFilter`
* Maven Artifact: org.eclipse.jetty:jetty-servlets
* Javadoc: {JDURL}/org/eclipse/jetty/servlets/QoSFilter.html
* Xref: {JXURL}/org/eclipse/jetty/servlets/QoSFilter.html
[[qos-filter-usage]]
==== Usage
Jetty supports Continuations, which allow non-blocking handling of HTTP requests, so that threads can be allocated in a managed way to provide application specific Quality of Service (QoS).
The QoSFilter is a utility servlet filter that implements some QoS features.
[[qos-understanding]]
==== Understanding the Problem
===== Waiting for Resources
Web applications frequently use JDBC Connection pools to limit the simultaneous load on the database.
This protects the database from peak loads, but makes the web application vulnerable to thread starvation.
Consider a thread pool with 20 connections, being used by a web application that that typically receives 200 requests per second and each request holds a JDBC connection for 50ms.
Such a pool can service on average 200*20*1000/50 = 400 requests per second.
However, if the request rate rises above 400 per second, or if the database slows down (due to a large query) or becomes momentarily unavailable, the thread pool can very quickly accumulate many waiting requests.
If, for example, the website is slashdotted or experiences some other temporary burst of traffic and the request rate rises from 400 to 500 requests per second, then 100 requests per second join those waiting for a JDBC connection.
Typically, a web server's thread pool contains only a few hundred threads, so a burst or slow DB need only persist for a few seconds to consume the entire web server's thread pool.
This is called thread starvation.
The key issue with thread starvation is that it effects the entire web application, and potentially the entire web server.
Even if the requests using the database are only a small proportion of the total requests on the web server, all requests are blocked because all the available threads are waiting on the JDBC connection pool.
This represents non graceful degradation under load and provides a very poor quality of service.
===== Prioritizing Resources
Consider a web application that is under extreme load.
This load might be due to a popularity spike (slashdot), usage burst (Christmas or close of business), or even a denial of service attack.
During such periods of load, it is often desirable not to treat all requests as equals, and to give priority to high value customers or administrative users.
The typical behaviour of a web server under extreme load is to use all its threads to service requests and to build up a backlog of unserviced requests.
If the backlog grows deep enough, then requests start to timeout and users experience failures as well as delays.
Ideally, the web application should be able to examine the requests in the backlog, and give priority to high value customers and administrative users.
But with the standard blocking servlet API, it is not possible to examine a request without allocating a thread to that request for the duration of its handling.
There is no way to delay the handling of low priority requests, so if the resources are to be reallocated, then the low priority requests must all be failed.
[[qos-applying]]
==== Applying the QoSFilter
The Quality of Service Filter (QoSFilter) uses Continuations to avoid thread starvation, prioritize requests and give graceful degradation under load, to provide a high quality of service.
When you apply the filter to specific URLs within a web application, it limits the number of active requests being handled for those URLs.
Any requests in excess of the limit are suspended. When a request completes handling the limited URL, one of the waiting requests resumes and can be handled.
You can assign priorities to each suspended request, so that high priority requests resume before lower priority requests.
===== Required JARs
To use the QoS Filter, these JAR files must be available in WEB-INF/lib:
* $JETTY_HOME/lib/ext/jetty-util.jar
* $JETTY_HOME/lib/ext/jetty-servlets.jarcontains QoSFilter
===== Sample Configuration
Place the configuration in a webapp's web.xml or jetty-web.xml.
The default configuration processes ten requests at a time, servicing more important requests first, and queuing up the rest.
This example processes fifty requests at a time:
[source,xml]
----
<filter>
<filter-name>QoSFilter</filter-name>
<filter-class>org.eclipse.jetty.servlets.QoSFilter</filter-class>
<init-param>
<param-name>maxRequests</param-name>
<param-value>50</param-value>
</init-param>
</filter>
----
[[qos-filter-init]]
===== Configuring QoS Filter Parameters
A semaphore polices the "maxRequests" limit.
The filter waits a short time while attempting to acquire the semaphore.
The "waitMs" init parameter controls the wait, avoiding the expense of a suspend if the semaphore is shortly available.
If the semaphore cannot be obtained, Jetty suspends the request for the default suspend period of the container or the value set as the "suspendMs" init parameter.
The QoS filter uses the following init parameters:
maxRequests::
the maximum number of requests to be serviced at a time. The default is 10.
maxPriority::
the maximum valid priority that can be assigned to a request.
A request with a high priority value is more important than a request with a low priority value. The default is 10.
waitMS::
waitMSlength of time, in milliseconds, to wait while trying to accept a new request.
Used when the maxRequests limit is reached.
Default is 50 ms.
suspendMS::
length of time, in milliseconds, that the request will be suspended if it is not accepted immediately.
If not set, the container's default suspend period applies. Default is -1 ms.
managedAttr::
If set to true, then this servlet is set as a ServletContext attribute with the filter name as the attribute name.
This allows a context external mechanism (for example, JMX via ContextHandler.MANAGED_ATTRIBUTES) to manage the configuration of the filter.
===== Mapping to URLs
You can use the `<filter-mapping>` syntax to map the QoSFilter to a servlet, either by using the servlet name, or by using a URL pattern.
In this example, a URL pattern applies the QoSFilter to every request within the web application context:
[source,xml]
----
<filter-mapping>
<filter-name>QoSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
----
===== Setting the Request Priority
Requests with higher values have a higher priority.
The default request priorities assigned by the QoSFilter are:
* 2 -- For any authenticated request
* 1 -- For any request with a non-new valid session
* 0 -- For all other requests
To customize the priority, subclass QoSFilter and then override the getPriority(ServletRequest request) method to return an appropriate priority for the request.
You can then use this subclass as your QoS filter.
Here's a trivial example:
[source,java]
----
public class ParsePriorityQoSFilter extends QoSFilter
{
protected int getPriority(ServletRequest request)
{
String p = ((HttpServletRequest)request).getParameter("priority");
if (p!=null)
return Integer.parseInt(p);
return 0;
}
}
----

View File

@ -0,0 +1,56 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[resource-handler]]
=== Resource Handler
[[resource-handler-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.ResourceHandler`
* Maven Artifact: org.eclipse.jetty:jetty-server
* Javadoc: {JDURL}/org/eclipse/jetty/server/handler/ResourceHandler.html
* Xref: {JXURL}/org/eclipse/jetty/server/handler/ResourceHandler.html
[[resource-handler-usage]]
==== Usage
This handler will serve static content and handle If-Modified-Since headers and is suitable for simple serving of static content.
____
[IMPORTANT]
There is no caching done with this handler so if you are looking for a more featureful way of serving static content look to the xred:default-servlet[].
____
____
[NOTE]
Requests for resources that do not exist are let pass (Eg no 404's).
____
==== Improving the Look and Feel
The resource handler has a default stylesheet which you can change by calling `setStyleSheet(String location)` with the location of a file on the system that it can locate through the resource loading system.
The default css is called jetty-dir.css and is located in the jetty-util package, pulled as a classpath resource from the jetty-util jar when requested through the ResourceHandler.
==== Embedded Example
The following is an example of a split fileserver, able to serve static content from multiple directory locations.
Since this handler does not return 404's on content you are able to iteratively try multiple resource handlers to resolve content.
[source,java]
----
include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SplitFileServer.java[]
----

View File

@ -0,0 +1,146 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[rewrite-handler]]
=== Rewrite Handler
The RewriteHandler matches a request against a set of rules, and modifies the request accordingly for any rules that match. The most common use is to rewrite request URIs, but it is capable of much more: rules can also be configured to redirect the response, set a cookie or response code on the response, modify the header, etc.
[[rewrite-handler-metadata]]
==== Info
* Classname: org.eclipse.jetty.rewrite.handler.RewriteHandler
* Maven artifact: org.eclipse.jetty:jetty-rewrite
* Javadoc: {JDURL}/org/eclipse/jetty/rewrite/handler/RewriteHandler.html
* Xref: {JXURL}/org/eclipse/jetty/rewrite/handler/RewriteHandler.html
The standard Jetty distribution bundle contains the `jetty-rewrite` link:#startup-modules[module], so all you need to do is to enable it using one of the link:#start-jar[module commands], eg:
....
$ java -jar start.jar --add-to-startd=rewrite
....
_____
[NOTE]
If you are running the standard Jetty distribution with the sample test webapp, there will be a demo of the rewrite module at http://localhost:8080/test/rewrite/
_____
==== Usage
The rewrite module enables the following jetty xml config file on the execution path:
[source,xml]
----
include::{SRCDIR}/jetty-rewrite/src/main/config/etc/jetty-rewrite.xml[]
----
As the commented out code shows, you configure the RewriteHandler by adding various rules.
There is an example of link:#rewrite-rules[rules] configuration in the standard distribution in the `demo-base/etc/demo-rewrite-rules.xml` file:
[source,xml]
----
include::{SRCDIR}/tests/test-webapps/test-jetty-webapp/src/main/config/demo-base/etc/demo-rewrite-rules.xml[]
----
===== Embedded Example
This is an example for embedded Jetty, which does something similar to the configuration file example above:
[source,java]
----
Server server = new Server();
RewriteHandler rewrite = new RewriteHandler();
rewrite.setRewriteRequestURI(true);
rewrite.setRewritePathInfo(false);
rewrite.originalPathAttribute("requestedPath");
RedirectPatternRule redirect = new RedirectPatternRule();
redirect.setPattern("/redirect/*");
redirect.setReplacement("/redirected");
rewrite.addRule(redirect);
RewritePatternRule oldToNew = new RewritePatternRule();
oldToNew.setPattern("/some/old/context");
oldToNew.setReplacement("/some/new/context");
rewrite.addRule(oldToNew);
RewriteRegexRule reverse = new RewriteRegexRule();
reverse.setRegex("/reverse/([^/]*)/(.*)");
reverse.setReplacement("/reverse/$2/$1");
rewrite.addRule(reverse);
server.setHandler(rewrite);
----
[[rewrite-rules]]
==== Rules
There are several types of rules that are written extending useful base rule classes.
===== PatternRule
Matches against the request URI using the servlet pattern syntax.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/CookiePatternRule.html[CookiePatternRule]::
Adds a cookie to the response.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/HeaderPatternRule.html[HeaderPatternRule]::
Adds/modifies a header in the response.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/RedirectPatternRule.html[RedirectPatternRule]::
Redirects the response.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/ResponsePatternRule.html[ResponsePatternRule]::
Sends the response code (status or error).
link:{JXURL}/org/eclipse/jetty/rewrite/handler/RewritePatternRule.html[RewritePatternRule]::
Rewrite the URI by replacing the matched request path with a fixed string.
===== RegexRule
Matches against the request URI using regular expressions.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/RedirectRegexRule.html[RedirectRegexRule]::
Redirect the response.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/RewriteRegexRule.html[RewriteRegexRule]::
Rewrite the URI by matching with a regular expression.
(The replacement string may use Template:$n to replace the nth capture group.)
===== HeaderRule
Match against request headers. Match either on a header name + specific value, or on the presence of a header (with any value).
link:{JXURL}/org/eclipse/jetty/rewrite/handler/ForwardedSchemeHeaderRule.html[ForwardedSchemaHeaderRule]::
Set the scheme on the request (defaulting to https).
===== Others
Oddball rules that defy classification.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/MsieSslRule.html[MsieSslRule]::
Disables the keep alive for SSL from IE5 or IE6.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/LegacyRule.html[LegacyRule]::
Implements the legacy API of RewriteHandler
===== RuleContainer
Groups rules together. The contained rules will only be processed if the conditions for the RuleContainer evaluate to true.
link:{JXURL}/org/eclipse/jetty/rewrite/handler/VirtualHostRuleContainer.html[VirtualHostRuleContainer]::
Groups rules that apply only to a specific virtual host or a set of virtual hosts

View File

@ -0,0 +1,71 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[shutdown-handler]]
=== Shutdown Handler
[[shutdown-handler-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.ShutdownHandler`
* Maven Artifact: org.eclipse.jetty:jetty-server
* Javadoc: {JDURL}/org/eclipse/jetty/server/handler/ShutdownHandler.html
* Xref: {JXURL}/org/eclipse/jetty/server/handler/ShutdownHandler.html
[[shutdown-handler-usage]]
==== Usage
A handler that shuts the server down on a valid request.
Used to do "soft" restarts from Java.
If _exitJvm is set to true a hard System.exit() call is being made.
This is an example of how you can setup this handler directly with the Server, it can be added as a part of handler chain or collection as well.
[source,java]
----
Server server = new Server(8080);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]
{ someOtherHandler, new ShutdownHandler(server,"secret password") });
server.setHandler(handlers);
server.start();
----
And this is an example that you can use to call the shutdown handler from within java.
[source,java]
----
public static void attemptShutdown(int port, String shutdownCookie) {
try {
URL url = new URL("http://localhost:" + port + "/shutdown?token=" + shutdownCookie);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.getResponseCode();
logger.info("Shutting down " + url + ": " + connection.getResponseMessage());
} catch (SocketException e) {
logger.debug("Not running");
// Okay - the server is not running
} catch (IOException e) {
throw new RuntimeException(e);
}
}
----

View File

@ -0,0 +1,125 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[statistics-handler]]
=== Statistics Handler
[[statistics-handler-metadata]]
==== Info
* Classname: `org.eclipse.jetty.server.handler.StatisticsHandler`
* Maven Artifact: org.eclipse.jetty:jetty-server
* Javadoc:
{JDURL}/org/eclipse/jetty/server/handler/StatisticsHandler.html
* Xref: {JXURL}/org/eclipse/jetty/server/handler/StatisticsHandler.html
[[statistics-handler-usage]]
==== Usage
Jetty currently has two levels of request statistic collection:
* Subclasses of AbstractConnector class optionally can collect statistics about connections as well as number of requests.
* The StatisticsHandler class may be used to collect request statistics.
In addition to that, subclasses of AbstractSessionHandler class optionally can collect session statistics.
AbstractConnector and AbstractSessionHandler statistics are turned off by default and must either be configured manually for each instance or
turned on via JMX interface.
The Statistics Handler is not included in default Jetty configuration, and needs to be configured manually.
_____
[NOTE]
To view statistics, you have to be able to connect to Jetty using either JConsole or some other JMX agent. See xref:using-jmx[] for more information.
_____
[[connector-statistics]]
==== Connector statistics
Detailed statistics on connection duration and number of requests are only collated when a connection is closed.
The current and maximum number of connections are the only "live" statistics.
To learn how to turn on connector statistics please see Jetty Statistics tutorial, although this is not recommended and it is best to use a JMX agent to select statistics only when needed.
The following example shows how to turn on connector statistics in jetty xml.
This example comes from within `jetty-http.xml`.
[source,xml]
----
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<Item>
<New class="org.eclipse.jetty.server.HttpConnectionFactory">
<Arg name="config"><Ref refid="httpConfig" /></Arg>
</New>
</Item>
</Array>
</Arg>
<Set name="host"><Property name="jetty.host" /></Set>
<Set name="port"><Property name="jetty.http.port" default="8080" /></Set>
<Set name="idleTimeout">30000</Set>
<!-- Enable Connector Statistics -->
<Call name="addBean">
<Arg>
<New id="ConnectorStatistics" class="org.eclipse.jetty.server.ConnectorStatistics"/>
</Arg>
</Call>
</New>
</Arg>
</Call>
----
[[request-statistics]]
==== Request Statistics
To collect request statistics a StatisticsHandler must be configured as one of the handlers of the server.
Typically this can be done as the top level handler, but you may choose to configure a statistics handler for just one context by creating a context configuration file.
Please note that `jetty-stats.xml` has to appear in the command line after the main Jetty configuration file as shown below.
It should be able to be uncommented in the start.ini file.
....
$ java -jar start.jar OPTIONS=default etc/jetty.xml etc/jetty-stats.xml
....
Alternately, if you are making multiple changes to the Jetty configuration, you could include statistics handler configuration into your own jetty xml configuration.
The following fragment shows how to configure a top level statistics handler:
[source,xml]
----
<Get id="oldhandler" name="handler" />
<Set name="handler">
<New id="StatsHandler" class="org.eclipse.jetty.server.handler.StatisticsHandler">
<Set name="handler"><Ref refid="oldhandler" /></Set>
</New>
</Set>
----
[[session-statistics]]
==== Session Statistics
Session handling is built into Jetty for any servlet or webapp context.
Detailed statistics on session duration are only collated when a session is closed.
The current, minimum, and maximum number of sessions are the only "live" statistics.
The session statistics are enabled by default and do not need to be configured.

View File

@ -0,0 +1,21 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[fastcgi]]
== FastCGI Support
include::fastcgi-intro.adoc[]
include::configuring-fastcgi.adoc[]

View File

@ -0,0 +1,176 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[configuring-fastcgi]]
=== Configuring Jetty for FastCGI
In this section you will see how to configure Jetty to serve WordPress via FastCGI.
The first step is to have WordPress installed in your server machine, for example under `/var/www/wordpress`.
For more information about how to install WordPress, please refer to the https://codex.wordpress.org/Installing_WordPress[WordPress Installation Guide].
The second step is to install `php-fpm` and make sure it is configured to listen on a TCP socket; typically it is configured to listen to `localhost:9000`.
The third step is to install Jetty, for example under `/opt/jetty`, called in the following `$JETTY_HOME`.
Refer to xref:jetty-downloading[] for more information about how to install Jetty.
The fourth step is to create a Jetty base directory (see xref:startup-base-and-home[]), called in the following `$JETTY_BASE`, where you setup the configuration needed to support FastCGI in Jetty, and configure the `fcgi`, `http` and `deploy` modules, so that Jetty will be able to accept HTTP requests from browsers, convert them in FastCGI, and proxy them to `php-fpm`:
....
$ mkdir -p /usr/jetty/wordpress
$ cd /usr/jetty/wordpress
$ java -jar $JETTY_HOME/start.jar --add-to-module=fcgi,http,deploy
....
Therefore `$JETTY_BASE=/usr/jetty/wordpress`.
The fifth step is to deploy the web application that provides the proxying of client requests to the FastCGI server, `php-fpm`.
Typically this is done by deploying a `*.war` file in the `$JETTY_BASE/webapps` directory, but in case of FastCGI there is really nothing of this web application that you have to write: all the work is already done for you by the Jetty developers.
Therefore you just need to deploy a Jetty XML file that configures the web application directly.
Copy and paste the following content as `$JETTY_BASE/webapps/jetty-wordpress.xml`
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">
<Configure class="org.eclipse.jetty.servlet.ServletContextHandler">
<New id="root" class="java.lang.String">
<Arg>/var/www/wordpress</Arg>
</New>
<Set name="contextPath">/</Set>
<Set name="resourceBase"><Ref refid="root" /></Set>
<Set name="welcomeFiles">
<Array type="string"><Item>index.php</Item></Array>
</Set>
<Call name="addFilter">
<Arg>org.eclipse.jetty.fcgi.server.proxy.TryFilesFilter</Arg>
<Arg>/*</Arg>
<Arg>
<Call name="of" class="java.util.EnumSet">
<Arg><Get name="REQUEST" class="javax.servlet.DispatcherType" /></Arg>
</Call>
</Arg>
<Call name="setInitParameter">
<Arg>files</Arg>
<Arg>$path /index.php?p=$path</Arg>
</Call>
</Call>
<Call name="addServlet">
<Arg>
<New class="org.eclipse.jetty.servlet.ServletHolder">
<Arg>default</Arg>
<Arg>
<Call name="forName" class="java.lang.Class">
<Arg>org.eclipse.jetty.servlet.DefaultServlet</Arg>
</Call>
</Arg>
<Call name="setInitParameter">
<Arg>dirAllowed</Arg>
<Arg>false</Arg>
</Call>
</New>
</Arg>
<Arg>/</Arg>
</Call>
<Call name="addServlet">
<Arg>org.eclipse.jetty.fcgi.server.proxy.FastCGIProxyServlet</Arg>
<Arg>*.php</Arg>
<Call name="setInitParameter">
<Arg>proxyTo</Arg>
<Arg>http://localhost:9000</Arg>
</Call>
<Call name="setInitParameter">
<Arg>prefix</Arg>
<Arg>/</Arg>
</Call>
<Call name="setInitParameter">
<Arg>scriptRoot</Arg>
<Arg><Ref refid="root" /></Arg>
</Call>
<Call name="setInitParameter">
<Arg>scriptPattern</Arg>
<Arg>(.+?\\.php)</Arg>
</Call>
</Call>
</Configure>
----
Explanation of this file content:
* At line 6 it is specified the WordPress installation directory, in this example `/var/www/wordpress` (as defined in the first step).
* At line 9 it is specified the context path at which WordPress will be served, in this example at the root context path `/`.
* At line 10 it is specified the resource base of the context, also set to the WordPress installation directory. This allows Jetty to serve static resources directly from the WordPress installation directory.
* At line 12 it is specified the welcome file as `index.php`, so that Jetty can perform the proper redirects in case of URIs ending with the `/` character.
* At line 15 it is specified the `TryFilesFilter`, a Servlet Filter that has been inspired by the http://wiki.nginx.org/HttpCoreModule#try_files[try_files] functionality offered by Nginx.
This filter tries to serve the resource from the file system first, and if the resource is not found it forwards the request as `index.php?p=$path`, which will match the proxy servlet defined below.
Refer to the link:{JDURL}/org/eclipse/jetty/fcgi/server/proxy/TryFilesFilter.html[TryFilesFilter] documentation for further information.
* At line 29 it is specified Jetty's `DefaultServlet` to serve static content such as CSS files, JavaScript files, etc. `DefaultServlet` will serve these files by looking in the resource base of the context, defined at line 10 (see above).
* At line 47 it is specified the `FastCGIProxyServlet`, a Servlet that proxies HTTP requests arriving from clients to FastCGI requests to the FastCGI server.
* At line 52 it is specified the TCP address of the FastCGI server (`php-fpm`), where HTTP requests are forwarded as FastCGI requests.
* At line 60 it is specified once again the WordPress installation directory, so that the `FastCGIProxyServlet` can pass this information to the FastCGI server.
* At line 64 it is specified a regular expression that matches request URIs performed to this servlet, in addition to the standard URL mapping defined by Servlet at line 49.
Refer to the link:{JDURL}/org/eclipse/jetty/fcgi/server/proxy/FastCGIProxyServlet.html[FastCGIProxyServlet] documentation for further information.
The last step is to start Jetty (see xref:startup[]) and hit `http://localhost:8080` with your browser and enjoy WordPress:
....
$ cd $JETTY_BASE
$ java -jar /opt/jetty/start.jar
....
[[configuring-fastcgi-http2]]
==== Configuring Jetty to Proxy HTTP/2 to FastCGI
In order to configure Jetty to listen for HTTP/2 requests from clients that are HTTP/2 enabled and forward them to the FastCGI server as FastCGI requests, you need to enable the `http2` module, which in turn will require a TLS connector and consequently a keystore to read the key material required by TLS.
Enabling the `http2` is really simple; in additions to the modules you have enabled above, add the `http2` module:
....
$ cd $JETTY_BASE
$ java -jar $JETTY_HOME/start.jar --add-to-start=http2
....
The command above adds the `http2` module (and its dependencies) to the existing modules and uses the default Jetty keystore to provide the key material required by TLS.
You will want to use your own keystore with your own private key and certificate for your own domain.
Remember that by adding the `http2` module, you will start two JVMs: one that reads the configuration, and one that has the ALPN boot boot jar in the boot classpath, as explained in xref:http2-configuring[].
Since now your site will run over TLS, you need to make sure that the WordPress URL is also configured so.
If you have followed the steps of the link:#configuring-fastcgi[previous section], your WordPress site is served at `http://localhost:8080`.
You will need to change that to be `https://localhost:8443` from the WordPress administration web interface, or follow the http://codex.wordpress.org/Changing_The_Site_URL[WordPress instructions] to do so without using the administration web interface.
The minimal modules required to run WordPress with Jetty on HTTP/2 are therefore: `http2`, `http`, `fcgi` and `deploy`.
These will setup a clear text connector on port 8080 for HTTP/1.1 and a TLS connector on port 8443 for HTTP/2 and HTTP/1.1.
At this point, you can start Jetty (see xref:startup[]), hit `http://localhost:8080` with your browser and enjoy WordPress via HTTP/2 using a HTTP/2 enabled browser:
....
$ cd $JETTY_BASE
$ java -jar $JETTY_HOME/start.jar
....
If you don't have a HTTP/2 enabled browser, WordPress will still be available over plain HTTP/1.1.

View File

@ -0,0 +1,34 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[fastcgi-intro]]
=== FastCGI Introduction
FastCGI is a network protocol primarily used by a _web server_ to communicate to a __FastCGI server__.
FastCGI servers are typically used to serve web content generated by dynamic web languages, primarily http://www.php.net/[PHP], but also Python, Ruby, Perl and others.
Web servers that supports FastCGI are, among others, http://httpd.apache.org/[Apache] and http://nginx.org/[Nginx], and Jetty.
Web servers typically act as proxies, converting HTTP requests that they receive from clients (browsers) to FastCGI requests that are forwarded to the FastCGI server.
The FastCGI server spawns the dynamic web language interpreter, passing it the information contained in the FastCGI request and a dynamic web language script is executed, producing web content, typically HTML.
The web content is then formatted into a FastCGI response that is returned to the web server, which converts it to a HTTP response that is then returned to the client.
The most well known FastCGI server is the http://php-fpm.org/[PHP FastCGI Process Manager], or `php-fpm`.
In the following we will assume that `php-fpm` is used as FastCGI server.
Jetty can be configured to act as a web server that supports FastCGI, replacing the functionality that is normally provided by Apache or Nginx.
This allows users to leverage Jetty features such as HTTP/2, the unique support that Jetty provides for HTTP/2 Push, Jetty's scalability, and of course Jetty's native support for Java Web Standards such as Servlets, JSPs, etc.
With such configuration, users can deploy their Java Web Applications in Jetty, but also serve their http://wordpress.com/[WordPress] site or blog or their https://drupal.org/[Drupal] site without having to install and manage multiple web servers.

View File

@ -0,0 +1,24 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[http2]]
== HTTP/2
include::introduction.adoc[]
include::enabling-http2.adoc[]
include::configuring-http2.adoc[]
include::configuring-push.adoc[]
include::configuring-haproxy.adoc[]

View File

@ -0,0 +1,201 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[http2-configuring-haproxy]]
=== Configuring HAProxy and Jetty
Typical website deployments have Apache (or Nginx) configured as reverse proxy to talk to one or more backend Jetty instances.
This configuration cannot be used for HTTP/2 because Apache does not yet support HTTP/2 (nor does Nginx).
http://haproxy.org[HAProxy] is an open source solution that offers load balancing and proxying for TCP and HTTP based application, and can be used as a replacement for Apache (or Nginx) when these are used as reverse proxies, and has the major benefit that supports HTTP/2.
It also offers load balancing and a ton of other features, so you can probably use it as a replacement for Apache (or Nginx).
The deployment proposed here will have HAProxy play the role that Apache (or Nginx) usually do: to perform the TLS offloading (that is, decrypt and encrypt TLS) and then forwarding the now clear-text traffic to a backend Jetty server, speaking either HTTP/1.1 or HTTP/2.
The instructions that follow are for Linux.
[[http2-haproxy-install]]
==== Installing HAProxy
You will need HAProxy 1.5 or later, because it provides support for SSL and ALPN, both required by HTTP/2. Most Linux distributions have the HAProxy package available to be installed out of the box. For example on Ubuntu 15.04:
[source,shell]
----
$ sudo apt-get install haproxy
----
Alternatively you can download the HAProxy source code and build it on your environment, by following the README bundled with the HAProxy source code tarball.
____
[NOTE]
HAProxy supports ALPN only if built with OpenSSL 1.0.2 or greater.
Alternatively, HAProxy supports NPN when built with OpenSSL 1.0.1 or greater.
You must upgrade OpenSSL if you have a version earlier than 1.0.1.
Use `haproxy -vv` to know with which OpenSSL version HAProxy has been built.
____
[[http2-haproxy-ssl]]
==== Setup SSL for HAProxy
HAProxy will perform the TLS decryption and encryption much more efficiently than a Java implementation.
HAProxy will need a single file containing the X509 certificates and the private key, all in https://en.wikipedia.org/wiki/X.509[PEM format], with the following order:
1. The site certificate; this certificate's Common Name refers to the site domain (for example: CN=*.webtide.com) and it's signed by Certificate Authority #1.
2. The Certificate Authority #1 certificate; this certificate may be signed by Certificate Authority #2.
3. The Certificate Authority #2 certificate; this certificate may be signed by Certificate Authority #3; and so on until the Root Certificate Authority.
4. The Root Certificate Authority certificate.
5. The private key corresponding to the site certificate.
Let's use `keytool` to generate a self signed certificate:
[source,shell]
----
$ keytool -genkeypair -keyalg RSA -keystore keystore.p12 -storetype pkcs12 -storepass storepwd -ext SAN=DNS:domain.com
What is your first and last name?
[Unknown]: *.domain.com
What is the name of your organizational unit?
[Unknown]: Unit
What is the name of your organization?
[Unknown]: Domain
What is the name of your City or Locality?
[Unknown]: Torino
What is the name of your State or Province?
[Unknown]: TO
What is the two-letter country code for this unit?
[Unknown]: IT
Is CN=*.domain.com, OU=Unit, O=Domain, L=Torino, ST=TO, C=IT correct?
[no]: yes
----
The above command will generate a self signed certificate and private key for `domain.com` and subdomains, stored in the `keystore.p12` file in PKCS#12 format.
We need to extract the certificate and the private key in PEM format.
To extract the certificate into `certificate.pem`:
[source,shell]
----
$ keytool -exportcert -keystore keystore.p12 -storetype pkcs12 -storepass storepwd -rfc -file certificate.pem
----
To export the private key into `private_key.pem`:
[source,shell]
----
$ openssl pkcs12 -in keystore.p12 -nodes -nocerts -out private_key.pem -passin pass:storepwd
----
At this point you just need to concatenate the two files into one, in the correct order:
[source,shell]
----
$ cat certificate.pem private_key.pem > domain.pem
----
The `domain.pem` file will be used later by HAProxy.
[[http2-haproxy-cfg]]
==== HAProxy Configuration File
Now we can setup `haproxy.cfg` to configure HAProxy.
This is a minimal configuration:
....
global
tune.ssl.default-dh-param 1024
defaults
timeout connect 10000ms
timeout client 60000ms
timeout server 60000ms
frontend fe_http
mode http
bind *:80
# Redirect to https
redirect scheme https code 301
frontend fe_https
mode tcp
bind *:443 ssl no-sslv3 crt domain.pem ciphers TLSv1.2 alpn h2,http/1.1
default_backend be_http
backend be_http
mode tcp
server domain 127.0.0.1:8282
....
The HAProxy configuration file works in the following way.
The `fe_http` front-end accepts connections on port 80 and redirects them to use the `https` scheme.
The `fe_https` front-end accepts connections on port 443 and it is where the TLS decryption/encryption happens.
You must specify the path to the PEM file containing the TLS key material (the `crt domain.pem` part), the ciphers that are suitable for HTTP/2 (the `ciphers TLSv1.2` part), and the ALPN (or NPN if you are using old OpenSSL versions) protocols supported (the `alpn h2,http/1.1` part).
This front-end then forwards the now decrypted bytes to the back-end in `mode tcp`. The `mode tcp`) means that HAProxy will not try to interpret the bytes as HTTP/1.1 but just opaquely forward them to the back-end.
The `be_http` back-end will forward (again in `mode tcp`) the clear-text bytes to a Jetty connector that talks clear-text HTTP/2 and HTTP/1.1 on port 8282.
[[http2-haproxy-jetty]]
==== Setup Jetty for HTTP/2 and HTTP/1.1
The Jetty setup follows the usual steps of having Jetty installed in the `JETTY_HOME` directory, creating a `JETTY_BASE` directory and initializing it using Jetty's command line tools.
You must enable the `http2c` module, that is the module that speaks clear-text HTTP/2.
Since the `http2c` module depends on the `http` module, the `http` module will be enabled transitively, and the final setup will therefore support both HTTP/2 and HTTP/1.1 in clear text.
Additionally, you will also enable the `deploy` module to be able to deploy a sample web application:
[source,shell]
----
$ JETTY_BASE=haproxy-jetty-http2
$ mkdir $JETTY_BASE
$ cd $JETTY_BASE
$ java -jar $JETTY_HOME/start.jar --add-to-start=http2c,deploy
----
Now let's deploy a demo web application and start Jetty:
[source,shell]
----
$ cd $JETTY_BASE
$ cp $JETTY_HOME/demo-base/webapps/async-rest.war $JETTY_BASE/webapps/
$ java -jar $JETTY_HOME/start.jar jetty.http.host=127.0.0.1 jetty.http.port=8282
----
Now you can browse https://domain.com/async-rest (replace `domain.com` with your own domain, or with `localhost`, to make this example work).
____
[NOTE]
You want the Jetty connector that listens on port 8282 to be available only to HAProxy, and not to remote clients.
For this reason, you want to specify the `jetty.http.host` property on the command line (or in `start.ini` to make this setting persistent) to bind the Jetty connector only on the loopback interface (127.0.0.1), making it available to HAProxy but not to remote clients.
If your Jetty instance runs on a different machine and/or on a different (sub)network, you may want to adjust both the back-end section of the HAProxy configuration file and the `jetty.http.host` property to match accordingly.
____
Browsers supporting HTTP/2 will connect to HAProxy, which will decrypt the traffic and send it to Jetty.
Likewise, HTTP/1.1 clients will connect to HAProxy, which will decrypt the traffic and send it to Jetty.
The Jetty connector, configured with the `http2c` module (and therefore transitively with the `http` module) is able to distinguish whether the incoming bytes are HTTP/2 or HTTP/1.1 and will handle the request accordingly.
The response is relayed back to HAProxy, which will encrypt it and send it back to the remote client.
This configuration offers you efficient TLS offloading, HTTP/2 support and transparent fallback to HTTP/1.1 for clients that don't support HTTP/1.1.

View File

@ -0,0 +1,64 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[http2-configuring]]
=== Configuring HTTP/2
Enabling the HTTP/2 module in the jetty server does not create a HTTP/2 specific connector, but rather it adds a HTTP/2 Connection factory to an
existing connector.
Thus configuring HTTP/2 is a combination of configuring common properties on the connector and HTTP/2 specific properties on the connection factory.
The modules and XML files involved can be seen with the following commands:
[source,shell]
----
$ java -jar $JETTY_HOME/start.jar --list-modules
...
1) protonego-boot <transitive>
...
2) http ${jetty.base}/start.d/http.ini
2) ssl ${jetty.base}/start.d/ssl.ini
3) alpn ${jetty.base}/start.d/alpn.ini
3) http2c ${jetty.base}/start.d/http2c.ini
...
4) http2 ${jetty.base}/start.d/http2.ini
5) https ${jetty.base}/start.d/https.ini
$ java -jar $JETTY_HOME/start.jar --list-config
...
${jetty.home}/etc/jetty-ssl.xml
${jetty.home}/etc/jetty-ssl-context.xml
${jetty.home}/etc/jetty-alpn.xml
${jetty.home}/etc/jetty-http2c.xml
${jetty.home}/etc/jetty-http.xml
...
${jetty.home}/etc/jetty-http2.xml
${jetty.home}/etc/jetty-https.xml
----
The common properties associated with connectors (host,port, timeouts, etc.) can be set in the module ini files (or start.ini if --add-to-start was used): `${jetty.base}/start.d/http.ini` `${jetty.base}/start.d/ssl.ini`.
These properties are instantiated in the associated XML files: `${jetty.home}/etc/jetty-http.xml`; `${jetty.home}/etc/jetty-ssl.xml`, plus the SSL keystore is instantiated in `${jetty.home}/etc/jetty-ssl-context.xml`.
HTTP/2 specific properties can be set in the module ini files: `${jetty.base}/start.d/http2.ini`; `${jetty.base}/start.d/http2c.ini`, which are instantiated in the associated XML files: `${jetty.home}/etc/jetty-http2.xml`; `${jetty.home}/etc/jetty-http2c.xml`.
Currently there are very few HTTP/2 configuration properties and the default values are reasonable:
.HTTP/2 Configuration Properties
[cols=",",options="header",]
|=======================================================================
|Property |Description
|jetty.http2.maxConcurrentStreams |The maximum number of concurrently open streams allowed on a single HTTP/2 connection (default 1024). Larger values increase parallelism but cost a memory commitment.
|jetty.http2.initialStreamSendWindow |The initial flow control window size for a new stream (default 65535). Larger values may allow greater throughput but also risk head of line blocking if TCP/IP flow control is triggered.
|=======================================================================

View File

@ -0,0 +1,65 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[http2-configuring-push]]
=== Configuring HTTP/2 Push
HTTP/2 Push is a mechanism that allows the server to send multiple resources to the client for a single client request.
This will reduce the amount of round-trips necessary to retrieve all the resources that make up a web page, and can significantly improve the page load time.
HTTP/2 Push can be automated in your application by simply configuring a link:{JDURL}/org/eclipse/jetty/servlets/PushCacheFilter.html[`PushCacheFilter`] in your `web.xml`, in this way:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
metadata-complete="true"
version="3.1">
...
<filter>
<filter-name>PushFilter</filter-name>
<filter-class>org.eclipse.jetty.servlets.PushCacheFilter</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>PushFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
----
`PushCacheFilter` analyzes the HTTP requests for resources that arrive to your web application.
Some of these requests contain the HTTP `Referrer` header that points to a resource that has been requested previously.
This allows the `PushCacheFilter` to organize resources in _primary_ resources (those referenced by the `Referrer` header) and _secondary_ resources (those that have the `Referer` header).
`PushCacheFilter` associates secondary resources to primary resources.
Only secondary resources that have been requested within a time window from the request of the primary resource are associated with the primary resource.
`PushCacheFilter` can be configured with the following `init-params`::
* `associatePeriod`: the time window, in milliseconds, within which a request for a secondary resource will be associated to a primary resource.
* `maxAssociations`: the max number of secondary resources that may be associated to a primary resource.

View File

@ -0,0 +1,70 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[http2-enabling]]
=== Enabling HTTP/2
This section is written assuming that a jetty base directory is being used and a demo jetty base that support HTTP/1, HTTPS/1 and deployment from a webapps directory can be created with the commands:
....
$ JETTY_BASE=http2-demo
$ mkdir $JETTY_BASE
$ cd $JETTY_BASE
$ java -jar $JETTY_HOME/start.jar --add-to-startd=http,https,deploy
....
The commands above create a `$JETTY_BASE` directory called `http2-demo`, and initializes the `http,` `https` and `deploy` modules (and their dependencies) to run a typical Jetty Server on port 8080 (for HTTP/1) and 8443 (for HTTPS/1).
Note that the https module downloads a demo keystore file with a self signed certificate, which needs to be replaced by a Certificate Authority issued certificate for real deployment.
To add HTTP/2 to this demo base, it is just a matter of enabling the http2 module with the following command:
[source,shell]
----
$ java -jar $JETTY_HOME/start.jar --add-to-startd=http2
----
This command does not create a new connector, but instead simply adds the HTTP/2 protocol to the existing HTTPS/1 connector, so that it now supports both protocols on port 8443.
To do this, it also transitively enables the ALPN module for protocol negotiation.
The support for each protocol can be seen in the info logging when the server is started:
[source,shell]
----
$ java -jar $JETTY_HOME/start.jar
...
2015-06-17 14:16:12.549:INFO:oejs.ServerConnector:main: Started ServerConnector@34c9c77f{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2015-06-17 14:16:12.782:INFO:oejs.ServerConnector:main: Started ServerConnector@711f39f9{SSL,[ssl, alpn, h2, h2-17, http/1.1]}{0.0.0.0:8443}
...
----
This log shows that port 8080 supports only HTTP/1.1 (which by specification includes HTTP/1.0 support), while port 8443 supports the SSL protocol, with ALPN negotiation to select between several versions of HTTP/2 (h2 & the draft h2-17) and HTTP/1.1.
What is not shown, is that http/1.1 is the default ALPN protocol, so that if a client connects that does not speak ALPN, then HTTP/1.1 will be assumed.
A browser can now be pointed at `https://localhost:8443/` and if it supports HTTP/2 then it will be used (often indicated by a lightening bolt icon in the address bar).
Note that a browser pointed at this server with URL starting with `http://localhost:8080/` will still talk HTTP/1.1, as HTTP/2 has not been enabled on the plain text connector.
HTTP/2 can be enabled on the plain text connector and the server restarted with the following command:
[source,shell]
----
$ java -jar $JETTY_HOME/start.jar --add-to-startd=http2c
$ java -jar $JETTY_HOME/start.jar
...
2015-06-17 14:16:12.549:INFO:oejs.ServerConnector:main: Started ServerConnector@6f32cd1e{HTTP/1.1,[http/1.1, h2c, h2c-17]}{0.0.0.0:8080}
2015-06-17 14:16:12.782:INFO:oejs.ServerConnector:main: Started ServerConnector@711f39f9{SSL,[ssl, alpn, h2, h2-17, http/1.1]}{0.0.0.0:8443}
...
----
However, no major browser currently supports plain text HTTP/2, so the 8080 port will only be able to use HTTP/2 with specific clients (eg curl) that use the upgrade mechanism or assume HTTP/2

View File

@ -0,0 +1,42 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[http2-introduction]]
=== Introducing HTTP/2
Jetty supports both a client and a server implementation for the HTTP/2 protocol as defined by http://tools.ietf.org/html/rfc7540[RFC 7540].
The requirements for running HTTP/2 are JDK 8 or greater, and typically also ALPN support (see xref:alpn-chapter[]).
A server deployed over TLS (SSL) normally advertises the HTTP/2 protocol via the TLS extension Application Layer Protocol Negotiation link:#alpn[(ALPN)].
____
[IMPORTANT]
To use HTTP/2 in Jetty via a TLS connector you need to add the link:#alpn-starting[ALPN boot Jar in the boot classpath.]
This is done automatically when using the jetty distributions start.jar module system, but must be configured directly otherwise.
____
[[http2-modules]]
==== Jetty HTTP/2 Sub Projects
The Jetty HTTP/2 implementation consists of the following sub-projects (each producing a jar):
1. `http2-common`: contains the HTTP/2 API and a partial implementation shared across other modules.
2. `http2-hpack`: contains the HTTP/2 HPACK implementation for HTTP header compression.
3. `http2-server`: provides the server-side implementation of HTTP/2.
4. `http2-client`: provides the implementation of HTTP/2 client with a low level HTTP/2 API, dealing with HTTP/2 streams, frames, etc.
5. `http2-http-client-transport`: provides the implementation of the HTTP/2 transport for `HttpClient` (see xref:http-client[]).
Applications can use the higher level API provided by `HttpClient` to send HTTP requests and receive HTTP responses, and the HTTP/2 transport will take care of converting them in HTTP/2 format (see also https://webtide.com/http2-support-for-httpclient/[this blog entry]).

View File

@ -0,0 +1,22 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jmx-chapter]]
== JMX
include::using-jmx.adoc[]
include::jetty-jconsole.adoc[]
include::jetty-jmx-annotations.adoc[]

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

View File

@ -0,0 +1,98 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jetty-jconsole]]
=== Jetty JConsole
JConsole is a graphical tool; it allows you to remotely manage and monitor your server and web application status using JMX.
When following the instructions given below, please also ensure that you make any necessary changes to any anti-virus software you may be using which may prevent jconsole from running.
[[jetty-jconsole-monitoring]]
==== Monitoring Jetty with JConsole
To monitor Jetty's server status with JConsole, make sure JConsole is running, and start Jetty with a special system property.
===== Starting Jetty Standalone
The simplest way to enable support is to add the jmx support module to your $\{jetty.base}.
....
[mybase]$ java /opt/jetty-dist/start.jar --add-to-start=jmx
INFO: jmx-remote initialised in ${jetty.base}/start.ini (appended)
INFO: jmx initialised transitively
....
Then open the $\{jetty.base}/start.ini file and edit the properties to suit your needs:
....
#
# Initialize module jmx-remote
#
--module=jmx-remote
## JMX Configuration
## Enable for an open port accessible by remote machines
jetty.jmxrmihost=localhost
jetty.jmxrmiport=1099
## Strictly speaking you shouldn't need --exec to use this in most environments.
## If this isn't working, make sure you enable --exec as well
-Dcom.sun.management.jmxremote
....
===== Starting the Jetty Maven Plugin
If you are running the Jetty Maven Plugin, you must set the system property com.sun.management.jmxremote on Maven before running the plugin.
The way to do this is to set your MAVEN_OPTS environment variable (if you're not sure how to do this, consult the Maven documentation).
Here is an example that sets the system property on the fly in a BASH shell, before starting Jetty via the plugin:
....
$ export MAVEN_OPTS=-Dcom.sun.management.jmxremote
$ mvn jetty:run
$ jconsole & # runs jconsole in the background
....
===== Connecting to your server process
When you start Jetty, you see a dialog box from JConsole with a list of running processes to which you can connect. It should look something like so:
image:images/jconsole1.jpg[image,width=576]
____
[IMPORTANT]
If you don't see your Jetty process in the list of processes you can
connect to, quickly switch tabs, or close and reopen a new "New
Connection" dialog window. This forces JConsole to refresh the list, and
recognize your newly-started Jetty process.
____
Select the start.jar entry and click the "Connect" button.
A new JConsole window opens:
image:images/jconsole2.jpg[image,width=576]
From this window you can monitor memory usage, thread usage, classloading and VM statistics.
You can also perform operations such as a manual garbage collect.
JConsole is an extremely powerful and useful tool.
==== Managing Jetty Objects with JConsole
The MBean tab of JConsole allows access to managed objects within the Java application, including MBeans the JVM provides.
If you also want to interact with the Jetty JMX implementation via JConsole, you need to start Jetty JMX in a form that JConsole can access.
See xref:using-jmx[] for more information.

View File

@ -0,0 +1,138 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jetty-jmx-annotations]]
=== Jetty JMX Annotations
When the jetty-jmx libraries are present on startup and the wiring is enabled for exposing jetty mbeans to jmx, there are three annotations that govern when and how mbeans are created and exposed.
[[jmx-annotation-introspection]]
==== Annotation Introspection
When jmx is configured and enabled in jetty any time an object is registered with the Server it is introspected as a potential mbean to be exposed.
This introspection proceeds as follows assuming the class is named `com.acme.Foo`:
1. All influences for `com.acme.Foo` determined. These include each class in the chain of super classes, and by convention each of these classes following a form of `com.acme.jmx.FooMBean`.
All super classes and their corresponding MBean representations are then used in the next step.
2. Each potential influencing class is checked for the @ManagedObject annotation, should this annotation exist at any point in the chain of influencers then a mbean is created with the description of the version @ManageObject discovered.
3. Once an mbean has been created for an object then each potential influencing object is introspected for @ManagedAttribute and @ManagedOperation annotations and the corresponding type is exposed to the mbean.
The convention of looking for @ManageObject annotations on `.jmx.ClassMBean` allows for a normal POJO to be wrapped in an mbean without itself without requiring it being marked up with annotations.
Since the pojo is passed to these wrapped derived Mbean instances and is an internal variable then the MBean can be used to better expose a set of attributes and operations that may not have been anticipated when the original object was created.
[[jmx-managed-object]]
==== @ManagedObject
The @ManagedObject annotation is used on a class at the top level to indicate that it should be exposed as an mbean.
It has only one attribute to it which is used as the description of the MBean.
Should multiple @ManagedObject annotations be found in the chain of influence then the first description is used.
The list of attributes available are:
value::
The description of the Managed Object.
[[jmx-managed-attribute]]
==== @ManagedAttribute
The @ManagedAttribute annotation is used to indicate that a given method exposes a JMX attribute. This annotation is placed always on the reader method of a given attribute.
Unless it is marked as read-only in the configuration of the annotation a corresponding setter is looked for following normal naming conventions.
For example if this annotation is on a method called getFoo() then a method called setFoo() would be looked for and if found wired automatically into the jmx attribute.
The list of attributes available are:
value::
The description of the Managed Attribute.
name::
The name of the Managed Attribute.
proxied::
Value is true if the corresponding mbean for this object contains the method of this JMX attribute in question.
readonly::
By default this value is false which means that a corresponding setter will be looked for an wired into the attribute should one be found.
Setting this to true make the jmx attribute read only.
setter::
This attribute can be used when the corresponding setter for a JMX attribute follows a non-standard naming convention and it should still be exposed as the setter for the attribute.
[[jmx-managed-operation]]
==== @ManagedOperation
The @ManagedOperation annotation is used to indicate that a given method should be considered a JMX operation.
The list of attributes available are:
value::
The description of the Managed Operation.
impact::
The impact of an operation.
By default this value is "UNKNOWN" and acceptable values are "ACTION", "INFO", "ACTION_INFO" and should be used according to their definitions with JMX.
proxied::
Value is true if the corresponding mbean for this object contains the method of this JMX operation in question.
[[jmx-name-annotation]]
==== @Name
A fourth annotation is often used in conjunction with the JMX annotations mentioned above.
This annotation is used to describe variables in method signatures so that when rendered into tools like JConsole it is clear what the parameters are.
For example:
The list of attributes available are:
value::
The name of the parameter.
description::
The description of the parameter.
[[jmx-annotation-example]]
==== Example
The following is an example of each of the annotations mentioned above in practice.
[source,java]
----
package com.acme;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.annotation.Name;
@ManagedObject("Test MBean Annotations")
public class Derived extends Base implements Signature
{
String fname="Full Name";
@ManagedAttribute(value="The full name of something", name="fname")
public String getFullName()
{
return fname;
}
public void setFullName(String name)
{
fname=name;
}
@ManagedOperation("Doodle something")
public void doodle(@Name(value="doodle", description="A description of the argument") String doodle)
{
System.err.println("doodle "+doodle);
}
}
----

View File

@ -0,0 +1,198 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[using-jmx]]
=== Using Java Management Extensions (JMX)
The [http://java.sun.com/products/JavaManagement/[Java Management Extensions (JMX) API] is a standard API for managing and monitoring resources such as applications, devices, services, and the Java virtual machine.
Typical uses of the JMX technology include:
* Consulting and changing application configuration.
* Accumulating and making available statistics about application behavior.
* Notifying of state changes and erroneous conditions.
The JMX API includes remote access, so a remote management program can interact with a running application for these purposes.
Jetty JMX integration uses the platform MBean server implementation that Java VM provides.
The integration is based on the ObjectMBean implementation of DynamicMBean.
This implementation allows you to wrap an arbitrary POJO in an MBean and annotate it appropriately to expose it via JMX.
See xref:jetty-jmx-annotations[].
TheMBeanContainer implementation of the Container.Listener interface coordinates creation of MBeans.
The Jetty Server and it's components use a link:{JDURL}/org/eclipse/jetty/util/component/Container.html[Container] to maintain a containment tree of components and to support notification of changes to that tree.
The MBeanContainer class listens for Container events and creates and destroys MBeans as required to wrap all Jetty components.
You can access the MBeans that Jetty publishes both through built-in Java VM connector via JConsole, or by registering a remote JMX connector and using a remote JMX agent to monitor Jetty.
[[configuring-jmx]]
==== Configuring JMX
This guide describes how to initialize and configure the Jetty JMX integration.
To monitor an application using JMX, perform the following steps:
* Configure the application to instantiate an MBean container.
* Instrument objects to be MBeans.
* Provide access for JMX agents to MBeans.
[[accessing-jetty-mbeans]]
===== Using JConsole to Access Jetty MBeans
The simplest way to access the MBeans that Jetty publishes is to use the http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html[JConsole utility] the Java Virtual Machine supplies.
See xref:jetty-jconsole[] for instructions on how to configure JVM for use with JConsole.
To access Jetty MBeans via JConsole, you must:
* Enable the registration of Jetty MBeans into the platform MBeanServer.
* Enable a JMXConnectorServer so that JConsole can connect and visualize the MBeans.
[[registering-jetty-mbeans]]
===== Registering Jetty MBeans
Configuring Jetty JMX integration differs for standalone and embedded Jetty.
[[jmx-standalone-jetty]]
====== Standalone Jetty
JMX is enabled by default in the jetty-9 distribution.
If you are having difficulties validate that the section in the jetty.home/start.ini file is uncommented.
[[jmx-embedded-jetty]]
====== Embedded Jetty
When running Jetty embedded into an application, create and configure an MBeanContainer instance as follows:
[source,java]
----
Server server = new Server();
// Setup JMX
MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addEventListener(mbContainer);
server.addBean(mbContainer);
// Add loggers MBean to server (will be picked up by MBeanContainer above)
server.addBean(Log.getLog());
----
Notice that Jetty creates the MBeanContainer immediately after creating the Server, and immediately after registering it as an EventListener of the Server object (which is also a Container object).
Because logging is initialized prior to the MBeanContainer (even before the Server itself), it is necessary to register the logger manually via `server.addBean()` so that the loggers may show up in the JMX tree.
[[jmx-using-jetty-maven-plugin]]
===== Using the Jetty Maven Plugin with JMX
If you are using the link:#jetty-maven-plugin[jetty maven plugin] you should copy the `etc/jetty-jmx.xml` file into your webapp project somewhere, such as `src/etc,` then add a `<jettyconfig>` element to the plugin `<configuration>`:
[source,xml]
----
<plugin>
<groupid>org.eclipse.jetty</groupid>
<artifactid>jetty-maven-plugin</artifactid>
<version>@project.version@</version>
<configuration>
<scanintervalseconds>10</scanintervalseconds>
<jettyXml>src/etc/jetty-jmx.xml</jettyXml>
</configuration>
</plugin>
----
[[enabling-jmxconnectorserver-for-remote-access]]
==== Enabling JMXConnectorServer for Remote Access
There are two ways of enabling remote connectivity so that JConsole can connect to visualize MBeans.
* Use the `com.sun.management.jmxremote` system property on the command line.
Unfortunately, this solution does not play well with firewalls and it is not flexible.
* Use Jetty's `ConnectorServer` class.
To enable use of this class, uncomment the correspondent portion in `etc/jetty-jmx.xml,` like this:
[source,xml]
----
<New id="ConnectorServer" class="org.eclipse.jetty.jmx.ConnectorServer">
<Arg>
<New class="javax.management.remote.JMXServiceURL">
<Arg type="java.lang.String">rmi</Arg>
<Arg type="java.lang.String" />
<Arg type="java.lang.Integer"><SystemProperty name="jetty.jmxrmiport" default="1099"/></Arg>
<Arg type="java.lang.String">/jndi/rmi://<SystemProperty name="jetty.jmxrmihost" default="localhost"/>:<SystemProperty name="jetty.jmxrmiport" default="1099"/>/jmxrmi</Arg>
</New>
</Arg>
<Arg>org.eclipse.jetty.jmx:name=rmiconnectorserver</Arg>
<Call name="start" />
</New>
----
This configuration snippet starts an RMIRegistry and a JMXConnectorServer both on port 1099 (by default), so that firewalls should open just that one port to allow connections from JConsole.
[[securing-remote-access]]
==== Securing Remote Access
JMXConnectorServer several options to restrict access.
For a complete guide to controlling authentication and authorization in JMX, see https://blogs.oracle.com/lmalventosa/entry/jmx_authentication_authorization[Authentication and Authorization in JMX RMI connectors] in Luis-Miguel Alventosa's blog.
To restrict access to the JMXConnectorServer, you can use this configuration, where the `jmx.password` and `jmx.access` files have the format specified in the blog entry above:
[source,xml]
----
<New id="ConnectorServer" class="org.eclipse.jetty.jmx.ConnectorServer">
<Arg>
<New class="javax.management.remote.JMXServiceURL">
<Arg type="java.lang.String">rmi</Arg>
<Arg type="java.lang.String" />
<Arg type="java.lang.Integer"><SystemProperty name="jetty.jmxrmiport" default="1099"/></Arg>
<Arg type="java.lang.String">/jndi/rmi://<SystemProperty name="jetty.jmxrmihost" default="localhost"/>:<SystemProperty name="jetty.jmxrmiport" default="1099"/>/jmxrmi</Arg>
</New>
</Arg>
<Arg>
<Map>
<Entry>
<Item>jmx.remote.x.password.file</Item>
<Item>
<New class="java.lang.String"><Arg><Property name="jetty.home" default="." />/resources/jmx.password</Arg></New>
</Item>
</Entry>
<Entry>
<Item>jmx.remote.x.access.file</Item>
<Item>
<New class="java.lang.String"><Arg><Property name="jetty.home" default="." />/resources/jmx.access</Arg></New>
</Item>
</Entry>
</Map>
</Arg>
<Arg>org.eclipse.jetty.jmx:name=rmiconnectorserver</Arg>
<Call name="start" />
</New>
----
[[custom-monitor-applcation]]
==== Custom Monitor Application
Using the JMX API, you can also write a custom application to monitor your Jetty server.
To allow this application to connect to your Jetty server, you need to uncomment the last section of your `etc/jetty-jmx.xml` configuration file and optionally modify the endpoint name.
Doing so creates a JMX HTTP connector and registers a JMX URL that outputs to the `Stderr` log.
You should provide the URL that appears in the log to your monitor application in order to create an ` MBeanServerConnection.`
You can use the same URL to connect to your Jetty instance from a remote machine using JConsole.
See the link:{GITBROWSEURL}/jetty-jmx/src/main/config/etc/jetty-jmx.xml[configuration file] for more details.

View File

@ -0,0 +1,27 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jndi]]
== Configuring JNDI
Jetty supports `java:comp/env` lookups in webapps. This is an optional
feature for which you need to do some setup.
include::quick-jndi-setup.adoc[]
include::using-jndi.adoc[]
include::jndi-configuration.adoc[]
include::jndi-embedded.adoc[]
include::jndi-datasources.adoc[]

View File

@ -0,0 +1,382 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jndi-configuration]]
=== Configuring JNDI
[[configuring-jndi-env-entries]]
==== Configuring JNDI `env-entries`
Sometimes it is useful to pass configuration information to a webapp at
runtime that you either cannot or cannot conveniently code into a
`web.xml env-entry`. In such cases, you can use `org.eclipse.jetty.plus.jndi.EnvEntry`, and even override an entry of
the same name in ` web.xml`.
[source,xml]
----
<New class="org.eclipse.jetty.plus.jndi.EnvEntry">
<Arg></Arg>
<Arg>mySpecialValue</Arg>
<Arg type="java.lang.Integer">4000</Arg>
<Arg type="boolean">true</Arg>
</New>
----
This example defines a virtual `env-entry` called `mySpecialValue` with
value `4000` that is xref:jndi-name-scope[scoped] to the JVM. It is put
into JNDI at ` java:comp/env/mySpecialValue` for _every_ web app
deployed. Moreover, the boolean argument indicates that this value
overrides an `env-entry` of the same name in `web.xml`. If you don't
want to override, omit this argument, or set it to `false`.
The Servlet Specification allows binding only the following object types
to an `env-entry`:
* java.lang.String
* java.lang.Integer
* java.lang.Float
* java.lang.Double
* java.lang.Long
* java.lang.Short
* java.lang.Character
* java.lang.Byte
* java.lang.Boolean
That being said, Jetty is a little more flexible and allows you to also
bind custom POJOs,
http://docs.oracle.com/javase/1.5.0/docs/api/javax/naming/Reference.html[`javax.naming.References`]
and
http://docs.oracle.com/javase/1.5.0/docs/api/javax/naming/Referenceable.html[`javax.naming.Referenceables`].
Be aware that if you take advantage of this feature, your web
application is __not portable__.
To use the `env-entry` configured above, use code in your
`servlet/filter/etc.`, such as:
[source,java]
----
import javax.naming.InitialContext;
public class MyClass {
public void myMethod() {
InitialContext ic = new InitialContext();
Integer mySpecialValue = (Integer)ic.lookup("java:comp/env/mySpecialValue");
...
}
}
----
[[configuring-resource-refs-and-resource-env-refs]]
==== Configuring `resource-refs` and `resource-env-refs`
You can configure any type of resource that you want to refer to in a
`web.xml` file as a `resource-ref` or `resource-env-ref`, using the `
org.eclipse.jetty.plus.jndi.Resource` type of naming entry. You
provide the scope, the name of the object (relative to `java:comp/env`)
and a POJO instance or a `javax.naming.Reference` instance or
`javax.naming.Referenceable` instance.
The http://jcp.org/aboutJava/communityprocess/pr/jsr244/index.html[J2EE
Specification] recommends storing DataSources in `java:comp/env/jdbc`,
JMS connection factories under `java:comp/env/jms`, JavaMail connection
factories under `
java:comp/env/mail` and URL connection factories under
`java:comp/env/url`. For example:
.DataSource Declaration Conventions
[cols=",,",options="header",]
|=======================================================================
|Resource Type |Name in `jetty.xml` |Environment Lookup
|javax.sql.DataSource |jdbc/myDB |java:comp/env/jdbc/myDB
|javax.jms.QueueConnectionFactory |jms/myQueue
|java:comp/env/jms/myQueue
|javax.mail.Session |mail/myMailService
|java:comp/env/mail/myMailService
|=======================================================================
[[configuring-datasources]]
==== Configuring DataSources
Here is an example of configuring a `javax.sql.DataSource`. Jetty can
use any DataSource implementation available on its classpath. In this
example, the DataSource is from the http://db.apache.org/derby[Derby]
relational database, but you can use any implementation of a
`javax.sql.DataSource`. This example configures it as scoped to a web
app with the id of __wac__:
[source,xml]
----
<Configure id='wac' class="org.eclipse.jetty.webapp.WebAppContext">
<New id="myds" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref refid="wac"/></Arg>
<Arg>jdbc/myds</Arg>
<Arg>
<New class="org.apache.derby.jdbc.EmbeddedDataSource">
<Set name="DatabaseName">test</Set>
<Set name="createDatabase">create</Set>
</New>
</Arg>
</New>
</Configure>
----
The code above creates an instance of
`org.apache.derby.jdbc.EmbeddedDataSource`, calls the two setter methods
`setDatabaseName("test"),` and `setCreateDatabase("create"),` and binds
it into the JNDI scope for the web app. If you do not have the
appropriate `resource-ref` set up in your `web.xml`, it is available
from application lookups as `
java:comp/env/jdbc/myds`.
Here's an example `web.xml` declaration for the datasource above:
[source,xml]
----
<resource-ref>
<res-ref-name>jdbc/myds</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
----
To look up your DataSource in your `servlet/filter/etc.`:
[source,java]
----
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class MyClass {
public void myMethod() {
InitialContext ic = new InitialContext();
DataSource myDS = (DataSource)ic.lookup("java:comp/env/jdbc/myds");
...
}
}
----
____
[NOTE]
Careful! When configuring Resources, ensure that the type of object you configure matches the type of object you expect to look up in `java:comp/env`.
For database connection factories, this means that the object you register as a Resource _must_ implement the `javax.sql.DataSource` interface.
____
For more examples of datasource configurations, see
xref:jndi-datasource-examples[].
[[configuring-jms-queues-topics-connectionfactories]]
==== Configuring JMS Queues, Topics and ConnectionFactories
Jetty can bind any implementation of the JMS destinations and connection
factories. You just need to ensure the implementation Jars are available
on Jetty's classpath. Here is an example of binding an
http://activemq.apache.org[ActiveMQ] in-JVM connection factory:
[source,xml]
----
<Configure id='wac' class="org.eclipse.jetty.webapp.WebAppContext">
<New id="cf" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref refid='wac'/></Arg>
<Arg>jms/connectionFactory</Arg>
<Arg>
<New class="org.apache.activemq.ActiveMQConnectionFactory">
<Arg>vm://localhost?broker.persistent=false</Arg>
</New>
</Arg>
</New>
</Configure>
----
The entry in `web.xml` would be:
[source,xml]
----
<resource-ref>
<res-ref-name>jms/connectionFactory</res-ref-name>
<res-type>javax.jms.ConnectionFactory</res-type>
<res-auth>Container</res-auth>
</resource-ref>
----
TODO: put in an example of a QUEUE from progress demo
[[configuring-mail-with-jndi]]
==== Configuring Mail
Jetty also provides infrastructure for access to `javax.mail.Sessions`
from within an application:
[source,xml]
----
<Configure id='wac' class="org.eclipse.jetty.webapp.WebAppContext">
<New id="mail" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref refid="wac"/></Arg>
<Arg>mail/Session</Arg>
<Arg>
<New class="org.eclipse.jetty.jndi.factories.MailSessionReference">
<Set name="user">fred</Set>
<Set name="password">OBF:1xmk1w261z0f1w1c1xmq</Set>
<Set name="properties">
<New class="java.util.Properties">
<Put name="mail.smtp.host">XXX</Put>
<Put name="mail.from">me@me</Put>
<Put name="mail.debug">true</Put>
</New>
</Set>
</New>
</Arg>
</New>
</Configure>
----
This setup creates an instance of the `
org.eclipse.jetty.jndi.factories.MailSessionReference` class, calls
its setter methods to set up the authentication for the mail system, and
populates a set of Properties, setting them on the `
MailSessionReference` instance. The result is that an application
can look up ` java:comp/env/mail/Session`  at runtime and obtain access
to a `javax.mail.Session`  that has the necessary configuration to
permit it to send email via SMTP.
____
[TIP]
You can set the password to be plain text, or use Jetty's link:#configuring-security-secure-passwords[Secure Password Obfuscation] (OBF:) mechanism to make the config file a little more secure from prying eyes.
Remember that you cannot use the other Jetty encryption mechanisms of MD5 and Crypt because they do not allow you to recover the original password, which the mail system requires.
____
[[configuring-xa-transactions]]
==== Configuring XA Transactions
If you want to perform distributed transactions with your resources, you
need a _transaction manager_ that supports the JTA interfaces, and that
you can look up as `java:comp/UserTransaction` in your webapp. Jetty
does not ship with one as standard, but you can plug in the one you
prefer. You can configure a transaction manager using the
link:{JDURL}/org/eclipse/jetty/plus/jndi/Transaction.html[JNDI
Transaction] object in a Jetty config file. The following example
configures the http://www.atomikos.com/[Atomikos] transaction manager:
[source,xml]
----
<New id="tx" class="org.eclipse.jetty.plus.jndi.Transaction">
<Arg>
<New class="com.atomikos.icatch.jta.J2eeUserTransaction"/>
</Arg>
</New>
----
[[configuring-links]]
==== Configuring Links
Generally, the name you set for your `Resource` should be the same name
you use for it in `web.xml`. For example:
In a context xml file:
[source,xml]
----
<Configure id='wac' class="org.eclipse.jetty.webapp.WebAppContext">
<New id="myds" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref refid="wac"/></Arg>
<Arg>jdbc/mydatasource</Arg>
<Arg>
<New class="org.apache.derby.jdbc.EmbeddedDataSource">
<Set name="DatabaseName">test</Set>
<Set name="createDatabase">create</Set>
</New>
</Arg>
</New>
</Configure>
----
In `web.xml`:
[source,xml]
----
<resource-ref>
<res-ref-name>jdbc/mydatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<injection-target>
<injection-target-class>com.acme.JNDITest</injection-target-class>
<injection-target-name>myDatasource</injection-target-name>
</injection-target>
</resource-ref>
----
However, you can refer to it in `web.xml` by a different name, and link
it to the name in your `
org.eclipse.jetty.plus.jndi.Resource` by using an
`org.eclipse.jetty.plus.jndi.Link`. For the example above, you can refer
to the `jdbc/mydatasource` resource as `
jdbc/mydatasource1` as follows:
In a context xml file declare `jdbc/mydatasource`:
[source,xml]
----
<Configure id='wac' class="org.eclipse.jetty.webapp.WebAppContext">
<New id="myds" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref refid="wac"/></Arg>
<Arg>jdbc/mydatasource</Arg>
<Arg>
<New class="org.apache.derby.jdbc.EmbeddedDataSource">
<Set name="DatabaseName">test</Set>
<Set name="createDatabase">create</Set>
</New>
</Arg>
</New>
</Configure>
----
Then in a `WEB-INF/jetty-env.xml` file, link the name
`jdbc/mydatasource` to the name you want to reference it as in
`web.xml`, which in this case is `jdbc/mydatasource1`:
[source,xml]
----
<New id="map1" class="org.eclipse.jetty.plus.jndi.Link">
<Arg><Ref refid='wac'/></Arg>
<Arg>jdbc/mydatasource1</Arg> <!-- name in web.xml -->
<Arg>jdbc/mydatasource</Arg> <!-- name in container environment -->
</New>
----
Now you can refer to `jdbc/mydatasource1` in the `web.xml` like this:
[source,xml]
----
<resource-ref>
<res-ref-name>jdbc/mydatasource1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<injection-target>
<injection-target-class>com.acme.JNDITest</injection-target-class>
<injection-target-name>myDatasource</injection-target-name>
</injection-target>
</resource-ref>
----
This can be useful when you cannot change a JNDI resource directly in
the `web.xml` but need to link it to a specific resource in your
deployment environment.

View File

@ -0,0 +1,447 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jndi-datasource-examples]]
=== Datasource Examples
Here are examples of configuring a JNDI datasource for various
databases.
____
[NOTE]
Read xref:configuring-datasources[] in xref:jndi-configuration[] for more information about configuring datasources.
____
All of these examples correspond to a `resource-ref` in `web.xml`.
[source,xml]
----
<resource-ref>
<description>My DataSource Reference</description>
<res-ref-name>jdbc/DSTest</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
----
These examples assume that all of the datasources are declared at the
JVM scope, but you can use other scopes if desired. You can configure
all JNDI resources in a `jetty.xml` file or in a `
WEB-INF/jetty-env.xml` file, or a context XML file. See the section
xref:jndi-where-to-declare[] for more information.
____
[IMPORTANT]
You must provide Jetty with the libraries necessary to instantiate the datasource you have configured by putting the corresponding Jar in `JETTY_HOME/lib/ext`.
____
[[pooling-datasources]]
==== Pooling DataSources
Pooling datasources enables connection pooling, which lets you reuse an
existing connection instead of creating a new connection to the
database. This is highly efficient in terms of memory allocation and
speed of the request to the database. We highly recommend this option
for production environments.
The following is a list of the pooled datasource examples we have worked
with in the past:
* xref:hikaricp-datasource[]
* xref:bonecp-datasource[]
* xref:c3p0-datasource[]
* xref:dbcp-datasource[]
* xref:atomikos-datasource[]
* xref:mysql-pooled-datasource[]
* xref:postgreSQL-pooled-datasource[]
* xref:DB2-pooled-datasource[]
[[hikaricp-datasource]]
===== HikariCP
Connection pooling, available at
http://search.maven.org/remotecontent?filepath=com/zaxxer/HikariCP/1.4.0/HikariCP-1.4.0.jar[HikariCP
Download]. All configuration options for HikariCP are described here:
https://github.com/brettwooldridge/HikariCP[HikariCP documentation].
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.zaxxer.hikari.HikariDataSource">
<Arg>
<New class="com.zaxxer.hikari.HikariConfig">
<Set name="minimumPoolSize">5</Set>
<Set name="maximumPoolSize">20</Set>
<Set name="dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</Set>
<Set name="username">jdbc.user</Set>
<Set name="password">jdbc.pass</Set>
<Call name="addDataSourceProperty">
<Arg>url</Arg>
<Arg>jdbc.url</Arg>
</Call>
</New>
</Arg>
</New>
</Arg>
</New>
----
[[bonecp-datasource]]
===== BoneCP
Connection pooling, available at
http://jolbox.com/index.html?page=http://jolbox.com/download.html[BoneCP
Download]. All configuration options for BoneCP are described here:
http://jolbox.com/bonecp/downloads/site/apidocs/com/jolbox/bonecp/BoneCPDataSource.html[BoneCP
API].
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.jolbox.bonecp.BoneCPDataSource">
<Set name="driverClass">com.mysql.jdbc.Driver</Set>
<Set name="jdbcUrl">jdbc.url</Set>
<Set name="username">jdbc.user</Set>
<Set name="password">jdbc.pass</Set>
<Set name="minConnectionsPerPartition">5</Set>
<Set name="maxConnectionsPerPartition">50</Set>
<Set name="acquireIncrement">5</Set>
<Set name="idleConnectionTestPeriod">30</Set>
</New>
</Arg>
</New>
----
[[c3p0-datasource]]
===== c3p0
Connection pooling, available at
http://central.maven.org/maven2/c3p0/c3p0/0.9.1.2/c3p0-0.9.1.2.jar[c3p0
Jar].
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.mchange.v2.c3p0.ComboPooledDataSource">
<Set name="driverClass">org.some.Driver</Set>
<Set name="jdbcUrl">jdbc.url</Set>
<Set name="user">jdbc.user</Set>
<Set name="password">jdbc.pass</Set>
</New>
</Arg>
</New>
----
[[dbcp-datasource]]
===== DBCP
Connection pooling, available at
http://central.maven.org/maven2/commons-dbcp/commons-dbcp/1.2/commons-dbcp-1.2.jar[dbcp
Jar].
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="org.apache.commons.dbcp.BasicDataSource">
<Set name="driverClassName">org.some.Driver</Set>
<Set name="url">jdbc.url</Set>
<Set name="username">jdbc.user</Set>
<Set name="password">jdbc.pass</Set>
</New>
</New>
</Arg>
</New>
----
[[atomikos-datasource]]
===== Atomikos 3.3.2+
Connection pooling + XA transactions.
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.atomikos.jdbc.AtomikosDataSourceBean">
<Set name="minPoolSize">2</Set>
<Set name="maxPoolSize">50</Set>
<Set name="xaDataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</Set>
<Set name="UniqueResourceName">DSTest</Set>
<Get name="xaProperties">
<Call name="setProperty">
<Arg>url</Arg>
<Arg>jdbc:mysql://localhost:3306/databasename</Arg>
</Call>
<Call name="setProperty">
<Arg>user</Arg>
<Arg>some_username</Arg>
</Call>
<Call name="setProperty">
<Arg>password</Arg>
<Arg>some_password</Arg>
</Call>
</Get>
</New>
</Arg>
</New>
----
[[mysql-pooled-datasource]]
===== MySQL
Implements `javax.sql.DataSource,
javax.sql.ConnectionPoolDataSource.`
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
<Set name="Url">jdbc:mysql://localhost:3306/databasename</Set>
<Set name="User">user</Set>
<Set name="Password">pass</Set>
</New>
</Arg>
</New>
----
[[postgreSQL-pooled-datasource]]
===== PostgreSQL
Implements `javax.sql.ConnectionPoolDataSource`
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="org.postgresql.ds.PGConnectionPoolDataSource">
<Set name="User">user</Set>
<Set name="Password">pass</Set>
<Set name="DatabaseName">dbname</Set>
<Set name="ServerName">localhost</Set>
<Set name="PortNumber">5432</Set>
</New>
</Arg>
</New>
----
[[DB2-pooled-datasource]]
===== DB2
Implements `javax.sql.ConnectionPoolDataSource`
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.ibm.db2.jcc.DB2ConnectionPoolDataSource">
<Set name="DatabaseName">dbname</Set>
<Set name="User">user</Set>
<Set name="Password">pass</Set>
<Set name="ServerName">servername</Set>
<Set name="PortNumber">50000</Set>
</New>
</Arg>
</New>
----
[[non-pooling-datasources]]
==== Non-pooling DataSources
If you are deploying in a production environment, we highly recommend
using a Pooling DataSource. Since that is not always an option we have a
handful of examples for non-pooling datasources listed here as well.
The following is a list of the non-pooled datasource examples:
* xref:sql-server-2000-datasource[]
* xref:oracle-9i10g-datasource[]
* xref:postgreSQL-datasource[]
* xref:sybase-datasource[]
* xref:DB2-datasource[]
[[sql-server-2000-datasource]]
===== SQL Server 2000
Implements `javax.sql.DataSource,
javax.sql.ConnectionPoolDataSource.`
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="net.sourceforge.jtds.jdbcx.JtdsDataSource">
<Set name="User">user</Set>
<Set name="Password">pass</Set>
<Set name="DatabaseName">dbname</Set>
<Set name="ServerName">localhost</Set>
<Set name="PortNumber">1433</Set>
</New>
</Arg>
</New>
----
[[oracle-9i10g-datasource]]
===== Oracle 9i/10g
Implements `javax.sql.DataSource,
javax.sql.ConnectionPoolDataSource.`
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="oracle.jdbc.pool.OracleDataSource">
<Set name="DriverType">thin</Set>
<Set name="URL">jdbc:oracle:thin:@fmsswdb1:10017:otcd</Set>
<Set name="User">xxxx</Set>
<Set name="Password">xxxx</Set>
<Set name="connectionCachingEnabled">true</Set>
<Set name="connectionCacheProperties">
<New class="java.util.Properties">
<Call name="setProperty">
<Arg>MinLimit</Arg>
<Arg>5</Arg>
</Call>
<!-- put the other properties in here too -->
</New>
</Set>
</New>
</Arg>
</New>
----
For more information, refer to:
http://docs.oracle.com/cd/B14117_01/java.101/b10979/conncache.htm[Oracle
Database JDBC documentation].
[[postgreSQL-datasource]]
===== PostgreSQL
Implements `javax.sql.DataSource.`
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="org.postgresql.ds.PGSimpleDataSource">
<Set name="User">user</Set>
<Set name="Password">pass</Set>
<Set name="DatabaseName">dbname</Set>
<Set name="ServerName">localhost</Set>
<Set name="PortNumber">5432</Set>
</New>
</Arg>
</New>
----
[[sybase-datasource]]
===== Sybase
Implements `javax.sql.DataSource.`
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.sybase.jdbc2.jdbc.SybDataSource">
<Set name="DatabaseName">dbname</Set>
<Set name="User">user</Set>
<Set name="Password">pass</Set>
<Set name="ServerName">servername</Set>
<Set name="PortNumber">5000</Set>
</New>
</Arg>
</New>
----
[[DB2-datasource]]
===== DB2
Implements `javax.sql.DataSource.`
[source,xml]
----
<New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg>
<Arg>jdbc/DSTest</Arg>
<Arg>
<New class="com.ibm.db2.jcc.DB2SimpleDataSource">
<Set name="DatabaseName">dbname</Set>
<Set name="User">user</Set>
<Set name="Password">pass</Set>
<Set name="ServerName">servername</Set>
<Set name="PortNumber">50000</Set>
</New>
</Arg>
</New>
----

View File

@ -0,0 +1,146 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jndi-embedded]]
=== Using JNDI with Jetty Embedded
==== Setting up the Classpath
In addition to the jars that you require for your application, and the
jars needed for core Jetty, you will need to place the following jars
onto your classpath:
....
jetty-jndi.jar
jetty-plus.jar
....
If you are using transactions, you will also need the javax.transaction
api. You can
http://download.eclipse.org/jetty/orbit/javax.transaction_1.1.1.v201004190952.jar/dist/[obtain
this jar] from http://download.eclipse.org/jetty/orbit[the Jetty
dependencies site.]
If you wish to use mail, you will also need the javax.mail api and
implementation. You can
http://download.eclipse.org/jetty/orbit/javax.mail.glassfish_1.4.1.v201005082020.jar/dist/[obtain
this jar] from
thehttp://download.eclipse.org/jetty/orbit/javax.mail.glassfish_1.4.1.v201005082020.jar/dist/[Jetty
dependencies site]. Note that this jar also requires the
javax.activation classes, which you can also
http://download.eclipse.org/jetty/orbit/javax.activation_1.1.0.v201105071233.jar/dist/[obtain]
from the http://download.eclipse.org/jetty/orbit/[Jetty dependencies
site].
==== Example Code
Here is an example class that sets up some JNDI entries and deploys a
webapp that references these JNDI entries in code. We'll use some mocked
up classes for the transaction manager and the DataSource in this
example for simplicity:
[source,java]
----
import java.util.Properties;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* ServerWithJNDI
*
*
*/
public class ServerWithJNDI
{
public static void main(String[] args) throws Exception
{
//Create the server
Server server = new Server(8080);
//Enable parsing of jndi-related parts of web.xml and jetty-env.xml
org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
classlist.addAfter("org.eclipse.jetty.webapp.FragmentConfiguration", "org.eclipse.jetty.plus.webapp.EnvConfiguration", "org.eclipse.jetty.plus.webapp.PlusConfiguration");
//Create a WebApp
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar("./my-foo-webapp.war");
server.setHandler(webapp);
//Register new transaction manager in JNDI
//At runtime, the webapp accesses this as java:comp/UserTransaction
org.eclipse.jetty.plus.jndi.Transaction transactionMgr = new org.eclipse.jetty.plus.jndi.Transaction(new com.acme.MockUserTransaction());
//Define an env entry with Server scope.
//At runtime, the webapp accesses this as java:comp/env/woggle
//This is equivalent to putting an env-entry in web.xml:
//<env-entry>
// <env-entry-name>woggle</env-entry-name>
// <env-entry-type>java.lang.Integer</env-entry-type>
// <env-entry-value>4000</env-entry-value>
//</env-entry>
org.eclipse.jetty.plus.jndi.EnvEntry woggle = new org.eclipse.jetty.plus.jndi.EnvEntry(server, "woggle", new Integer(4000), false);
//Define an env entry with webapp scope.
//At runtime, the webapp accesses this as java:comp/env/wiggle
//This is equivalent to putting a web.xml entry in web.xml:
//<env-entry>
// <env-entry-name>wiggle</env-entry-name>
// <env-entry-value>100</env-entry-value>
// <env-entry-type>java.lang.Double</env-entry-type>
//</env-entry>
//Note that the last arg of "true" means that this definition for "wiggle" would override an entry of the
//same name in web.xml
org.eclipse.jetty.plus.jndi.EnvEntry wiggle = new org.eclipse.jetty.plus.jndi.EnvEntry(webapp, "wiggle", new Double(100), true);
//Register a reference to a mail service scoped to the webapp.
//This must be linked to the webapp by an entry in web.xml:
// <resource-ref>
// <res-ref-name>mail/Session</res-ref-name>
// <res-type>javax.mail.Session</res-type>
// <res-auth>Container</res-auth>
// </resource-ref>
//At runtime the webapp accesses this as java:comp/env/mail/Session
org.eclipse.jetty.jndi.factories.MailSessionReference mailref = new org.eclipse.jetty.jndi.factories.MailSessionReference();
mailref.setUser("CHANGE-ME");
mailref.setPassword("CHANGE-ME");
Properties props = new Properties();
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.host","CHANGE-ME");
props.put("mail.from","CHANGE-ME");
props.put("mail.debug", "false");
mailref.setProperties(props);
org.eclipse.jetty.plus.jndi.Resource xxxmail = new org.eclipse.jetty.plus.jndi.Resource(webapp, "mail/Session", mailref);
// Register a mock DataSource scoped to the webapp
//This must be linked to the webapp via an entry in web.xml:
//<resource-ref>
// <res-ref-name>jdbc/mydatasource</res-ref-name>
// <res-type>javax.sql.DataSource</res-type>
// <res-auth>Container</res-auth>
//</resource-ref>
//At runtime the webapp accesses this as java:comp/env/jdbc/mydatasource
org.eclipse.jetty.plus.jndi.Resource mydatasource = new org.eclipse.jetty.plus.jndi.Resource(webapp, "jdbc/mydatasource",
new com.acme.MockDataSource());
server.start();
server.join();
}
}
----

View File

@ -0,0 +1,56 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jndi-quick-setup]]
=== Quick Setup
If you are using the standard distribution of Jetty, you must enable the
*jndi* link:#startup-modules[module] to obtain jetty's jndi
implementation, and the *plus* link:#startup-modules[module] which
provides classes for interacting with jndi. As the *plus* module depends
on the *jndi* module, you only need to enable the *plus* module to
enable both. Assuming you have jetty
link:#startup-base-and-home[installed] in /opt/jetty, and you have made
a link:#startup-base-and-home[jetty base] in /opt/jetty/my-base, do:
[source,bash]
----
cd /opt/jetty
cd my-base
java -jar $JETTY_HOME/start.jar --add-to-startd=plus
----
You can now start Jetty and use JNDI within your webapps. See
link:#using-jndi[Using JNDI] for information on how to add entries to
the JNDI environment that Jetty can look up within webapps.
If you have extra jars associated with your jndi resources, for example
a database driver jar, and you haven't made a custom
link:#startup-modules[module] for it, you can put the jars into your
link:#startup-base-and-home[jetty base] `ext/` directory. You will then
need to enable the *ext* module to ensure the jars in the `ext/`
directory are on the classpath. Assuming you have jetty
link:#startup-base-and-home[installed] in /opt/jetty, and you have made
a link:#startup-base-and-home[jetty base] in /opt/jetty/my-base, do:
[source,bash]
----
cd /opt/jetty
cd my-base
java -jar $JETTY_HOME/start.jar --add-to-startd=ext
----

View File

@ -0,0 +1,195 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[using-jetty-jndi]]
=== Working with Jetty JNDI
==== Defining the web.xml
You can configure naming resources to reference in a `web.xml` file and
access from within the `java:comp/env` naming environment of the webapp
during execution. Specifically, you can configure support for the
following `web.xml` elements:
[source,xml]
----
<env-entry/>
<resource-ref/>
<resource-env-ref/>
----
link:#configuring-jndi-env-entries[Configuring env-entries] shows you
how to set up overrides for `
env-entry` elements in `web.xml`, while
link:#configuring-resource-refs-and-resource-env-refs[Configuring
`resource-refs` and `resource-env-refs`] discusses how to configure
support resources such as `javax.sql.DataSource`.
You can also plug a JTA `javax.transaction.UserTransaction`
implementation into Jetty so that webapps can look up
`java:comp/UserTransaction` to obtain a distributed transaction manager:
see link:#configuring-xa-transactions[Configuring XA Transactions].
[[defining-jndi-naming-entries]]
==== Declaring Resources
You must declare the objects you want bound into the Jetty environment
so that you can then hook into your webapp via `env-entry,
resource-ref` and `resource-env-refs` in `web.xml`. You create
these bindings by using declarations of the following types:
`org.eclipse.jetty.plus.jndi.EnvEntry`::
for `env-entry` type of entries
`org.eclipse.jetty.plus.jndi.Resource`::
for all other type of resources
`org.eclipse.jetty.plus.jndi.Transaction`::
for a JTA manager
`org.eclipse.jetty.plus.jndi.Link`::
for link between a `web.xml` resource name and a naming entry
Declarations of each of these types follow the same general pattern:
[source,xml]
----
<New class="org.eclipse.jetty.plus.jndi.xxxx">
<Arg><!-- scope --></Arg>
<Arg><!-- name --></Arg>
<Arg><!-- value --></Arg>
</New>
----
You can place these declarations into three different files, depending
on your needs and the link:#jndi-name-scope[scope] of the resources
being declared.
[[jndi-where-to-declare]]
==== Deciding Where to Declare Resources
You can define naming resources in three places:
jetty.xml::
Naming resources defined in a `jetty.xml` file are
link:#jndi-name-scope[scoped] at either the JVM level or the Server
level. The classes for the resource must be visible at the Jetty
container level. If the classes for the resource only exist inside
your webapp, you must declare it in a `WEB-INF/jetty-env.xml` file.
WEB-INF/jetty-env.xml::
Naming resources in a `WEB-INF/jetty-env.xml` file are
link:#jndi-name-scope[scoped] to the web app in which the file
resides. While you can enter JVM or Server scopes if you choose, we do
not recommend doing so. The resources defined here may use classes
from inside your webapp. This is a Jetty-specific mechanism.
context xml file::
Entries in a context xml file should be link:#jndi-name-scope[scoped]
at the level of the webapp to which they apply, although you can
supply a less strict scoping level of Server or JVM if you choose. As
with resources declared in a `jetty.xml` file, classes associated with
the resource must be visible on the container's classpath.
[[jndi-name-scope]]
==== Scope of Resource Names
Naming resources within Jetty belong to one of three different scopes,
in increasing order of restrictiveness:
JVM scope::
The name is unique across the JVM instance, and is visible to all
application code. You represent this scope by a `null` first parameter
to the resource declaration. For example:
+
[source,xml]
----
<New id="cf" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg></Arg> <!-- empty arg -->
<Arg>jms/connectionFactory</Arg>
<Arg>
<New class="org.apache.activemq.ActiveMQConnectionFactory">
<Arg>vm://localhost?broker.persistent=false</Arg>
</New>
</Arg>
</New>
----
Server scope::
The name is unique to a Server instance, and is only visible to code
associated with that instance. You represent this scope by referencing
the Server instance as the first parameter to the resource
declaration. For example:
+
[source,xml]
----
<Configure id="Server" class="org.eclipse.jetty.Server">
<New id="cf" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref refid="Server"/></Arg> <!-- reference to Server instance -->
<Arg>jms/connectionFactory</Arg>
<Arg>
<New class="org.apache.activemq.ActiveMQConnectionFactory">
<Arg>vm://localhost?broker.persistent=false</Arg>
</New>
</Arg>
</New>
</Configure>
----
Webapp scope::
The name is unique to the WebAppContext instance, and is only visible
to code associated with that instance. You represent this scope by
referencing the WebAppContext instance as the first parameter to the
resource declaration. For example:
+
[source,xml]
----
<Configure id='wac' class="org.eclipse.jetty.webapp.WebAppContext">
<New id="cf" class="org.eclipse.jetty.plus.jndi.Resource">
<Arg><Ref refid='wac'/></Arg> <!-- reference to WebAppContext -->
<Arg>jms/connectionFactory</Arg>
<Arg>
<New class="org.apache.activemq.ActiveMQConnectionFactory">
<Arg>vm://localhost?broker.persistent=false</Arg>
</New>
</Arg>
</New>
</Configure>
----
[[binding-objects-into-jetty-jndi]]
==== What Can Be Bound as a Resource?
You can bind four types of objects into a Jetty JNDI reference:
* An ordinary POJO instance.
* A
http://docs.oracle.com/javase/1.5.0/docs/api/javax/naming/Reference.html[javax.naming.Reference]
instance.
* An object instance that implements the
http://docs.oracle.com/javase/1.5.0/docs/api/javax/naming/Referenceable.html[javax.naming.Referenceable]
interface.
* A link between a name as referenced in `web.xml` and as referenced in
the Jetty environment.

View File

@ -0,0 +1,21 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[configuring-logging]]
== Jetty Logging
This chapter discusses various options for configuring logging.

View File

@ -0,0 +1,99 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[configuring-jetty-logging]]
= Configuring Jetty Logging
Jetty provides logging via its own `org.eclipse.jetty.util.log.Logger`
layer, and does not natively use any existing Java logging framework.
All logging events, produced via the Jetty logging layer, have a name, a
level, and a message. The name is a FQCN (fully qualified class name)
similar to how all existing Java logging frameworks operate.
Jetty logging, however, has a slightly different set of levels that it
uses internally:
WARN::
For events serious enough to inform and log, but not fatal.
INFO::
Informational events.
DEBUG::
Debugging events (very noisy).
IGNORE::
Exception events that you can safely ignore, but useful for some
people. You might see this level as DEBUG under some Java logging
framework configurations, where it retains the _ignore_ phrase
somewhere in the logging.
____
[NOTE]
Jetty logging produces no FATAL or SEVERE events.
____
[[selecting-log-framework]]
== Selecting the Log Framework
Configure the Jetty logging layer via the
`org.eclipse.jetty.util.log.Log` class, following
link:{GITBROWSEURL}/jetty-util/src/main/java/org/eclipse/jetty/util/log/Log.java[these
rules].
1. Load Properties
* First from a Classpath Resource called `jetty-logging.properties` (if
found).
* Then from the `System.getProperties()`.
2. Determine the log implementation.
* If property `org.eclipse.jetty.util.log.class` is defined, load the
class it defines as the logger implementation from the server classpath.
* If the class `org.slf4j.Logger` exists in server classpath, the Jetty
implementation becomes `org.eclipse.jetty.util.log.Slf4jLog`.
* If no logger implementation is specified, default to
`org.eclipse.jetty.util.log.StdErrLog`.
____
[NOTE]
You can create your own custom logging by providing an implementation of
the link:{JDURL}org/eclipse/jetty/util/log/Logger.html[Jetty Logger
API]. For an example of a custom logger, see
link:{GITBROWSEURL}/jetty-util/src/main/java/org/eclipse/jetty/util/log/JavaUtilLog.java[JavaUtilLog.java].
____
[[configuring-jetty-stderrlog]]
== The jetty-logging.properties file
By default, the internal Jetty Logging discovery mechanism will load
logging specific properties from a classpath resource called
`jetty-logging.properties` and then initialize the Logging from a
combination of properties found in that file, along with any System
Properties.
A typical jetty-logging.properties file will include at least the
declaration of which logging implementation you want to use by defining
a value for the `org.eclipse.jetty.util.log.class` property.
Examples for various logging frameworks can be found later in this
documentation.
* Default Logging with link:#default-logging-with-stderrlog[Jetty's
StdErrLog]
* Using link:#example-logging-log4j[Log4j via Slf4jLog]
* Using link:#example-logging-logback[Logback via Slf4jLog]
* Using java.util.logging via Slf4jLog
* Using java.util.logging via Jetty's JavaUtilLog
* Capturing link:#example-slf4j-multiple-loggers[Multiple Logging
Frameworks via Slf4jLog]
* link:#example-logging-logback-centralized[Centralized Logging with
Logback and Sfl4jLog]

View File

@ -0,0 +1,123 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[configuring-jetty-request-logs]]
= Configuring Jetty Request Logs
Request logs are a record of the requests that the server has processed.
There is one entry per request received, and commonly in the standard
NCSA format, so you can use tools like
http://en.wikipedia.org/wiki/Webalizer[Webalizer] to analyze them
conveniently.
[[constructing-request-log-entry]]
== Constructing a Request Log Entry
A standard request log entry includes the client IP address, date,
method, URL, result, size, referrer, and user agent, for example:
....
123.4.5.6 - - [27/Aug/2004:10:16:17 +0000]
"GET /jetty/tut/XmlConfiguration.html HTTP/1.1"
200 76793 "http://localhost:8080/jetty/tut/logging.html"
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.6) Gecko/20040614 Firefox/0.8"
....
[[implementing-request-log]]
== Implementing a Request Log
Jetty provides an implementation called _`NCSARequestLog`_ which
supports the NCSA format in files that you can roll over on a daily
basis.
The http://logback.qos.ch/[Logback Project] offers
http://logback.qos.ch/access.html[another implementation] of a
RequestLog interface, providing rich and powerful HTTP-access log
functionality.
If neither of these options meets your needs, you can implement a custom
request logger by implementing Jetty's
link:{JDURL}/org/eclipse/jetty/server/RequestLog.html[`RequestLog.java`]
interface and plugging it in similar to the NCSARequestLog, as shown
below.
[[configuring-request-log]]
== Configuring a Request Log
To configure a single request log for the entire Jetty Server instance:
[source,xml]
----
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<Set name="RequestLog">
<New id="RequestLog" class="org.eclipse.jetty.server.AsyncNCSARequestLog">
<Set name="filename">/var/log/jetty/yyyy_mm_dd.request.log</Set>
<Set name="append">true</Set>
<Set name="extended">false</Set>
<Set name="LogTimeZone">GMT</Set>
</New>
</Set>
</Configure>
----
The equivalent code is:
[source,java]
----
NCSARequestLog requestLog = new NCSARequestLog("/var/logs/jetty/jetty-yyyy_mm_dd.request.log");
requestLog.setAppend(true);
requestLog.setExtended(false);
requestLog.setLogTimeZone("GMT");
server.setRequestLog(requestLog);
----
This configures a request log in `$JETTY_HOME/logs` with filenames
including the date. Old log files are kept for 90 days before being
deleted. Existing log files are appended to and the extended NCSA format
is used in the GMT timezone.
To examine many more configuration options, see
link:{JDURL}/org/eclipse/jetty/server/NCSARequestLog.html[NCSARequestLog.java]
[[configuring-separate-request-log-for-web-application]]
== Configuring a Separate Request Log For a Web Application
To configure a separate request log for a web application, add the
following to the context XML file.
[source,xml]
----
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
...
<Call name="insertHandler">
<Arg>
<New id="RequestLog" class="org.eclipse.jetty.server.handler.RequestLogHandler">
<Set name="requestLog">
<New id="RequestLogImpl" class="org.eclipse.jetty.server.NCSARequestLog">
<Set name="filename"><Property name="jetty.logs" default="./logs"/>/test-yyyy_mm_dd.request.log</Set>
<Set name="filenameDateFormat">yyyy_MM_dd</Set>
<Set name="LogTimeZone">GMT</Set>
<Set name="retainDays">90</Set>
<Set name="append">true</Set>
</New>
</Set>
</New>
</Arg>
</Call>
...
</Configure>
----

View File

@ -0,0 +1,150 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[default-logging-with-stderrlog]]
= Default Logging with Jetty's StdErrLog
If you do nothing to configure your own logging framework, then Jetty
will default to using an internal `org.eclipse.jetty.util.log.StdErrLog`
implementation. This will output all logging events to STDERR (aka
System.err).
Simply use Jetty and you get StdErrLog based logging output.
Included in the Jetty distribution is a logging module that is capable
of performing simple capturing of all STDOUT and STDERR output to a file
that is rotated daily.
To enable on the command line:
[source,bash]
----
[my-base]$ java -jar /opt/jetty/start.jar --module=logging
----
You can also include the `--module=logging` command in your
`${jetty.base}/start.ini`
[source,bash]
----
[my-base]$ java -jar /opt/jetty/start.jar --add-to-start=logging
----
The default configuration for logging output will create a file
`${jetty.logs}/yyyy_mm_dd.stderrout.log` which allows you to configure
the output directory by setting the `jetty.logs` property to a path of
your choice.
If you want a more advanced configuration of your logging output,
consider using your logging library of choice.
The recommended way to configure StdErrLog is to create a
`${jetty.home}/resources/jetty-logging.properties` file, specify the Log
implementation to StdErrLog and then setup your logging levels.
[source,properties]
----
# Configure Jetty for StdErrLog Logging
org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StrErrLog
# Overall Logging Level is INFO
org.eclipse.jetty.LEVEL=INFO
# Detail Logging for WebSocket
org.eclipse.jetty.websocket.LEVEL=DEBUG
----
There are a number of properties you can define in here that will affect
the StdErrLog behavior.
`<name>.LEVEL=<level>`::
Sets the logging level for all loggers within the `name` specified to
the level, which can be (in increasing order of restriction) `ALL`,
`DEBUG`, `INFO`, `WARN`, `OFF`. The name (or hierarchy) can be a
specific fully qualified class or a package namespace, for example,
`org.eclipse.jetty.http.LEVEL=DEBUG` is a package namespace approach
to turn all loggers in the Jetty HTTP package to DEBUG level, and
`org.eclipse.jetty.io.ChanelEndPoint.LEVEL=ALL` turns on all logging
events for the specific class, including `DEBUG`, `INFO`, `WARN` (and
even special internally ignored exception classes). If more than one
system property specifies a logging level, the most specific one
applies.
`<name>.SOURCE=<boolean>`::
Named Logger specific, attempts to print the Java source file name and
line number from where the logging event originated. Name must be a
fully qualified class name (this configurable does not support package
name hierarchy). Default is false. Be aware that this is a slow
operation and has an impact on performance.
`<name>.STACKS=<boolean>`::
Named Logger specific, controls the display of stacktraces. Name must
be a fully qualified class name (this configurable does not support
package name hierarchy).
+
Default is true.
`org.eclipse.jetty.util.log.stderr.SOURCE=<boolean>`::
Special Global Configuration. Attempts to print the Java source file
name and line number from where the logging event originated. Default
is false.
`org.eclipse.jetty.util.log.stderr.LONG=<boolean>`::
Special Global Configuration. When true, outputs logging events to
STDERR using long form, fully qualified class names. When false, uses
abbreviated package names.
+
Default is false.
+
Example when set to false:
+
....
2014-06-03 14:36:16.013:INFO:oejs.Server:main: jetty-9.2.0.v20140526
2014-06-03 14:36:16.028:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/opt/jetty/demo-base/webapps/] at interval 1
2014-06-03 14:36:16.051:INFO:oejsh.ContextHandler:main: Started o.e.j.s.h.MovedContextHandler@7d256e50{/oldContextPath,null,AVAILABLE}
2014-06-03 14:36:17.880:INFO:oejs.ServerConnector:main: Started ServerConnector@34f2d11a{HTTP/1.1}{0.0.0.0:8080}
2014-06-03 14:36:17.888:INFO:oejs.Server:main: Started @257ms
....
+
Example when set to true:
+
....
2014-06-03 14:38:19.019:INFO:org.eclipse.jetty.server.Server:main: jetty-9.2.0.v20140526
2014-06-03 14:38:19.032:INFO:org.eclipse.jetty.deploy.providers.ScanningAppProvider:main: Deployment monitor [file:/opt/jetty/demo-base/webapps/] at interval 1
2014-06-03 14:38:19.054:INFO:org.eclipse.jetty.server.handler.ContextHandler:main: Started o.e.j.s.h.MovedContextHandler@246d8660{/oldContextPath,null,AVAILABLE}
2014-06-03 14:38:20.715:INFO:org.eclipse.jetty.server.ServerConnector:main: Started ServerConnector@59f625be{HTTP/1.1}{0.0.0.0:8080}
2014-06-03 14:38:20.723:INFO:org.eclipse.jetty.server.Server:main: Started @243ms
....
Deprecated Parameters:
These parameters existed in prior versions of Jetty, and are no longer
supported. They are included here for historical (and search engine)
reasons.
`org.eclipse.jetty.util.log.DEBUG`::
Formerly used to enable DEBUG level logging on any logger used within
Jetty (not just Jetty's own logger).
+
Replaced with using the logger implementation specific configuration
and level filtering.
`org.eclipse.jetty.util.log.stderr.DEBUG`::
Formerly used to enable DEBUG level logging on the internal Jetty
StdErrLog implementation.
+
Replaced with level specific equivalent: example:
`org.eclipse.jetty.LEVEL=DEBUG`
`DEBUG`::
Ancient debugging flag that turned on all debugging, even non-logging
debugging.
+
Jetty no longer uses because many third party libraries employ this
overly simple property name, which would generate far too much console
output.

View File

@ -0,0 +1,89 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[example-logging-log4j]]
= Example: Logging with Apache Log4j
It is possible to have the Jetty Server logging configured so that Log4j
controls the output of logging events produced by Jetty. This is
accomplished by configuring Jetty for logging to
http://logging.apache.org/log4j/[Apache Log4j] via
http://slf4j.org/manual.html[Slf4j] and the
http://slf4j.org/manual.html#swapping[Slf4j binding layer for Log4j].
A convenient replacement `logging` module has been created to bootstrap
your `${jetty.base}` directory for logging with log4j.
....
[mybase]$ mkdir modules
[mybase]$ cd modules
[modules]$ curl -O https://raw.githubusercontent.com/jetty-project/logging-modules/master/log4j-1.2/logging.mod
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 720 100 720 0 0 2188 0 --:--:-- --:--:-- --:--:-- 2188
[modules]$ cd ..
[mybase]$ java -jar /opt/jetty-dist/start.jar --add-to-start=logging
INFO: logging initialised in ${jetty.base}/start.ini (appended)
MKDIR: ${jetty.base}/logs
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/slf4j-api/1.6.6/slf4j-api-1.6.6.jar to lib/logging/slf4j-api-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/slf4j-log4j12/1.6.6/slf4j-log4j12-1.6.6.jar to lib/logging/slf4j-log4j12-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/log4j/log4j/1.2.17/log4j-1.2.17.jar to lib/logging/log4j-1.2.17.jar
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/log4j-1.2/log4j.properties to resources/log4j.properties
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/log4j-1.2/jetty-logging.properties to resources/jetty-logging.properties
INFO: resources initialised transitively
INFO: resources enabled in ${jetty.base}/start.ini
[mybase]$ java -jar /opt/jetty-dist/start.jar
....
The replacement `logging.mod` performs a number of tasks.
1. `mybase` is a `${jetty.base}` directory
2. The jetty-distribution is unpacked (and untouched) into
`/opt/jetty-dist/ `and becomes the `${jetty.home}` directory for this
demonstration.
3. The `curl` command downloads the replacement `logging.mod` and puts
it into the `${jetty.base}/modules/` directory for use by mybase only.
4. The `start.jar --add-to-start=logging` command performs a number of
steps to make the logging module available to the `${jetty.base}`
configuration.
1. The `--module=logging` command is added to the
`${jetty.base}/start.ini` configuration
2. Required `${jetty.base}` directories are created:
`${jetty.base}/logs` and `${jetty.base}/resources`
3. Required libraries are downloaded (if not present already):
slf4j-api, slf4j-log4j, and log4j itself.
+
The libraries are put in the `${jetty.base}/lib/logging/` directory.
4. Required configuration files are downloaded (if not present
already): `jetty-logging.properties`, and `log4j.properties`
+
The configuration files are put in the `${jetty.base}/resources/`
directory.
5. At this point you have your `mybase` configured so that the jetty
server itself will log using log4j, using the log4j configuration found
in `mybase/resources/log4j.properties`
You can verify the server classpath by using the `start.jar
--list-config` command.
In essence, Jetty is now configured to emit its own logging events to
slf4j, and slf4j itself is using the static log binder found in
slf4j-log4j12.jar. Making all Jetty + Slf4j + Log4j events emitted by
the Jetty server go to Log4j for routing (to console, file, syslog,
etc...)

View File

@ -0,0 +1,109 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[example-logging-java-util-logging-native]]
= Example: Logging with Java's java.util.logging via JavaUtilLog
It is possible to have the Jetty Server logging configured so that
`java.util.logging` controls the output of logging events produced by
Jetty.
This example demonstrates how to configuring Jetty for logging to
`java.util.logging` via Jetty's own JavaUtilLog implementation.
____
[IMPORTANT]
While this is a valid setup, the Jetty project recommends always using the link:#example-logging-java-util-logging[slf4j to java.util.logging configuration] for memory and performance reasons.
(this naive implementation is very non-performant and is not guaranteed to exist in the future)
____
A convenient replacement `logging` module has been created to bootstrap
your `${jetty.base}` directory for logging with java.util.logging.
....
[mybase]$ mkdir modules
[mybase]$ cd modules
[modules]$ curl -O https://raw.githubusercontent.com/jetty-project/logging-modules/master/java.util.logging-native/logging.mod
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 623 100 623 0 0 1879 0 --:--:-- --:--:-- --:--:-- 1876
[modules]$ cd ..
[mybase]$ java -jar /opt/jetty-dist/start.jar --add-to-start=logging
INFO: logging initialised in ${jetty.base}/start.ini (appended)
MKDIR: ${jetty.base}/logs
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/java.util.logging-native/jetty-logging.xml to etc/jetty-logging.xml
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/java.util.logging-native/logging.properties to resources/logging.properties
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/java.util.logging-native/jetty-logging.properties to resources/jetty-logging.properties
INFO: resources initialised transitively
INFO: resources enabled in ${jetty.base}/${jetty.base}
[mybase]$ java -jar /opt/jetty-dist/start.jar
....
The replacement `logging.mod` performs a number of tasks.
1. `mybase` is a `${jetty.base}` directory
2. The jetty-distribution is unpacked (and untouched) into
`/opt/jetty-dist/ `and becomes the `${jetty.home}` directory for this
demonstration.
3. The `curl` command downloads the replacement `logging.mod` and puts
it into the `${jetty.base}/modules/` directory for use by mybase only.
4. The `start.jar --add-to-start=logging` command performs a number of
steps to make the logging module available to the `${jetty.base}`
configuration.
1. The `--module=logging` command is added to the
`${jetty.base}/start.ini` configuration
2. Required `${jetty.base}` directories are created:
`${jetty.base}/logs` and `${jetty.base}/resources`
3. Required configuration files are downloaded (if not present
already): `jetty-logging.properties`, and `logging.properties`
+
The configuration files are put in the `${jetty.base}/resources/`
directory.
4. Required `java.util.logging` initialization commands are downloaded
(if not present already): `jetty-logging.xml`
+
The xml file is put in the `${jetty.base}/etc/` directory.
5. At this point you have your `mybase` configured so that the jetty
server itself will log using java.util.logging, using the
java.util.logging configuration found in
`mybase/resources/logging.properties`
You can verify the server classpath by using the `start.jar
--list-config` command.
In essence, Jetty is now configured to use
`org.eclipse.jetty.util.log.JavaUtilLog`, which emit its own logging
events to java.util.logging. Making all Jetty + java.util.logging events
emitted by the Jetty server go to java.util.logging for routing (to
console, file, etc...)
If you have any custom java.util.logging handlers that you want to use,
put the implementation jar in your `${jetty.base}/lib/logging/`
directory and reference them in the
`${jetty.base}/resources/logging.properties` file.
____
[NOTE]
`java.util.logging` is configured via the `${jetty.base}/resources/logging.properties` file during a valid startup of Jetty.
This means that if there is any startup errors that occur before `java.util.logging` is configured, they will likely be lost and/or not routed through your configuration.
(Other logging frameworks are more reliable in that they always initialize and configure on first use, unlike java.util.logging)
+
While it is possible to configure java.util.logging sooner, even at JVM startup, the example demonstrated here does not show this technique.
For more information consult the http://docs.oracle.com/javase/7/docs/api/java/util/logging/LogManager.html[official java.util.logging.LogManager javadoc documentation from Oracle].
____

View File

@ -0,0 +1,112 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[example-logging-java-util-logging]]
= Example: Logging with Java's java.util.logging via Slf4j
It is possible to have the Jetty Server logging configured so that
`java.util.logging` controls the output of logging events produced by
Jetty.
This example demonstrates how to configuring Jetty for logging to
`java.util.logging` via http://slf4j.org/manual.html[Slf4j] and the
http://slf4j.org/manual.html#swapping[Slf4j binding layer for
java.util.logging]. If you want to use the built-in native JavaUtilLog
implementation, see #example-logging-java-util-logging-native
A convenient replacement `logging` module has been created to bootstrap
your `${jetty.base}` directory for logging with java.util.logging.
....
[mybase]$ mkdir modules
[mybase]$ cd modules
[modules]$ curl -O https://raw.githubusercontent.com/jetty-project/logging-modules/master/java.util.logging-slf4j/logging.mod
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 826 100 826 0 0 2468 0 --:--:-- --:--:-- --:--:-- 2473
[modules]$ cd ..
[mybase]$ java -jar /opt/jetty-dist/start.jar --add-to-start=logging
INFO: logging initialised in ${jetty.base}/start.ini (appended)
MKDIR: ${jetty.base}/logs
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/slf4j-jdk14/1.6.6/slf4j-jdk14-1.6.6.jar to lib/logging/slf4j-jdk14-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/slf4j-api/1.6.6/slf4j-api-1.6.6.jar to lib/logging/slf4j-api-1.6.6.jar
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/java.util.logging-slf4j/jetty-logging.xml to etc/jetty-logging.xml
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/java.util.logging-slf4j/logging.properties to resources/logging.properties
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/java.util.logging-slf4j/jetty-logging.properties to resources/jetty-logging.properties
INFO: resources initialised transitively
INFO: resources enabled in ${jetty.base}/start.ini
[mybase]$ java -jar /opt/jetty-dist/start.jar
....
The replacement `logging.mod` performs a number of tasks.
1. `mybase` is a `${jetty.base}` directory
2. The jetty-distribution is unpacked (and untouched) into
`/opt/jetty-dist/ `and becomes the `${jetty.home}` directory for this
demonstration.
3. The `curl` command downloads the replacement `logging.mod` and puts
it into the `${jetty.base}/modules/` directory for use by mybase only.
4. The `start.jar --add-to-start=logging` command performs a number of
steps to make the logging module available to the `${jetty.base}`
configuration.
1. The `--module=logging` command is added to the
`${jetty.base}/start.ini` configuration
2. Required `${jetty.base}` directories are created:
`${jetty.base}/logs` and `${jetty.base}/resources`
3. Required libraries are downloaded (if not present already):
slf4j-api, and slf4j-jdk14.
+
The libraries are put in the `${jetty.base}/lib/logging/` directory.
4. Required configuration files are downloaded (if not present
already): `jetty-logging.properties`, and `logging.properties`
+
The configuration files are put in the `${jetty.base}/resources/`
directory.
5. Required `java.util.logging` initialization commands are downloaded
(if not present already): `jetty-logging.xml`
+
The xml file is put in the `${jetty.base}/etc/` directory.
5. At this point you have your `mybase` configured so that the jetty
server itself will log using java.util.logging, using the
java.util.logging configuration found in
`mybase/resources/logging.properties`
You can verify the server classpath by using the `start.jar
--list-config` command.
In essence, Jetty is now configured to emit its own logging events to
slf4j, and slf4j itself is using the static log binder found in
slf4j-jdk14.jar. Making all Jetty + Slf4j + java.util.logging events
emitted by the Jetty server go to java.util.logging for routing (to
console, file, etc...)
If you have any custom java.util.logging handlers that you want to use,
put the implementation jar in your `${jetty.base}/lib/logging/`
directory and reference them in the
`${jetty.base}/resources/logging.properties` file.
____
[NOTE]
`java.util.logging` is configured via the `${jetty.base}/resources/logging.properties` file during a valid startup of Jetty.
This means that if there is any startup errors that occur before `java.util.logging` is configured, they will likely be lost and/or not routed through your configuration.
(Other logging frameworks are more reliable in that they always initialize and configure on first use, unlike java.util.logging)
+
While it is possible to configure java.util.logging sooner, even at JVM startup, the example demonstrated here does not show this technique.
For more information consult the http://docs.oracle.com/javase/7/docs/api/java/util/logging/LogManager.html[official java.util.logging.LogManager javadoc documentation from Oracle].
____

View File

@ -0,0 +1,166 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[example-logging-logback-centralized]]
= Example: Centralized Logging with Logback
The term _Centralized Logging_ refers to a forced logging configuration
for the Jetty Server and all web applications that are deployed on the
server. It routes all logging events from the web applications to a
single configuration on the Server side.
The example below shows how to accomplish this with Jetty and Slf4j,
using Logback to manage the final writing of logs to disk.
____
[IMPORTANT]
This mechanism forces all webapps to use the server's configuration for logging, something that isn't 100% appropriate for all webapps.
+
An example would be having Jenkins-CI deployed as an webapp, if you force its logging configuration to the server side, you lose the ability on http://jenkins-ci.org/[Jenkins-CI] to see the logs from the various builds (as now those logs are actually going to the main server log).
____
This configuration is essentially the multiple logger configuration with
added configuration to the deployers to force a WebAppClassLoader change
to use the server classpath over the webapps classpath for the logger
specific classes.
The technique used by this configuration is to provide an
link:{JDURL}org/eclipse/jetty/deploy/AppLifeCycle.Binding.html[AppLifeCycle.Binding]
against the
link:{JDURL}/org/eclipse/jetty/deploy/AppLifeCycle.html[`"deploying"`
node] that modifies the
link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#addSystemClass(java.lang.String)[WebAppContext.addSystemClass(String)]
for the common logging classes. (See
https://github.com/jetty-project/jetty-webapp-logging/blob/master/src/main/java/org/eclipse/jetty/webapp/logging/CentralizedWebAppLoggingBinding.java[org.eclipse.jetty.logging.CentralizedWebAppLoggingBinding]
for actual implementation)
A convenient replacement `logging` module has been created to bootstrap
your `${jetty.base}` directory for capturing all Jetty server logging
from multiple logging frameworks into a single logging output file
managed by logback.
....
[mybase]$ mkdir modules
[mybase]$ cd modules
[modules]$ curl -O https://raw.githubusercontent.com/jetty-project/logging-modules/master/capture-all/logging.mod
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1416 100 1416 0 0 4241 0 --:--:-- --:--:-- --:--:-- 4252
[master]$ curl -O https://raw.githubusercontent.com/jetty-project/logging-modules/master/centralized/webapp-logging.mod
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 660 100 660 0 0 2032 0 --:--:-- --:--:-- --:--:-- 2037
[modules]$ cd ..
[mybase]$ java -jar /opt/jetty-dist/start.jar --add-to-start=logging,webapp-logging
INFO: logging initialised in ${jetty.base}/start.ini (appended)
MKDIR: ${jetty.base}/logs
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/slf4j-api/1.6.6/slf4j-api-1.6.6.jar to lib/logging/slf4j-api-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/log4j-over-slf4j/1.6.6/log4j-over-slf4j-1.6.6.jar to lib/logging/log4j-over-slf4j-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/jul-to-slf4j/1.6.6/jul-to-slf4j-1.6.6.jar to lib/logging/jul-to-slf4j-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/jcl-over-slf4j/1.6.6/jcl-over-slf4j-1.6.6.jar to lib/logging/jcl-over-slf4j-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/ch/qos/logback/logback-core/1.0.7/logback-core-1.0.7.jar to lib/logging/logback-core-1.0.7.jar
DOWNLOAD: http://central.maven.org/maven2/ch/qos/logback/logback-classic/1.0.7/logback-classic-1.0.7.jar to lib/logging/logback-classic-1.0.7.jar
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/capture-all/logback.xml to resources/logback.xml
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/capture-all/jetty-logging.properties to resources/jetty-logging.properties
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/capture-all/jetty-logging.xml to etc/jetty-logging.xml
INFO: resources initialised transitively
INFO: resources enabled in ${jetty.base}/start.ini
INFO: webapp-logging initialised in ${jetty.base}/start.ini (appended)
DOWNLOAD: http://central.maven.org/maven2/org/eclipse/jetty/jetty-webapp-logging/9.0.0/jetty-webapp-logging-9.0.0.jar to lib/webapp-logging/jetty-webapp-logging-9.0.0.jar
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/jetty-webapp-logging/master/src/main/config/etc/jetty-webapp-logging.xml to etc/jetty-webapp-logging.xml
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/jetty-webapp-logging/master/src/main/config/etc/jetty-mdc-handler.xml to etc/jetty-mdc-handler.xml
INFO: deploy initialised transitively
INFO: deploy enabled in ${jetty.base}/start.ini
INFO: logging initialised transitively
INFO: resources initialised transitively
INFO: resources enabled in ${jetty.base}/start.ini
[mybase]$ java -jar /opt/jetty-dist/start.jar
....
The replacement `logging.mod` performs a number of tasks.
1. `mybase` is a `${jetty.base}` directory
2. The jetty-distribution is unpacked (and untouched) into
`/opt/jetty-dist/ `and becomes the `${jetty.home}` directory for this
demonstration.
3. The `curl` command downloads the replacement `logging.mod` and puts
it into the `${jetty.base}/modules/` directory for use by mybase only.
4. The `start.jar
--add-to-start=logging,webapp-logging` command performs a number
of steps to make the logging module available to the `${jetty.base}`
configuration.
1. Several entries are added to the `${jetty.base}/start.ini`
configuration
1. `--module=logging` is added to enable the logging module
2. `--module=webapp-logging` is added to enable the webapp-logging
module
2. Required `${jetty.base}` directories are created:
`${jetty.base}/logs` and `${jetty.base}/resources`
3. Required logging libraries are downloaded (if not present already):
* slf4j-api.jar - API jar for Slf4j (used by most of the rest of the
jars)
* log4j-over-slf4j.jar - Slf4j jar that captures all log4j emitted
logging events
* jul-to-slf4j.jar - Slf4j jar that captures all java.util.logging
events
* jcl-over-slf4j.jar - Slf4j jar that captures all commons-logging
events
* logback-classic.jar - the Slf4j adapter jar that routes all of the
captured logging events to logback itself.
* logback-core.jar - the logback implementation jar, that handles all of
the filtering and output of the logging events.
+
These libraries are put in the `${jetty.base}/lib/logging/` directory.
4. Required webapp-logging library are downloaded (if not present
already):
* jetty-webapp-logging.jar - the jetty side deployment manger
app-lifecycle bindings for modifying the WebAppClassloaders of deployed
webapps.
+
This library is put in the `${jetty.base}/lib/webapp-logging/`
directory.
5. Required configuration files are downloaded (if not present
already): `jetty-logging.properties`, and `logback.xml`
+
The configuration files are put in the `${jetty.base}/resources/`
directory.
6. Required initialization commands are downloaded (if not present
already): `jetty-logging.xml`, `jetty-webapp-logging.xml`, and
`jetty-mdc-handler.xml`
+
These xml files are put in the `${jetty.base}/etc/` directory.
5. At this point you have your `mybase` configured so that the jetty
server itself will log using slf4j, and all other logging events from
other Jetty Server components (such as database drivers, security
layers, jsp, mail, and other 3rd party server components) are routed to
logback for filtering and output.
+
All webapps deployed via the DeploymentManager have their
WebAppClassLoader modified to use server side classes and configuration
for all logging implementations.
You can verify the server classpath by using the `start.jar
--list-config` command.
In essence, Jetty is now configured to emit its own logging events to
slf4j, and various slf4j bridge jars are acting on behalf of log4j,
java.util.logging, and commons-logging, routing all of the logging
events to logback (a slf4j adapter) for routing (to console, file,
etc...)

View File

@ -0,0 +1,48 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[example-logging-logback-sifting]]
= Example: MDC Based Sifting of Logs with Logback
This page describes how to create log files at the server level and name
them based on an arbitrary context. You do this with SLF4J + Logback +
Jetty Webapp Logging in the mix. Find example projects for this feature
at github:
....
https://github.com/jetty-project/jetty-and-logback-example
....
.GitHub Example Project
[cols=",",options="header",]
|=======================================================================
|Modules |Description
|/jetty-distro-with-logback-basic/ |Configures the jetty distribution
with logback enabled at the server level with an example logback
configuration.
|/jetty-distro-with-logback-sifting/ |Configures the jetty distribution
with logback, centralized webapp logging, an MDC handler, and a sample
logback configuration that performs sifting based on the incoming Host
header on the requests.
|/jetty-slf4j-mdc-handler/ |Provides the SLF4J MDC key/value pairs that
Jetty needs to perform the sample sifting.
|/jetty-slf4j-test-webapp/ |A sample webapp+servlet that accepts
arbitrary values on a form POST and logs them via SLF4J, so that you can
see the results of this example.
|=======================================================================

View File

@ -0,0 +1,86 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[example-logging-logback]]
= Example: Logging with Logback
It is possible to have the Jetty Server logging configured so that
Logback controls the output of logging events produced by Jetty. This is
accomplished by configuring Jetty for logging to `Logback`, which uses
http://slf4j.org/manual.html[Slf4j] and the
http://logback.qos.ch/[Logback Implementation for Slf4j].
A convenient replacement `logging` module has been created to bootstrap
your `${jetty.base}` directory for logging with logback.
....
[mybase]$ mkdir modules
[mybase]$ cd modules
[modules]$ curl -O https://raw.githubusercontent.com/jetty-project/logging-modules/master/logback/logging.mod
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 742 100 742 0 0 2196 0 --:--:-- --:--:-- --:--:-- 2201
[modules]$ cd ..
[mybase]$ java -jar /opt/jetty-dist/start.jar --add-to-start=logging
INFO: logging initialised in ${jetty.base}/start.ini (appended)
MKDIR: ${jetty.base}/logs
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/slf4j-api/1.6.6/slf4j-api-1.6.6.jar to lib/logging/slf4j-api-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/ch/qos/logback/logback-core/1.0.7/logback-core-1.0.7.jar to lib/logging/logback-core-1.0.7.jar
DOWNLOAD: http://central.maven.org/maven2/ch/qos/logback/logback-classic/1.0.7/logback-classic-1.0.7.jar to lib/logging/logback-classic-1.0.7.jar
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/logback/logback.xml to resources/logback.xml
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/logback/jetty-logging.properties to resources/jetty-logging.properties
[mybase]$ java -jar /opt/jetty-dist/start.jar
....
The replacement `logging.mod` performs a number of tasks.
1. `mybase` is a `${jetty.base}` directory
2. The jetty-distribution is unpacked (and untouched) into
`/opt/jetty-dist/ `and becomes the `${jetty.home}` directory for this
demonstration.
3. The `curl` command downloads the replacement `logging.mod` and puts
it into the `${jetty.base}/modules/` directory for use by mybase only.
4. The `start.jar --add-to-start=logging` command performs a number of
steps to make the logging module available to the `${jetty.base}`
configuration.
1. The `--module=logging` command is added to the
`${jetty.base}/start.ini` configuration
2. Required `${jetty.base}` directories are created:
`${jetty.base}/logs` and `${jetty.base}/resources`
3. Required libraries are downloaded (if not present already):
slf4j-api, logback-core, and logback-classic.
+
The libraries are put in the `${jetty.base}/lib/logging/` directory.
4. Required configuration files are downloaded (if not present
already): `jetty-logging.properties`, and `logback.xml`
+
The configuration files are put in the `${jetty.base}/resources/`
directory.
5. At this point you have your `mybase` configured so that the jetty
server itself will log using logback, using the logback configuration
found in `mybase/resources/logback.xml`
You can verify the server classpath by using the `start.jar
--list-config` command.
In essence, Jetty is now configured to emit its own logging events to
slf4j, and slf4j itself is using the static log binder found in
logback-classic.jar. Making all Jetty + Slf4j + Logback events emitted
by the Jetty server go to Logback for routing (to console, file, syslog,
etc...)

View File

@ -0,0 +1,200 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[example-slf4j-multiple-loggers]]
= Example: Capturing Multiple Logging Frameworks with Slf4j
This page describes how to configure Jetty for capturing multiple
logging frameworks logging events into a single logging implementation
handled by Slf4j.
When using Slf4j, you can configure a single logging solution for the
variety of logging libraries available in common use. With careful
setup, you can support all of the following logging APIs at the same
time, with a single configuration file to control the output of events
produces by these APIs.
Logging APIs that Slf4j supports:
* Slf4j API
* Logback API
* Apache Log4j 1.2
* JDK 1.4 Logging (aka `java.util.logging`)
* Apache Commons Logging
To accomplish this you must make some careful choices, starting with a
single underlying logging framework. This decision guides the rest of
your choices about JARs to place on the Server classpath.
.Slf4j Logging Grid
[width="100%",cols="25%,25%,25%,25%",options="header",]
|=======================================================================
|Logging API |Slf4j Binding Jar |Slf4j Adapter Jar |Underlying Logging
Framework
|Logback API |n/a |logback-classic.jar |logback-core.jar
|Log4j
|http://slf4j.org/legacy.html#log4j-over-slf4j[log4j-over-slf4j.jar]
|slf4j-log4j12.jar |log4j.jar
|JDK 1.4 Logging
|http://slf4j.org/legacy.html#jul-to-slf4j[jul-to-slf4j.jar]
|slf4j-jdk14.jar |(Core Java Classlib)
|Commons Logging
|http://slf4j.org/legacy.html#jcl-over-slf4j[jcl-over-slf4j.jar]
|slf4j-jcl.jar |commons-logging.jar
|=======================================================================
Logging API::
The Logging API that you are either capturing events from and/or using
to write out those events (for example, to disk).
Slf4j Binding JAR::
Special JARs, created and maintained by the Slf4j project, that
pretend to be the various Logging API implementation classes, but
instead just route that Logging API's events to Slf4j to handle.
+
There MAY be multiple Slf4j binding JARs present on the classpath at
the same time.
+
For a single logging API, if you choose to use the Slf4j binding JAR,
then you MUST NOT include the SLf4j adapter JAR or underlying logging
framework in the classpath as well.
Slf4j Adapter Jar::
These JARs are created and maintained by the Slf4j project and route
Slf4j logging events to a specific underlying logging framework.
+
There MUST NOT be multiple Slf4j adapter JARs present on the classpath
at the same time.
+
Logging events that these adapter JARs capture can come from direct
use of the Slf4j API or via one of the Slf4j binding JAR
implementations.
Underlying Logging Framework::
This is the last leg of your configuration, the implementation that
processes, filters, and outputs the logging events to the console,
logging directory on disk, or whatever else the underlying logging
framework supports (like Socket, SMTP, Database, or even SysLog in the
case of Logback).
+
____
[CAUTION]
There MUST NOT be multiple underlying logging frameworks on the classpath.
If there are, the Slf4j framework fails to load.
____
+
____
[NOTE]
Some third party libraries provide their own implementations of common logging APIs; be careful not to accidentally include an underlying logging framework.
+
For example, if you are using SpringSource you likely have a `com.springsource.org.apache.log4j.jar` along with a `log4j.jar`, which have the same classes in them.
In this example, use the `com.springsource.org.apache.log4j.jar` version and exclude the `log4j.jar`, as the SpringSource version includes extra metadata suitable for using SpringSource.
____
The following sections use Logback as the underlying Logging framework.
This requires using `logback-classic.jar` and `logback-core.jar`, and
excluding any other Slf4j adapter JAR or underlying logging framework.
It also requires including the other Slf4j binding JARs in the
classpath, along with some special initialization for
`java.util.logging`.
A convenient replacement `logging` module has been created to bootstrap
your `${jetty.base}` directory for capturing all Jetty server logging
from multiple logging frameworks into a single logging output file
managed by logback.
....
[mybase]$ mkdir modules
[mybase]$ cd modules
[modules]$ curl -O https://raw.githubusercontent.com/jetty-project/logging-modules/master/capture-all/logging.mod
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1293 100 1293 0 0 3693 0 --:--:-- --:--:-- --:--:-- 3694
[modules]$ cd ..
[mybase]$ java -jar /opt/jetty-dist/start.jar --add-to-start=logging
INFO: logging initialised in ${jetty.base}/start.ini (appended)
MKDIR: ${jetty.base}/logs
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/slf4j-api/1.6.6/slf4j-api-1.6.6.jar to lib/logging/slf4j-api-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/log4j-over-slf4j/1.6.6/log4j-over-slf4j-1.6.6.jar to lib/logging/log4j-over-slf4j-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/jul-to-slf4j/1.6.6/jul-to-slf4j-1.6.6.jar to lib/logging/jul-to-slf4j-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/org/slf4j/jcl-over-slf4j/1.6.6/jcl-over-slf4j-1.6.6.jar to lib/logging/jcl-over-slf4j-1.6.6.jar
DOWNLOAD: http://central.maven.org/maven2/ch/qos/logback/logback-core/1.0.7/logback-core-1.0.7.jar to lib/logging/logback-core-1.0.7.jar
DOWNLOAD: http://central.maven.org/maven2/ch/qos/logback/logback-classic/1.0.7/logback-classic-1.0.7.jar to lib/logging/logback-classic-1.0.7.jar
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/capture-all/logback.xml to resources/logback.xml
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/capture-all/jetty-logging.properties to resources/jetty-logging.properties
DOWNLOAD: https://raw.githubusercontent.com/jetty-project/logging-modules/master/capture-all/jetty-logging.xml to etc/jetty-logging.xml
INFO: resources initialised transitively
INFO: resources enabled in ${jetty.base}/start.ini
[mybase]$ java -jar /opt/jetty-dist/start.jar
....
The replacement `logging.mod` performs a number of tasks.
1. `mybase` is a `${jetty.base}` directory
2. The jetty-distribution is unpacked (and untouched) into
`/opt/jetty-dist/ `and becomes the `${jetty.home}` directory for this
demonstration.
3. The `curl` command downloads the replacement `logging.mod` and puts
it into the `${jetty.base}/modules/` directory for use by mybase only.
4. The `start.jar --add-to-start=logging` command performs a number of
steps to make the logging module available to the `${jetty.base}`
configuration.
1. The `--module=logging` command is added to the
`${jetty.base}/start.ini` configuration
2. Required `${jetty.base}` directories are created:
`${jetty.base}/logs` and `${jetty.base}/resources`
3. Required libraries are downloaded (if not present already):
* slf4j-api.jar - API jar for Slf4j (used by most of the rest of the
jars)
* log4j-over-slf4j.jar - Slf4j jar that captures all log4j emitted
logging events
* jul-to-slf4j.jar - Slf4j jar that captures all java.util.logging
events
* jcl-over-slf4j.jar - Slf4j jar that captures all commons-logging
events
* logback-classic.jar - the Slf4j adapter jar that routes all of the
captured logging events to logback itself.
* logback-core.jar - the logback implementation jar, that handles all of
the filtering and output of the logging events.
+
These libraries are put in the `${jetty.base}/lib/logging/` directory.
4. Required configuration files are downloaded (if not present
already): `jetty-logging.properties`, and `logback.xml`
+
The configuration files are put in the `${jetty.base}/resources/`
directory.
5. Required `java.util.logging` initialization commands are downloaded
(if not present already): `jetty-logging.xml`
+
The xml file is put in the `${jetty.base}/etc/` directory.
5. At this point you have your `mybase` configured so that the jetty
server itself will log using slf4j, and all other logging events from
other Jetty Server components (such as database drivers, security
layers, jsp, mail, and other 3rd party server components) are routed to
logback for filtering and output.
You can verify the server classpath by using the `start.jar
--list-config` command.
In essence, Jetty is now configured to emit its own logging events to
slf4j, and various slf4j bridge jars are acting on behalf of log4j,
java.util.logging, and commons-logging, routing all of the logging
events to logback (a slf4j adapter) for routing (to console, file,
etc...)

View File

@ -0,0 +1,18 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[npn-chapter]]
== NPN

View File

@ -0,0 +1,303 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
How to build NPN
================
[[npn]]
=
[[npn-introduction]]
== Configuring NPN
The Jetty project provides an implementation of the Transport Layer
Security (TLS) extension for Next Protocol Negotiation (NPN) for OpenJDK
7 (but not for OpenJDK 8 or greater - see xref:alpn-chapter[] for
using a TLS protocol negotiation extension with OpenJDK 8 or greater).
NPN allows the application layer to negotiate which protocol to use over
the secure connection.
NPN currently negotiates using SPDY as an application level protocol on
port 443, and also negotiates the SPDY version. However, NPN is not
SPDY-specific in any way. Jetty's NPN implementation, although hosted
under the umbrella of the Jetty project, is independent of Jetty (the
servlet container); you can use it in any other Java network server.
[[npn-starting]]
== Starting the JVM
To enable NPN support, start the JVM as follows:
[source,plain]
----
java -Xbootclasspath/p:<path_to_npn_boot_jar> ...
----
where `path_to_npn_boot_jar` is the path on the file system for the NPN
Boot Jar file, for example, one at the Maven coordinates
org.mortbay.jetty.npn:npn-boot.
Be aware that the current versions of the npn packages no longer align
with Jetty versions. Look at the dates in those file paths before
looking at the version number.
[[npn-osgi]]
=== Starting in OSGi
To use NPN in an OSGi environment, in addition to putting the NPN jar on
the boot classpath for the container, you will also need to deploy the
jetty-osgi-npn jar. This jar contains a Fragment-Host directive that
ensures the NPN classes will be available from the system bundle.
You can download the jetty-osgi-npn jar from maven central:
http://central.maven.org/maven2/org/eclipse/jetty/osgi/jetty-osgi-npn/
[[npn-understanding]]
== Understanding the NPN API
Applications need to interact with NPN TLS extension protocol
negotiations. For example, server applications need to know whether the
client supports NPN, and client applications needs to know the list of
protocols the server supports, and so on.
To implement this interaction, Jetty's NPN implementation provides an
API to applications, hosted at Maven coordinates
org.eclipse.jetty.npn:npn-api. You need to declare this dependency as
provided, because the npn-boot Jar already includes it (see the previous
section), and it is therefore available in the boot classpath.
The API consists of a single class,
`org.eclipse.jetty.npn.NextProtoNego`, and applications need to register
instances of SSLSocket or SSLEngine with a ClientProvider or
ServerProvider (depending on whether the application is a client or
server application). Refer to NextProtoNego Javadocs and to the examples
below for further details about client and server provider methods.
[[client-example]]
== Client Example
[source,java]
----
SSLContext sslContext = ...;
final SSLSocket sslSocket = (SSLSocket)context.getSocketFactory().createSocket("localhost", server.getLocalPort());
NextProtoNego.put(sslSocket, new NextProtoNego.ClientProvider()
{
@Override
public boolean supports()
{
return true;
}
@Override
public void unsupported()
{
NextProtoNego.remove(sslSocket);
}
@Override
public String selectProtocol(List<String> protocols)
{
NextProtoNego.remove(sslSocket);
return protocols.get(0);
}
});
----
The NPN implementation calls `NextProtoNego.ClientProvider` methods
`supports()`, `unsupported()` and `selectProtocol(List<String>)`, so
that the client application can:
* decide whether to support NPN.
* know whether the server supports NPN.
* select one of the protocols the server supports.
[[server-example]]
== Server Example
The example for SSLEngine is identical, and you just need to replace the
SSLSocket instance with an SSLEngine instance.
[source,java]
----
final SSLSocket sslSocket = ...;
NextProtoNego.put(sslSocket, new NextProtoNego.ServerProvider()
{
@Override
public void unsupported()
{
NextProtoNego.remove(sslSocket);
}
@Override
public List<String> protocols()
{
return Arrays.asList("http/1.1");
}
@Override
public void protocolSelected(String protocol)
{
NextProtoNego.remove(sslSocket);
System.out.println("Protocol Selected is: " + protocol);
}
});
----
The NPN implementation calls `NextProtoNego.ServerProvider` methods
`unsupported()`, `protocols()` and `protocolSelected(String),` so that
the server application can:
* know whether the client supports NPN.
* provide the list of protocols the server supports.
* know which protocol the client chooses.
[[npn-implementation]]
== Implementation Details
It is common that the NextProtoNego.ServerProvider and the
NextProtoNego.ClientProvider are implemented as (anonymous) inner
classes, and that their methods' implementations require references to
the the sslSocket (or sslEngine), either directly or indirectly.
Since the NextProtoNego class holds [sslSocket/sslEngine, provider]
pairs in a `WeakHashMap`, if the value (that is, the provider
implementation) holds a strong (even indirect) reference to the key,
then the `WeakHashMap` entries are never removed, leading to a memory
leak.
It is important that implementations of `NextProtoNego.ServerProvider`
and `NextProtoNego.ClientProvider` remove the `sslSocket` or `sslEngine`
when the negotiation is complete, like shown in the examples above.
Be aware that declaring the SslConnection as a final local variable and
referencing it from within the anonymous NextProtoNego.ServerProvider
class generates a hidden field in the anonymous inner class, that may
cause a memory leak if the implementation does not call
`NextProtoNego.remove()`.
[[npn-tests]]
== Unit Tests
You can write and run unit tests that use the NPN implementation. The
solution that we use with Maven is to specify an additional command line
argument to the Surefire plugin:
[source,xml]
----
<project>
<properties>
<npn-version>1.1.1.v20121030</npn-version>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
-Xbootclasspath/p:${settings.localRepository}/org/mortbay/jetty/npn/npn-boot/${npn-version}/npn-boot-${npn-version}.jar
</argLine>
</configuration>
</plugin>
...
</plugins>
</build>
...
</project>
----
[[npn-debugging]]
== Debugging
You can enable debug logging for the NPN implementation in this way:
....
NextProtoNego.debug = true;
....
Since the NextProtoNego class is in the boot classpath, we chose not to
use logging libraries because we do not want to override application
logging library choices; therefore the logging is performed directly on
`System.err.`
[[npn-license-details]]
== License Details
The NPN implementation relies on modification of a few OpenJDK classes
and on a few new classes that need to live in the `sun.security.ssl`
package. These classes are released under the same GPLv2+exception
license of OpenJDK.
The NextProtoNego class is released under same license as the classes of
the Jetty project.
[[npn-versions]]
== Versions
The NPN implementation, relying on modifications of OpenJDK classes,
updates every time there are updates to the modified OpenJDK classes.
.NPN vs. OpenJDK versions
[cols=",",options="header",]
|==========================================================
|NPN version |OpenJDK version
|1.0.0.v20120402 |1.7.0 - 1.7.0u2 - 1.7.0u3
|1.1.0.v20120525 |1.7.0u4 - 1.7.0u5
|1.1.1.v20121030 |1.7.0u6 - 1.7.0u7
|1.1.3.v20130313 |1.7.0u9 - 1.7.0u10 - 1.7.0u11
|1.1.4.v20130313 |1.7.0u13
|1.1.5.v20130313 |1.7.0u15 - 1.7.0u17 - 1.7.0u21 - 1.7.0u25
|1.1.6.v20130911 |1.7.0u40 - 1.7.0u45 - 1.7.0u51
|1.1.8.v20141013 |1.7.0u55 - 1.7.0u60 - 1.7.0u65 - 1.7.0u67
|1.1.9.v20141016 |1.7.0u71 - 1.7.0u72
|1.1.10.v20150130 |1.7.0u75 - 1.7.0u76 - 1.7.0u79
|1.1.11.v20150415 |1.7.0u80
|==========================================================
[[npn-build]]
== How to build NPN
This section is for Jetty developers that need to update the NPN
implementation with the OpenJDK versions.
Clone the OpenJDK repository with the following command:
....
$ hg clone http://hg.openjdk.java.net/jdk7u/jdk7u jdk7u
$ cd jdk7u
$ ./get_source.sh
....
To update the source to a specific tag, use the following command:
....
$ ./make/scripts/hgforest.sh update <tag-name>
....
The list of OpenJDK tags can be obtained from
http://hg.openjdk.java.net/jdk7u/jdk7u/tags[this page].
Then you need to compare and incorporate the OpenJDK source changes into
the modified OpenJDK classes at the
https://github.com/jetty-project/jetty-npn[NPN GitHub Repository].

View File

@ -0,0 +1,30 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
= Jetty Administration Guide
include::startup/chapter.adoc[]
include::sessions/chapter.adoc[]
include::jndi/chapter.adoc[]
include::annotations/chapter.adoc[]
include::jmx/chapter.adoc[]
include::alpn/chapter.adoc[]
include::http2/chapter.adoc[]
include::fastcgi/chapter.adoc[]
include::extras/chapter.adoc[]
include::runner/chapter.adoc[]
include::tuning/chapter.adoc[]
include::logging/chapter.adoc[]

View File

@ -0,0 +1,22 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[runner]]
== Jetty Runner
This chapter explains how to use the jetty-runner to run your webapps without needing an installation of jetty.
include::jetty-runner.adoc[]

View File

@ -0,0 +1,322 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jetty-runner]]
=== Use Jetty without an installed distribution
The idea of the jetty-runner is extremely simple run a webapp directly from the command line using a single jar and as much default configuration as possible.
Of course, if your webapp is not so straightforward, the jetty-runner has command line options which allow
you to customize the execution environment.
[[jetty-runner-preparation]]
==== Preparation
You will need the jetty-runner jar:
1. http://central.maven.org/maven2/org/eclipse/jetty/jetty-runner/[Get] the jetty-runner jar, from http://search.maven.org/#browse[maven central]
==== Deploying a simple context
Let's assume we have a very simple webapp, that does not need any resources from its environment, nor any configuration apart from the defaults.
Starting it is as simple as doing the following:
....
> java -jar jetty-runner.jar simple.war
....
This will start jetty on port 8080, and deploy the webapp to "/".
Your webapp does not have to be packed into a war, you can deploy a webapp that is a directory instead in the same way:
....
> java -jar jetty-runner.jar simple
....
In fact, the webapp does not have to be a war or even a directory, it can simply be a jetty link:#using-context-provider[context xml] file that describes your webapp:
....
> java -jar jetty-runner.jar simple-context.xml
....
____
[NOTE]
When using a context xml file, the application being deployed is not even required to be a fully-fledged webapp. It can simply be a Jetty link:#what-is-a-context[context].
____
==== Deploying multiple contexts
If you have more than one webapp that must be deployed, simply provide them all on the command line.
You can control the context paths for them using the "--path" parameter.
Here's an example of deploying 2 wars (although either or both of them could be unpacked directories instead):
....
> java -jar jetty-runner.jar --path /one my1.war --path /two my2.war
....
If you have context xml files that describe your webapps, you can fully configure your webapps in them, and hence you don't need to use the command line switches.
Just provide the list of context files like so:
....
> java -jar jetty-runner.jar my-first-context.xml my-second-context.xml my-third-context.xml
....
____
[NOTE]
The command line switches override configuration file settings. So, for example, you could set the context path for the webapp inside the context xml file, and use the --path switch to override it on the command line.
____
===== Changing the default port
By default the jetty-runner will listen on port 8080.
You can easily change this on the command line using the "--port" command.
Here's an example that runs our simple.war on port 9090:
....
> java -jar jetty-runner.jar --port 9090 simple.war
....
===== Using jetty.xml files
Instead of, or in addition to using command line switches, you can use one or more jetty.xml files to configure the environment for your webapps.
Here's an example where we apply two different jetty.xml files:
....
> java -jar jetty-runner.jar --config jetty.xml --config jetty-https.xml simple.war
....
____
[NOTE]
Switches on the command line take precedence over those defined in configuration files, so you can use the command line as overrides.
____
===== Full configuration reference
You can see the fill set of configuration options using the --help switch:
....
> java -jar jetty-runner.jar --help
....
Here's what the output will look like:
[source,plain]
----
Usage: java [-Djetty.home=dir] -jar jetty-runner.jar [--help|--version] [ server opts] [[ context opts] context ...]
Server opts:
--version - display version and exit
--log file - request log filename (with optional 'yyyy_mm_dd' wildcard
--out file - info/warn/debug log filename (with optional 'yyyy_mm_dd' wildcard
--host name|ip - interface to listen on (default is all interfaces)
--port n - port to listen on (default 8080)
--stop-port n - port to listen for stop command
--stop-key n - security string for stop command (required if --stop-port is present)
[--jar file]*n - each tuple specifies an extra jar to be added to the classloader
[--lib dir]*n - each tuple specifies an extra directory of jars to be added to the classloader
[--classes dir]*n - each tuple specifies an extra directory of classes to be added to the classloader
--stats [unsecure|realm.properties] - enable stats gathering servlet context
[--config file]*n - each tuple specifies the name of a jetty xml config file to apply (in the order defined)
Context opts:
[[--path /path] context]*n - WAR file, web app dir or context xml file, optionally with a context path
----
Printing the version:::
Print out the version of jetty and then exit immediately.
+
....
> java -jar jetty-runner.jar --version
....
Configuring a request log:::
Cause jetty to write a request log with the given name.
If the file is prefixed with yyyy_mm_dd then the file will be automatically rolled over.
Note that for finer grained configuration of the link:{JDURL}/org/eclipse/jetty/server/NCSARequestLog.html[request log], you will need to use a jetty xml file instead.
+
....
> java -jar jetty-runner.jar --log yyyy_mm_dd-requests.log my.war
....
Configuring the output log:::
Redirect the output of jetty logging to the named file.
If the file is prefixed with yyyy_mm_dd then the file will be automatically rolled over.
+
....
> java -jar jetty-runner.jar --out yyyy_mm_dd-output.log my.war
....
Configuring the interface for http:::
Like jetty standalone, the default is for the connectors to listen on all interfaces on a machine.
You can control that by specifying the name or ip address of the particular interface you wish to use with the --host argument:
+
....
> java -jar jetty-runner.jar --host 192.168.22.19 my.war
....
Configuring the port for http:::
The default port number is 8080.
To link:#how-to-configure-connectors[configure a https connector], use a jetty xml config file instead.
+
....
> java -jar jetty-runner.jar --port 9090 my.war
....
Configuring stop:::
You can configure a port number for jetty to listen on for a stop command, so you are able to stop it from a different terminal.
This requires the use of a "secret" key, to prevent malicious or accidental termination.
Use the --stop-port and --stop-key parameters as arguments to the jetty-runner:
+
....
> java -jar jetty-runner.jar --stop-port 8181 --stop-key abc123
....
+
Then, to stop jetty from a different terminal, you need to supply the same port and key information.
For this you'll either need a local installation of jetty, the link:#jetty-maven-plugin[jetty-maven-plugin], the link:#jetty-ant[jetty-ant plugin], or write a custom class.
Here's how to use a jetty installation to perform a stop:
+
....
> java -jar start.jar --stop-port 8181 --stop-key abc123 --stop
....
Configuring the container classpath:::
With a local installation of jetty, you add jars and classes to the container's classpath by putting them in the $JETTY_HOME/lib directory.
With the jetty-runner, you can use the --lib, --jar and --classes arguments instead to achieve the same thing.
+
--lib adds the location of a directory which contains jars to add to the container classpath.
You can add 1 or more. Here's an example of configuring 2 directories:
+
....
> java -jar jetty-runner.jar --lib /usr/local/external/lib --lib $HOME/external-other/lib my.war
....
+
--jar adds a single jar file to the container classpath.
You can add 1 or more.
Here's an example of configuring 3 extra jars:
+
....
> java -jar jetty-runner.jar --jar /opt/stuff/jars/jar1.jar --jar $HOME/jars/jar2.jar --jar /usr/local/proj/jars/jar3.jar my.war
....
+
--classes add the location of a directory containing classes to add to the container classpath.
You can add 1 or more.
Here's an example of configuring a single extra classes dir:
+
....
> java -jar jetty-runner.jar --classes /opt/stuff/classes my.war
....
Gathering statistics:::
If statistics gathering is enabled, then they are viewable by surfing
to the context /stats. You may optionally protect access to that
context with a password. Here's an example of enabling statistics,
with no password protection:
+
....
> java -jar jetty-runner.jar --stats unsecure my.war
....
+
If we wished to protect access to the /stats context, we would provide the location of a jetty realm configuration file containing authentication and authorization information.
For example, we could use the following example realm file from the jetty distribution:
+
....
jetty: MD5:164c88b302622e17050af52c89945d44,user
admin: CRYPT:adpexzg3FUZAk,server-administrator,content-administrator,admin
other: OBF:1xmk1w261u9r1w1c1xmq,user
plain: plain,user
user: password,user
# This entry is for digest auth. The credential is a MD5 hash of username:realmname:password
digest: MD5:6e120743ad67abfbc385bc2bb754e297,user
....
+
Assuming we've copied it into the local directory, we would apply it like so
+
....
> java -jar jetty-runner.jar --stats realm.properties my.war
....
+
After surfing to http://localhost:8080/ a few times, we can surf to the stats servlet on http://localhost:8080/stats to see the output:
+
....
Statistics:
Statistics gathering started 1490627ms ago
Requests:
Total requests: 9
Active requests: 1
Max active requests: 1
Total requests time: 63
Mean request time: 7.875
Max request time: 26
Request time standard deviation: 8.349764752888037
Dispatches:
Total dispatched: 9
Active dispatched: 1
Max active dispatched: 1
Total dispatched time: 63
Mean dispatched time: 7.875
Max dispatched time: 26
Dispatched time standard deviation: 8.349764752888037
Total requests suspended: 0
Total requests expired: 0
Total requests resumed: 0
Responses:
1xx responses: 0
2xx responses: 7
3xx responses: 1
4xx responses: 0
5xx responses: 0
Bytes sent total: 1453
Connections:
org.eclipse.jetty.server.ServerConnector@203822411
Protocols:http/1.1
Statistics gathering started 1490606ms ago
Total connections: 7
Current connections open: 1
Max concurrent connections open: 2
Total connections duration: 72883
Mean connection duration: 12147.166666666666
Max connection duration: 65591
Connection duration standard deviation: 23912.40292977684
Total messages in: 7
Total messages out: 7
Memory:
Heap memory usage: 49194840 bytes
Non-heap memory usage: 12611696 bytes
....

View File

@ -0,0 +1,25 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[session-management]]
== Session Management
include::setting-session-characteristics.adoc[]
include::using-persistent-sessions.adoc[]
include::session-clustering-jdbc.adoc[]
include::session-clustering-mongodb.adoc[]
include::session-clustering-infinispan.adoc[]
include::session-clustering-gcloud-datastore.adoc[]

View File

@ -0,0 +1,219 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[session-clustering-gcloud-datastore]]
=== Session Clustering with Google Cloud Datastore
Jetty can support session clustering by persisting sessions to
https://cloud.google.com/datastore/docs/concepts/overview[Google Cloud
Datastore]. Each Jetty instance locally caches sessions for which it has
received requests, writing any changes to the session through to the
Datastore as the request exits the server. Sessions must obey the
Serialization contract, and servlets must call the
Session.setAttribute() method to ensure that changes are persisted.
The persistent session mechanism works in conjunction with a load
balancer that supports stickiness. Stickiness can be based on various
data items, such as source IP address or characteristics of the session
ID or a load-balancer specific mechanism. For those load balancers that
examine the session ID, the Jetty persistent session mechanism appends a
node ID to the session ID, which can be used for routing.
==== Configuration
There are two components to session management in Jetty: a session ID
manager and a session manager.
* The session ID manager ensures that session IDs are unique across all
webapps hosted on a Jetty instance, and thus there can only be one
session ID manager per Jetty instance.
* The session manager handles the session lifecycle
(create/update/invalidate/expire) on behalf of a web application, so
there is one session manager per web application instance.
These managers also cooperate and collaborate with the
`org.eclipse.jetty.server.session.SessionHandler` to enable
cross-context dispatch.
==== The gcloud-sessions Module
When using the jetty distribution, to enable Cloud Datastore session
persistence, you will first need to enable the `gcloud-sessions`
link:#startup-modules[module] for your link:#creating-jetty-base[base]
using the --add-to-start or --add-to-startd argument to the
link:#startup-overview[start.jar].
As part of the module installation, the necessary jars will be
dynamically downloaded and installed to your `${jetty.base}/lib/gcloud`
directory. If you need to up or downgrade the version of the jars, then
you can delete the jars that were automatically installed and replace
them. Once you've done that, you will need to prevent jetty's startup
checks from detecting the missing jars. To do that, you can use
`--skip-file-validation=glcoud-sessions` argument to start.jar on the
command line, or place that line inside `${jetty.base}/start.ini` to
ensure it is used for every start.
===== Configuring the GCloudSessionIdManager
The gcloud-sessions module will have installed file called
`${jetty.home}/etc/jetty-gcloud-sessions.xml`. This file configures an
instance of the GCloudSessionIdManager that will be shared across all
webapps deployed on that server. It looks like this:
[source,xml]
----
include::{SRCDIR}/jetty-gcloud/jetty-gcloud-session-manager/src/main/config/etc/jetty-gcloud-session-store.xml[]
----
You configure it by setting values for properties. The properties will
either be inserted as commented out in your `start.ini`, or your
`start.d/gcloud-sessions.ini` file, depending on how you enabled the
module.
The only property you always need to set is the name of the node in the
cluster:
jetty.gcloudSession.workerName::
The name that uniquely identifies this node in the cluster. This value
will also be used by the sticky load balancer to identify the node.
Don't forget to change the value of this property on *each* node on
which you enable gcloud datastore session clustering.
Which other properties you need to set depends on the execution
environment:
====== Running Within Google Infrastructure
When you upload your webapp to run in Compute Engine, you do not need to
set any other properties for jetty. If you follow the instructions in
the https://cloud.google.com/datastore/docs/activate[Cloud Datastore
documentation], all authorizations etc will be provided by the runtime
environment.
====== Running Externally to Google Infrastructure
When your app is executing outside of Google, you can either contact a
remote Cloud Datastore instance, or a
https://cloud.google.com/datastore/docs/tools/devserver[local test dev
server] provided by the sdk. The choice determines which properties you
need to set:
Contacting an sdk dev server for testing:::
In this case, you need to set up either some _System_ properties or
_environment variables_ - NOT jetty properties!
+
DATASTORE_DATASET;;
This must be the name of your (test) project.
DATASTORE_HOST;;
This is the url of the dev server as described at
https://cloud.google.com/datastore/docs/tools/devserver#setting_environment_variables.
An example may be "http://localhost:9999"
Contacting a remote Cloud Datastore:::
In this case, you need to provide all of the authentication and
authorization information explicitly via jetty properties in the ini
file:
+
jetty.gcloudSession.projectId;;
This is the name of your project.
jetty.gcloudSession.p12File;;
This is the location of the p12 key file that is associated with
your project.
jetty.gcloudSession.serviceAccount;;
This is the email address that defines your service account for the
Cloud Datastore.
jetty.gcloudSession.password;;
This is the password associated with the p12 key file.
===== Configuring the GCloudSessionManager
As mentioned elsewhere, there should be one GCloudSessionManager per
context (ie webapp). It will need to reference the single
GCloudSessionIdManager from which it derives the Cloud Datastore
configuration information.
The way you configure a GCloudSessionManager depends on whether you're
configuring from a context xml file or a `jetty-web.xml` file or code.
The basic difference is how you get a reference to the Jetty
`org.eclipse.jetty.server.Server` instance.
From a context xml file, you reference the Server instance as a Ref:
[source,xml]
----
<!-- Get a reference to the GCloudSessionIdManager -->
<Ref id="Server">
<Call id="idMgr" name="getSessionIdManager"/>
</Ref>
<!-- Use the GCloudSessionIdManager to set up the GCloudSessionManager -->
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New id="mgr" class="org.eclipse.jetty.gcloud.session.GCloudSessionManager">
<Set name="sessionIdManager">
<Ref id="idMgr"/>
</Set>
<Set name="scavengeIntervalSec">600</Set>
</New>
</Arg>
</New>
</Set>
----
From a `WEB-INF/jetty-web.xml` file, you can reference the Server
instance directly:
[source,xml]
----
<!-- Reference the server directly -->
<Get name="server">
<Get id="idMgr" name="sessionIdManager"/>
</Get>
<!-- Apply the SessionIdManager to the GCloudSessionManager -->
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New id="mgr" class="org.eclipse.jetty.gcloud.session.GCloudSessionManager">
<Set name="sessionIdManager">
<Ref id="idMgr"/>
</Set>
<Set name="scavengeIntervalSec">600</Set>
</New>
</Arg>
</New>
</Set>
----
The GCloudSessionManager supports the following configuration setters:
scavengeIntervalSec::
Time in seconds between runs of a scavenger task that looks for
expired old sessions to delete. The default is 10 minutes. If set to
0, no scavenging is done.
staleIntervalSec::
The length of time a session can be in memory without being checked
against the cluster. A value of 0 indicates that the session is never
checked against the cluster - the current node is considered to be the
master for the session.
maxQueryResults::
The maximum number of results to return for a query to find expired
sessions. For efficiency it is important to limit the size of the
result. The default is 100. If 0 or negative numbers are set, the
default is used instead.

View File

@ -0,0 +1,238 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[session-clustering-infinispan]]
=== Session Clustering with Infinispan
Jetty can support session clustering by persisting sessions to
http://www.infinispan.org[Infinispan]. Each Jetty instance locally
caches sessions for which it has received requests, writing any changes
to the session through to Infinispan as the request exits the server.
Sessions must obey the Serialization contract, and servlets must call
the Session.setAttribute() method to ensure that changes are persisted.
The persistent session mechanism works in conjunction with a load
balancer that supports stickiness. Stickiness can be based on various
data items, such as source IP address or characteristics of the session
ID or a load-balancer specific mechanism. For those load balancers that
examine the session ID, the Jetty persistent session mechanism appends a
node ID to the session ID, which can be used for routing.
==== Configuration
There are two components to session management in Jetty: a session ID
manager and a session manager.
* The session ID manager ensures that session IDs are unique across all
webapps hosted on a Jetty instance, and thus there can only be one
session ID manager per Jetty instance.
* The session manager handles the session lifecycle
(create/update/invalidate/expire) on behalf of a web application, so
there is one session manager per web application instance.
These managers also cooperate and collaborate with the
`org.eclipse.jetty.server.session.SessionHandler` to enable
cross-context dispatch.
==== The infinispan Module
When using the jetty distribution, to enable Infinispan session
persistence, you will first need to enable the `infinispan`
link:#startup-modules[module] for your link:#creating-jetty-base[base]
using the --add-to-start or --add-to-startd argument to the
link:#startup-overview[start.jar].
As part of the module installation, the necessary infinispan jars will
be dynamically downloaded and installed to your
`${jetty.base}/lib/infinispan` directory. If you need to up or downgrade
the version of the infinispan jars, then you can delete the jars that
were automatically installed and replace them. Once you've done that,
you will need to prevent jetty's startup checks from detecting the
missing jars. To do that, you can use
`--skip-file-validation=infinispan` argument to start.jar on the command
line, or place that line inside `${jetty.base}/start.ini` to ensure it
is used for every start.
You will also find the following properties, either in your base's
`start.d/infinispan.ini` file or appended to your `start.ini`, depending
on how you enabled the module:
....
## Unique identifier for this node in the cluster
jetty.infinispanSession.workerName=node1
....
jetty.infinispanSession.workerName::
The name that uniquely identifies this node in the cluster. This value
will also be used by the sticky load balancer to identify the node.
Don't forget to change the value of this property on *each* node on
which you enable infinispan session clustering.
These properties are applied to the InfinispanSessionIdManager described
below.
===== Configuring the InfinispanSessionIdManager
The infinispan module will have installed file called
$\{jetty.home}/etc/jetty-infinispan.xml. This file configures an
instance of the InfinispanSessionIdManager that will be shared across
all webapps deployed on that server. It looks like this:
[source,xml]
----
include::{SRCDIR}/jetty-infinispan/src/main/config/etc/jetty-default-infinispan-store.xml[]
----
As you can see, you configure the Infinispan
http://infinispan.org/docs/7.1.x/user_guide/user_guide.html#_the_cache_apis[Cache]
instance that the InfinispanSessionIdManager should use in this file. By
default, the infinispan
http://infinispan.org/docs/7.1.x/getting_started/getting_started.html#_running_infinispan_on_a_single_node[Default
cache] instance is used (ie on the local node). You can instead use a
custom Cache setup - the jetty-infinispan.xml file shows you how to
configure a remote Cache (using the
http://infinispan.org/docs/7.1.x/user_guide/user_guide.html#_using_hot_rod_server[hotrod
java client]).
The InfinispanSessionIdManager can be configured by calling setters:
idleExpiryMultiple::
Sessions that are not immortal, ie they have an expiry time, have
their ids stored into Infinispan with an
http://infinispan.org/docs/7.1.x/user_guide/user_guide.html#_expiration[idle
expiry timeout] equivalent to double the session's timeout. This
should be sufficient to ensure that a session id that is in-use by a
session is never accidentally removed. However, should you wish to,
you can configure this to any integral value to effectively increase
the
http://infinispan.org/docs/7.1.x/user_guide/user_guide.html#_expiration[idle
expiry] timeout.
===== Configuring the InfinispanSessionManager
As mentioned elsewhere, there should be one InfinispanSessionManager per
context (ie webapp). It will need to reference the single
InfinispanSessionIdManager configured previously for the Server.
The way you configure a InfinispanSessionManager depends on whether
you're configuring from a context xml file or a `jetty-web.xml` file or
code. The basic difference is how you get a reference to the Jetty
`org.eclipse.jetty.server.Server` instance.
From a context xml file, you reference the Server instance as a Ref:
[source,xml]
----
<!-- Expose the jetty infinispan classes for session serialization -->
<Call name="prependServerClass">
<Arg>-org.eclipse.jetty.session.infinispan.</Arg>
</Call>
<!-- Get a reference to the InfinispanSessionIdManager -->
<Ref id="Server">
<Call id="idMgr" name="getSessionIdManager"/>
</Ref>
<!-- Get a referencee to the Cache from the InfinispanSessionIdManager -->
<Ref id="idMgr">
<Get id="cache" name="cache"/>
</Ref>
<!-- Use the InfinispanSessionIdManager and Cache to setup up the InfinispanSessionManager -->
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New id="mgr" class="org.eclipse.jetty.session.infinispan.InfinispanSessionManager">
<Set name="sessionIdManager">
<Ref id="idMgr"/>
</Set>
<Set name="cache">
<Ref id="cache">
</Ref>
</Set>
<Set name="scavengeInterval">60</Set>
</New>
</Arg>
</New>
</Set>
----
From a `WEB-INF/jetty-web.xml` file, you can reference the Server
instance directly:
[source,xml]
----
<!-- Expose the jetty infinispan classes for session serialization -->
<Call name="prependServerClass">
<Arg>-org.eclipse.jetty.session.infinispan.</Arg>
</Call>
<!-- Reference the server directly -->
<Get name="server">
<Get id="idMgr" name="sessionIdManager"/>
</Get>
<!-- Get a reference to the Cache via the InfinispanSessionIdManager -->
<Ref id="idMgr">
<Get id="cache" name="cache"/>
</Ref>
<!-- Apply the SessionIdManager and Cache to the InfinispanSessionManager -->
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New id="mgr" class="org.eclipse.jetty.session.infinispan.InfinispanSessionManager">
<Set name="sessionIdManager">
<Ref id="idMgr"/>
</Set>
<Set name="cache">
<Ref id="cache">
</Ref>
</Set>
<Set name="scavengeInterval">600</Set>
</New>
</Arg>
</New>
</Set>
----
The InfinispanSessionManager can be provided by calling setters:
scavengeInterval::
Time in seconds between runs of a scavenger task that looks for
expired old sessions to delete. The default is 10 minutes.
staleIntervalSec::
The length of time a session can be in memory without being checked
against the cluster. A value of 0 indicates that the session is never
checked against the cluster - the current node is considered to be the
master for the session.
===== Using HotRod
If you're using the hotrod client - where serialization will be required
- you will need to ensure that the hotrod marshalling software works
with jetty classloading. To do this, firstly ensure that you have
included the lines containing the `prependServerClass` to your context
xml file as shown above.
Then, create the file
`${jetty.base}/resources/hotrod-client.properties`. Add the following
line to this file:
....
infinispan.client.hotrod.marshaller=org.eclipse.jetty.session.infinispan.WebAppMarshaller
....

View File

@ -0,0 +1,271 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[session-clustering-jdbc]]
=== Session Clustering with a Database
Jetty can support session clustering by persisting sessions to a shared
database. Each Jetty instance locally caches sessions for which it has
received requests, writing any changes to the session through to the
database as the request exits the server. Sessions must obey the
Serialization contract, and servlets must call the
Session.setAttribute() method to ensure that changes are persisted.
The persistent session mechanism works in conjunction with a load
balancer that supports stickiness. Stickiness can be based on various
data items, such as source IP address or characteristics of the session
ID or a load-balancer specific mechanism. For those load balancers that
examine the session ID, the Jetty persistent session mechanism appends a
node ID to the session ID, which can be used for routing.
In this type of solution, the database can become both a bottleneck and
a single point of failure. Jetty takes steps to reduce the load on the
database (discussed below), but in a heavily loaded environment you
might need to investigate other optimization strategies such as local
caching and database replication. You should also consult your database
vendor's documentation for information on how to ensure high
availability and failover of your database.
==== Configuration
There are two components to session management in Jetty: a session ID
manager and a session manager.
* The session ID manager ensures that session IDs are unique across all
webapps hosted on a Jetty instance, and thus there can only be one
session ID manager per Jetty instance.
* The session manager handles the session lifecycle
(create/update/invalidate/expire) on behalf of a web application, so
there is one session manager per web application instance.
These managers also cooperate and collaborate with the
`org.eclipse.jetty.server.session.SessionHandler` to enable
cross-context dispatch.
==== The jdbc-session Module
When using the jetty distribution, to enable jdbc session persistence,
you will first need to enable the jdbc-session
link:#startup-modules[module] for your link:#creating-jetty-base[base]
using the --add-to-start or --add-to-startd argument to the
link:#startup-overview[start.jar].
You will also find the following properties, either in your base's
start.d/jdbc-session.ini file or appended to your start.ini, depending
on how you enabled the module:
....
## Unique identifier for this node in the cluster
jetty.jdbcSession.workerName=node1
##Uncomment either the datasource name or driverClass and connectionURL
#jetty.jdbcSession.datasource=sessions
jetty.jdbcSession.driverClass=org.apache.derby.jdbc.EmbeddedDriver
jetty.jdbcSession.connectionURL=jdbc:derby:sessions;create=true
....
jetty.jdbcSession.workerName::
The name that uniquely identifies this node in the cluster. This value
will also be used by the sticky load balancer to identify the node.
Don't forget to change the value of this property on *each* node on
which you enable jdbc session clustering.
jetty.jdbcSession.scavenge::
The time in seconds between sweeps of a task which scavenges old
expired sessions. The default is 10 mins. We don't recommend you
increase the frequency bcause doing so increases the load on the
database with very little gain.
jetty.jdbcSession.datasource::
The name of a javax.sql.DataSource that gives access to the database
that holds the session information. You should configure *either* this
or the jdbc driver information described next.
jetty.jdbcSession.datasource and jetty.jdbcSession.connectionURL::
This is the name of the jdbc driver class, and a jdbc connection url
suitable for that driver. You should configure *either* this or the
jdbc datasource name described above.
These properties are applied to the JDBCSessionIdManager described
below.
===== Configuring the JDBCSessionIdManager
The jdbc-session module will have installed file called
$\{jetty.home}/etc/jetty-jdbc-sessions.xml. This file configures an
instance of the JDBCSessionIdManager that will be shared across all
webapps deployed on that server. It looks like this:
[source,xml]
----
include::{SRCDIR}/jetty-server/src/main/config/etc/jetty-jdbc-session-store.xml[]
----
As well as uncommenting and setting up appropriate values for the
properties we discussed above, you will also need to edit this file and
uncomment *either* the datasource or the driver info elements.
As Jetty configuration files are direct mappings of XML to Java, it is
straightforward to see how to do this in code, but here's an example
anyway:
[source,java]
----
Server server = new Server();
...
JDBCSessionIdManager idMgr = new JDBCSessionIdManager(server);
idMgr.setWorkerName("node1");
idMgr.setDriverInfo("com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/sessions?user=janb");
idMgr.setScavengeInterval(600);
server.setSessionIdManager(idMgr);
----
====== Configuring the Database Schema
You may find it necessary to change the names of the tables and columns
that the JDBC Session management uses to store the session information.
The defaults used are:
.Default Values for Session Id Table
[cols=",",]
|===========================
|table name |JettySessionIds
|columns |id
|===========================
.Default Values for Session Table
[cols=",",]
|=======================================================================
|table name |JettySessions
|columns |rowId, sessionId, contextPath, virtualHost, lastNode,
accessTime, lastAccessTime, createTime, cookieTime, lastSavedTime,
expiryTime, maxInterval, map
|=======================================================================
To change these values, use the
link:{JDURL}/org/eclipse/jetty/server/session/SessionIdTableSchema.html[org.eclipse.jetty.server.session.SessionIdTableSchema]
and
link:{JDURL}/org/eclipse/jetty/server/session/SessionTableSchema.html[org.eclipse.jetty.server.session.SessionTableSchema]
classes. These classes have getter/setter methods for the table name and
all columns.
Here's an example of changing the name of JettySessionsId table and its
single column. This example will use java code, but as explained above,
you may also do this via a jetty xml configuration file:
[source,java]
----
JDBCSessionIdManager idManager = new JDBCSessionIdManager(server);
SessionIdTableSchema idTableSchema = new SessionIdTableSchema();
idTableSchema.setTableName("mysessionids");
idTableSchema.setIdColumn("theid");
idManager.setSessionIdTableSchema(idTableSchema);
----
In a similar fashion, you can change the names of the table and columns
for the JettySessions table. *Note* that both the SessionIdTableSchema
and the SessionTableSchema instances are set on the JDBCSessionIdManager
class.
[source,java]
----
JDBCSessionIdManager idManager = new JDBCSessionIdManager(server);
SessionTableSchema sessionTableSchema = new SessionTableSchema();
sessionTableSchema.setTableName("mysessions");
sessionTableSchema.setIdColumn("mysessionid");
sessionTableSchema.setAccessTimeColumn("atime");
sessionTableSchema.setContextPathColumn("cpath");
sessionTableSchema.setCookieTimeColumn("cooktime");
sessionTableSchema.setCreateTimeColumn("ctime");
sessionTableSchema.setExpiryTimeColumn("extime");
sessionTableSchema.setLastAccessTimeColumn("latime");
sessionTableSchema.setLastNodeColumn("lnode");
sessionTableSchema.setLastSavedTimeColumn("lstime");
sessionTableSchema.setMapColumn("mo");
sessionTableSchema.setMaxIntervalColumn("mi");
idManager.setSessionTableSchema(sessionTableSchema);
----
===== Configuring the JDBCSessionManager
As mentioned elsewhere, there should be one JDBCSessionManager per
context (ie webapp). It will need to reference the single
JDBCSessionIdManager configured previously for the Server.
The way you configure a JDBCSessionManager depends on whether you're
configuring from a context xml file or a `jetty-web.xml` file or code.
The basic difference is how you get a reference to the Jetty
`org.eclipse.jetty.server.Server` instance.
From a context xml file, you reference the Server instance as a Ref:
[source,xml]
----
<Ref id="Server">
<Call id="idMgr" name="getSessionIdManager"/>
</Ref>
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New id="jdbcmgr" class="org.eclipse.jetty.server.session.JDBCSessionManager">
<Set name="sessionIdManager">
<Ref id="idMgr"/>
</Set>
</New>
</Arg>
</New>
</Set>
----
From a `WEB-INF/jetty-web.xml` file, you can reference the Server
instance directly:
[source,xml]
----
<Get name="server">
<Get id="idMgr" name="sessionIdManager"/>
</Get>
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New class="org.eclipse.jetty.server.session.JDBCSessionManager">
<Set name="sessionIdManager">
<Ref id="idMgr"/>
</Set>
</New>
</Arg>
</New>
</Set>
----
If you're embedding this in code:
[source,java]
----
//assuming you have already set up the JDBCSessionIdManager as shown earlier
//and have a reference to the Server instance:
WebAppContext wac = new WebAppContext();
... //configure your webapp context
JDBCSessionManager jdbcMgr = new JDBCSessionManager();
jdbcMgr.setSessionIdManager(server.getSessionIdManager());
SessionHandler sessionHandler = new SessionHandler(jdbcMgr);
wac.setSessionHandler(sessionHandler);
----

View File

@ -0,0 +1,300 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[session-clustering-mongodb]]
=== Session Clustering with MongoDB
Jetty can support session clustering by persisting sessions into
http://www.mogodb.org[MongoDB]. Each Jetty instance locally caches
sessions for which it has received requests, writing any changes to the
session through to the cluster as the request exits the server. Sessions
must obey the Serialization contract, and servlets must call the
Session.setAttribute() method to ensure that changes are persisted.
The session persistence mechanism works in conjunction with a load
balancer that supports stickiness. Stickiness can be based on various
data items, such as source IP address or characteristics of the session
ID or a load-balancer specific mechanism. For those load balancers that
examine the session ID, the Jetty persistent session mechanism appends a
node ID to the session ID, which can be used for routing.
In this type of solution, the traffic on the network needs to be
carefully watched and tends to be the bottleneck. You are probably
investigating this solution in order to scale to large amount of users
and sessions, so careful attention should be paid to your usage
scenario. Applications with a heavy write profile to their sessions will
consume more network bandwidth than profiles that are predominately read
oriented. We recommend using this session manager with largely read
based session scenarios.
==== Configuration
There are two components to session management in Jetty: a session ID
manager and a session manager.
* The session ID manager ensures that session IDs are unique across all
webapps hosted on a Jetty instance, and thus there should only be one
session ID manager per Jetty instance.
* The session manager handles the session lifecycle
(create/update/invalidate/expire) on behalf of a web application, so
there is one session manager per web application instance.
These managers also cooperate and collaborate with the
`org.eclipse.jetty.server.session.SessionHandler` to enable
cross-context dispatch.
==== The nosql Module
When using the jetty distribution, to enable the mongodb session
persistence mechanism, you will first need to enable the nosql
link:#startup-modules[module] for your link:#creating-jetty-base[base]
using the --add-to-start or --add-to-startd argument to the
link:#startup-overview[start.jar]. This module will automatically
download the mongodb-java-driver and install it to your base's lib/nosql
directory.
As part of the module installation, the necessary mongo java driver jars
will be dynamically downloaded and installed to your
`${jetty.base}/lib/nosql` directory. If you need to up or downgrade the
version of these jars, then you can delete the jars that were
automatically installed and replace them. Once you've done that, you
will need to prevent jetty's startup checks from detecting the missing
jars. To do that, you can use `--skip-file-validation=nosql` argument to
start.jar on the command line, or place that line inside
`${jetty.base}/start.ini` to ensure it is used for every start.
You will also find the following properties, either in your base's
start.d/nosql.ini file or appended to your start.ini, depending on how
you enabled the module:
....
## Unique identifier for this node in the cluster
jetty.nosqlSession.workerName=node1
## Interval in seconds between scavenging expired sessions
jetty.nosqlSession.scavenge=1800
....
The `jetty.nosqlSession.workerName` is the unique name for this jetty
Server instance. It will be used by the sticky load balancer to uniquely
identify the node. You should change this value on *each* node to which
you install mongodb session management.
The `jetty.nosqlSession.scavenge` property defines the time in seconds
between runs of the scavengeer: the scavenger is a task which runs
periodically to clean out sessions that have expired but become stranded
in the database for whatever reason.
These properties are substituted into the configuration of the
MongoDBSessionIdManager and MongoSessionManager.
===== Configuring the MongoSessionIdManager
The nosql module will have installed file called
$\{jetty.home}/etc/jetty-nosql.xml. This file configures an instance of
the MongoSessionIdManager that will be shared across all webapps
deployed on that server. It looks like this:
[source,xml]
----
include::{SRCDIR}/jetty-nosql/src/main/config/etc/jetty-mongo-session-store.xml[]
----
The MongoSessionIdManager needs access to a mongodb cluster, and the
jetty-nosql.xml file assumes the defaults of localhost and default
mongodb port. If you need to configure something else, you will need to
edit this file. Here's an example of a more complex setup to use a
remote mongodb instance:
[source,xml]
----
<New id="mongodb" class="com.mongodb.Mongo">
<Arg>
<New class="java.util.ArrayList">
<Call name="add">
<Arg>
<New class="com.mongodb.ServerAddress">
<Arg type="java.lang.String">foo.example.com</Arg>
<Arg type="int">27017</Arg>
</New>
</Arg>
</Call>
<!-- Add more Call statements here as desired --> </New>
</Arg>
<Call name="getDB">
<Arg>HttpSessions</Arg>
<Call id="sessionDocument" name="getCollection">
<Arg>sessions</Arg>
</Call>
</Call>
<!-- If you want to configure Jetty to be able to read through the slaves, call the following: -->
<Call name="slaveOk"/>
</New>
<Set name="sessionIdManager">
<New id="mongoIdMgr" class="org.eclipse.jetty.nosql.mongodb.MongoSessionIdManager">
<Arg>
<Ref id="Server"/>
</Arg>
<Arg>
<Ref id="sessionDocument"/>
</Arg>
<Set name="workerName"><Property name="jetty.nosqlSession.workerName" default="node1"/></Set>
<Set name="scavengePeriod"><Property name="jetty.nosqlSession.scavenge" default="1800"/></Set>
</New>
</Set>
----
As Jetty configuration files are direct mappings of XML to Java, it is
straightforward to see how to do this in code, but here's an example
anyway:
[source,java]
----
Server server = new Server();
...
MongoSessionIdManager idMgr = newMongoSessionIdManager(server);
idMgr.setWorkerName("node1");
idMgr.setScavengePeriod(1800);
server.setSessionIdManager(idMgr);
----
The MongoSessionIdManager has slightly different options than some of
our more traditional session options. The MongoDBSessionIdManager has
the same scavenge timers which govern the setting of a valid session to
invalid after a certain period of inactivity. New to this session id
manager is the extra purge setting which governs removal from the
mongodb cluster. This can be configured through the 'purge' option.
Purge is by default set to true and by default runs daily for each node
on the cluster. Also able to be configured is the age in which an
invalid session will be retained which is set to 1 day by default. This
means that invalid sessions will be removed after lingering in the
mongodb instance for a day. There is also an option for purging valid
sessions that have not been used recently. The default time for this is
1 week. You can disable these behaviors by setting purge to false.
scavengeDelay::
How long to delay before periodically looking for sessions to
scavenge?
scavengePeriod::
How much time after a scavenge has completed should you wait before
doing it again?
scavengeBlockSize::
Number of session ids to which to limit each scavenge query. If you
have a very large number of sessions in memory then setting this to a
non 0 value may help speed up scavenging by breaking the scavenge into
multiple, queries. The default is 0, which means that all session ids
are considered in a single query.
purge (Boolean)::
Do you want to purge (delete) sessions that are invalid from the
session store completely?
purgeDelay::
How often do you want to perform this purge operation?
purgeInvalidAge::
How old should an invalid session be before it is eligible to be
purged?
purgeValidAge::
How old should a valid session be before it is eligible to be marked
invalid and purged? Should this occur at all?
purgeLimit::
Integer value that represents how many items to return from a purge
query. The default is 0, which is unlimited. If you have a lot of old
expired orphaned sessions then setting this value may speed up the
purge process.
preserveOnStop::
Whether or not to retain all sessions when the session manager stops.
Default is `true`.
===== Configuring a MongoSessionManager
As mentioned elsewhere, there should be one MongoSessionManager per
context (ie webapp). It will need to reference the single
MongoSessionIdManager configured previously for the Server.
The way you configure a
link:{JDURL}/org/eclipse/jetty/nosql/MongoSessionManager.html[org.eclipse.jetty.nosql.mongodb.MongoSessionManager]
depends on whether you're configuring from a
link:#deployable-descriptor-file[context xml] file or a
link:#jetty-web-xml-config[jetty-web.xml] file or code. The basic
difference is how you get a reference to the Jetty
`org.eclipse.jetty.server.Server` instance.
From a context xml file, you reference the Server instance as a Ref:
[source,xml]
----
<Ref name="Server" id="Server">
<Call id="mongoIdMgr" name="getSessionIdManager"/>
</Ref>
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New id="mongoMgr" class="org.eclipse.jetty.nosql.mongodb.MongoSessionManager">
<Set name="sessionIdManager">
<Ref id="mongoIdMgr"/>
</Set>
</New>
</Arg>
</New>
</Set>
----
From a `WEB-INF/jetty-web.xml` file, you can reference the Server
instance directly:
[source,xml]
----
<Get name="server">
<Get id="mongoIdMgr" name="sessionIdManager"/>
</Get>
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New class="org.eclipse.jetty.nosql.mongodb.MongoSessionManager">
<Set name="sessionIdManager">
<Ref id="mongoIdMgr"/>
</Set>
</New>
</Arg>
</New>
</Set>
----
If you're embedding this in code:
[source,java]
----
//assuming you have already set up the MongoSessionIdManager as shown earlier
//and have a reference to the Server instance:
WebAppContext wac = new WebAppContext();
... //configure your webapp context
MongoSessionManager mongoMgr = new MongoSessionManager();
mongoMgr.setSessionIdManager(server.getSessionIdManager());
wac.setSessionHandler(new SessionHandler(mongoMgr));
----

View File

@ -0,0 +1,295 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[setting-session-characteristics]]
=== Setting Session Characteristics
To modify the session characteristics of a web application, you can use
the following parameters, applying them as in one of the example
configurations:
[[using-init-parameters]]
==== Using Init Parameters
Use these parameters to set session characteristics.
.Init Parameters
[cols=",,",options="header",]
|=======================================================================
|Context Parameter |Default Value |Description
|org.eclipse.jetty.servlet.SessionCookie |JSESSIONID |Session cookie
name defaults to JSESSIONID, but can be set for a particular webapp with
this context param.
|org.eclipse.jetty.servlet.SessionIdPathParameterName |jsessionid
|Session URL parameter name. Defaults to jsessionid, but can be set for
a particular webapp with this context param. Set to "none" to disable
URL rewriting.
|org.eclipse.jetty.servlet.SessionDomain |- |Session Domain. If this
property is set as a ServletContext param, then it is used as the domain
for session cookies.If it is not set, then no domain is specified for
the session cookie.
|org.eclipse.jetty.servlet.SessionPath |- |Session Path. If this
property is set as a ServletContext param, then it is used as the path
for the session cookie. If it is not set, then the context path is used
as the path for the cookie.
|org.eclipse.jetty.servlet.MaxAge |-1 |Session Max Age. If this property
is set as a ServletContext param, then it is used as the max age for the
session cookie. If it is not set, then a max age of -1 is used.
|org.eclipse.jetty.servlet.CheckingRemoteSessionIdEncoding |false |If
true, Jetty will add JSESSIONID parameter even when encoding external
urls with calls to encodeURL(). False by default.
|=======================================================================
[[applying-init-parameters]]
===== Applying Init Parameters
The following sections provide examples of how to apply the init
parameters.
[[context-parameter-example]]
====== Context Parameter Example
You can set these parameters as context parameters in a web
application's ` WEB-INF/web.xml` file:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
...
<context-param>
<param-name>org.eclipse.jetty.servlet.SessionCookie</param-name>
<param-value>XSESSIONID</param-value>
</context-param>
<context-param>
<param-name>org.eclipse.jetty.servlet.SessionIdPathParameterName</param-name>
<param-value>xsessionid</param-value>
</context-param>
...
</web-app>
----
[[web-application-examples]]
====== Web Application Examples
You can configure init parameters on a web application, either in code,
or in a Jetty context xml file equivalent:
[source,xml]
----
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/test</Set>
<Set name="war"><SystemProperty name="jetty.home" default="."/>/webapps/test</Set>
...
<Call name="setInitParameter">
<Arg>org.eclipse.jetty.servlet.SessionCookie</Arg>
<Arg>XSESSIONID</Arg>
</Call>
<Call name="setInitParameter">
<Arg>org.eclipse.jetty.servlet.SessionIdPathParameterName</Arg>
<Arg>xsessionid</Arg>
</Call>
</Configure>
----
[[init-parameter-examples]]
====== SessionManager Examples
You can configure init parameters directly on a `SessionManager`
instance, either in code or the equivalent in xml:
[source,xml]
----
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/test</Set>
<Set name="war"><SystemProperty name="jetty.home" default="."/>/webapps/test</Set>
...
<Get name="sessionHandler">
<Set name="sessionManager">
<New class="org.eclipse.jetty.server.session.HashSessionManager">
<Set name="sessionCookie">XSESSIONID</Set>
<Set name="sessionIdPathParameterName">xsessionid</Set>
</New>
</Set>
</Get>
</Configure>
----
==== Using Servlet 3.0 Session Configuration
With the advent of http://jcp.org/en/jsr/detail?id=315[Servlet
Specification 3.0] there are new APIs for configuring session handling
characteristics. What was achievable before only via jetty-specific
link:#session-init-params[init-parameters] can now be achieved in a
container-agostic manner either in code, or via web.xml.
[[session-cookie-configuration]]
===== SessionCookieConfiguration
The
http://docs.oracle.com/javaee/6/api/javax/servlet/SessionCookieConfig.html[javax.servlet.SessionCookieConfig]
class can be used to set up session handling characteristics. For full
details, consult the
http://docs.oracle.com/javaee/6/api/javax/servlet/SessionCookieConfig.html[javadoc].
Here's an example of how you use it: this is a ServletContextListener
that retrieves the SessionCookieConfig and sets up some new values for
it when the context is being initialized:
[source,java]
----
import javax.servlet.SessionCookieConfig;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TestListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent sce)
{
String comment = "This is my special cookie configuration";
String domain = "foo.com";
String path = "/my/special/path";
boolean isSecure = true;
boolean httpOnly = false;
int maxAge = 30000;
String cookieName = "FOO_SESSION";
SessionCookieConfig scf = sce.getServletContext().getSessionCookieConfig();
scf.setComment(comment);
scf.setDomain(domain);
scf.setHttpOnly(httpOnly);
scf.setMaxAge(maxAge);
scf.setPath(path);
scf.setSecure(isSecure);
scf.setName(cookieName);
}
public void contextDestroyed(ServletContextEvent sce)
{
}
}
----
You can also use web.xml to configure the session handling
characteristics instead: here's an example, doing exactly the same as we
did above in code:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true"
version="3.0">
<session-config>
<cookie-config>
<comment>This is my special cookie configuration</comment>
<domain>foo.com</domain>
<http-only>false</http-only>
<max-age>30000</max-age>
<path>/my/special/path</path>
<secure>true</secure>
<name>FOO_SESSION</name>
</cookie-config>
</session-config>
</web-app>
----
[[session-tracking-modes]]
===== SessionTrackingModes
In addition to the configuration of
link:#session-cookie-configuration[session cookies], since Servlet 3.0
you can also use the
http://docs.oracle.com/javaee/6/api/javax/servlet/SessionTrackingMode.html[javax.servlet.SessionTrackingMode]
to configure session tracking.
To determine what are the _default_ session tracking characteristics
used by the container, call:
[source,java]
----
javax.servlet.SessionContext.getDefaultSessionTrackingModes();
----
This returns a java.util.Set of javax.servlet.SessionTrackingMode. The
_default_ session tracking modes for Jetty are:
* http://docs.oracle.com/javaee/6/api/javax/servlet/SessionTrackingMode.html#COOKIE[SessionTrackingMode.COOKIE]
* http://docs.oracle.com/javaee/6/api/javax/servlet/SessionTrackingMode.html#URL[SessionTrackingMode.URL]
To see which session tracking modes are actually in effect for this
Context, the following call returns a java.util.Set of
javax.servlet.SessionTrackingMode:
....
javax.servlet.SessionContext.getEffectiveSessionTrackingModes();
....
To change the session tracking modes, call:
[source,java]
----
javax.servlet.SessionContext.setSessionTrackingModes(Set<SessionTrackingMode>);
----
You may also set the tracking mode in web.xml, eg:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true"
version="3.0">
<session-config>
<tracking-mode>URL</tracking-mode>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
</web-app>
----

View File

@ -0,0 +1,125 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[using-persistent-sessions]]
=== Using Persistent Sessions
It is sometimes useful to preserve existing Sessions across restarts of
Jetty. The
link:{JDURL}/org/eclipse/jetty/server/session/HashSessionManager.html[`HashSessionManager`]
supports this feature. If you enable persistence, the
`HashSessionManager` saves all existing, valid Sessions to disk before
shutdown completes. On restart, Jetty restores the saved Sessions.
[[enabling-persistence]]
==== Enabling Persistence
A SessionManager does just what its name suggestsit manages the
lifecycle and state of sessions on behalf of a webapp. Each webapp must
have its own unique SessionManager instance. Enabling persistence is as
simple as configuring the `HashSessionManager` as the SessionManager for
a webapp and telling it where on disk to store the sessions:
[source,xml]
----
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
.
.
.
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New class="org.eclipse.jetty.server.session.HashSessionManager">
<Set name="storeDirectory">your/chosen/directory/goes/here</Set>
</New>
</Arg>
</New>
</Set>
.
.
.
</Configure>
----
____
[TIP]
If you want to persist the sessions from multiple webapps:
1. Configure a separate HashSessionManager for each.
2. Assign to each a different value for 'storeDirectory'.
____
The above example uses a configuration file suitable for the
link:{JDURL}/org/eclipse/jetty/deploy/providers/ContextProvider.html[ContextProvider],
thus you might want to check out xref:using-context-provider[].
[[delaying-session-load]]
==== Delaying Session Load
You might need to ensure that the sessions are loaded AFTER the servlet
environment starts up (by default, Jetty eagerly loads sessions as part
of the container startup, but before it initializes the servlet
environment). For example, the Wicket web framework requires the servlet
environment to be available when sessions are activated.
Using `SessionManager.setLazyLoad(true)`, Jetty loads sessions lazily
either when it receives the first request for a session, or the session
scavenger runs for the first time, whichever happens first. Here's how
the configuration looks in XML:
[source,xml]
----
<Set name="sessionHandler">
<New class="org.eclipse.jetty.server.session.SessionHandler">
<Arg>
<New class="org.eclipse.jetty.server.session.HashSessionManager">
<Set name="lazyLoad">true</Set>
</New>
</Arg>
</New>
</Set>
----
[[enabling-persistence-for-jetty-maven-plugin]]
==== Enabling Persistence for the Jetty Maven Plugin
To enable session persistence for the Jetty Maven plugin, set up the
HashSessionManager in the configuration section like so:
[source,xml]
----
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.0.0.RC2 (or current version)</version>
<configuration>
<!-- ... -->
<webAppConfig implementation="org.eclipse.jetty.maven.plugin.JettyWebAppContext">
<defaultsDescriptor>${project.build.outputDirectory}/META-INF/webdefault.xml</defaultsDescriptor>
<contextPath>${jetty.contextRoot}</contextPath>
<sessionHandler implementation="org.eclipse.jetty.server.session.SessionHandler">
<sessionManager implementation="org.eclipse.jetty.server.session.HashSessionManager">
<storeDirectory>${project.basedir}/target/jetty-sessions</storeDirectory>
<idleSavePeriod>1</idleSavePeriod>
</sessionManager>
</sessionHandler>
</webAppConfig>
<!-- ... -->
</configuration>
</plugin>
----

View File

@ -0,0 +1,27 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup]]
== Starting Jetty
include::startup-overview.adoc[]
include::startup-xml-config.adoc[]
include::startup-classpath.adoc[]
include::startup-modules.adoc[]
include::startup-base-vs-home.adoc[]
include::start-jar.adoc[]
include::startup-unix-service.adoc[]
include::startup-windows-service.adoc[]

View File

@ -0,0 +1,254 @@
/*
* GraphViz Graph of Jetty Modules
*
* Jetty: http://eclipse.org/jetty/
* GraphViz: http://graphviz.org/
*
* To Generate Graph image using graphviz:
* $ dot -Tpng -Goverlap=false -o modules-9.png modules-9.3.dot
*/
digraph modules {
node [color=gray, style=filled, shape=rectangle];
node [fontname="Verdana", size="20,20"];
graph [
concentrate=false,
fontname="Verdana",
fontsize = 20,
rankdir = LR,
ranksep = 1.5,
nodesep = .5,
style = bold,
labeljust = l,
label = "Jetty Modules",
ssize = "20,40"
];
/* Modules */
node [ labeljust = l ];
/* Level 0 */
{ rank = same;
"server" [ color="#66FFCC" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>server</B></TD></TR>
</TABLE>>];
"ext" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>ext</B></TD></TR>
</TABLE>>];
"jvm" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jvm</B></TD></TR>
</TABLE>>];
"apache-jstl" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>apache-jstl</B></TD></TR>
</TABLE>>];
"client" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>client</B></TD></TR>
</TABLE>>];
"logging" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>logging</B></TD></TR>
</TABLE>>];
"resources" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>resources</B></TD></TR>
</TABLE>>];
"apache-jsp" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>apache-jsp</B></TD></TR>
</TABLE>>];
"protonego-boot" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>protonego-boot</B></TD></TR>
</TABLE>>];
}
/* Level 1 */
{ rank = same;
"requestlog" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>requestlog</B></TD></TR>
</TABLE>>];
"servlet" [ color="#66FFCC" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>servlet</B></TD></TR>
</TABLE>>];
"gzip" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>gzip</B></TD></TR>
</TABLE>>];
"monitor" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>monitor</B></TD></TR>
</TABLE>>];
"rewrite" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>rewrite</B></TD></TR>
</TABLE>>];
"ssl" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>ssl</B></TD></TR>
</TABLE>>];
"security" [ color="#66FFCC" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>security</B></TD></TR>
</TABLE>>];
"setuid" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>setuid</B></TD></TR>
</TABLE>>];
"spring" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>spring</B></TD></TR>
</TABLE>>];
"stats" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>stats</B></TD></TR>
</TABLE>>];
"jmx" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jmx</B></TD></TR>
</TABLE>>];
"http" [ color="#66FFCC" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>http</B></TD></TR>
</TABLE>>];
"debuglog" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>debuglog</B></TD></TR>
</TABLE>>];
"ipaccess" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>ipaccess</B></TD></TR>
</TABLE>>];
"jaas" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jaas</B></TD></TR>
</TABLE>>];
"jndi" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jndi</B></TD></TR>
</TABLE>>];
"lowresources" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>lowresources</B></TD></TR>
</TABLE>>];
}
/* Level 2 */
{ rank = same;
"fcgi" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>fcgi</B></TD></TR>
</TABLE>>];
"jmx-remote" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jmx-remote</B></TD></TR>
</TABLE>>];
"webapp" [ color="#66FFCC" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>webapp</B></TD></TR>
</TABLE>>];
"proxy" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>proxy</B></TD></TR>
</TABLE>>];
"alpn" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>alpn</B></TD></TR>
</TABLE>>];
"jaspi" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jaspi</B></TD></TR>
</TABLE>>];
"http2c" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>http2c</B></TD></TR>
</TABLE>>];
"https" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>https</B></TD></TR>
</TABLE>>];
"servlets" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>servlets</B></TD></TR>
</TABLE>>];
}
/* Level 3 */
{ rank = same;
"http2" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>http2</B></TD></TR>
</TABLE>>];
"plus" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>plus</B></TD></TR>
</TABLE>>];
"deploy" [ color="#66FFCC" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>deploy</B></TD></TR>
</TABLE>>];
"nosql" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>nosql</B></TD></TR>
</TABLE>>];
}
/* Level 4 */
{ rank = same;
"annotations" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>annotations</B></TD></TR>
</TABLE>>];
}
/* Level 5 */
{ rank = same;
"jdbc-sessions" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jdbc-sessions</B></TD></TR>
</TABLE>>];
"infinispan" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>infinispan</B></TD></TR>
</TABLE>>];
"quickstart" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>quickstart</B></TD></TR>
</TABLE>>];
"jsp" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jsp</B></TD></TR>
</TABLE>>];
"websocket" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>websocket</B></TD></TR>
</TABLE>>];
}
/* Level 6 */
{ rank = same;
"jstl" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>jstl</B></TD></TR>
</TABLE>>];
"cdi" [ color="#B8FFB8" label=<<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="2">
<TR><TD ALIGN="LEFT"><B>cdi</B></TD></TR>
<TR><TD ALIGN="LEFT">(experimental)</TD></TR>
</TABLE>>];
}
"alpn" -> "protonego-boot";
"annotations" -> "plus";
"cdi" -> "deploy";
"cdi" -> "annotations";
"cdi" -> "jsp";
"debuglog" -> "server";
"deploy" -> "webapp";
"fcgi" -> "servlet";
"fcgi" -> "client";
"gzip" -> "server";
"http" -> "server";
"http2" -> "ssl";
"http2" -> "alpn";
"http2c" -> "http";
"https" -> "ssl";
"infinispan" -> "annotations";
"infinispan" -> "webapp";
"ipaccess" -> "server";
"jaas" -> "server";
"jaspi" -> "security";
"jdbc-sessions" -> "annotations";
"jdbc-sessions" -> "webapp";
"jmx" -> "server";
"jmx-remote" -> "jmx";
"jndi" -> "server";
"jsp" -> "servlet";
"jsp" -> "annotations";
"jsp" -> "apache-jsp";
"jstl" -> "jsp";
"jstl" -> "apache-jstl";
"lowresources" -> "server";
"monitor" -> "server";
"monitor" -> "client";
"nosql" -> "webapp";
"plus" -> "security";
"plus" -> "jndi";
"plus" -> "webapp";
"proxy" -> "servlet";
"proxy" -> "client";
"quickstart" -> "plus";
"quickstart" -> "annotations";
"requestlog" -> "server";
"rewrite" -> "server";
"security" -> "server";
"servlet" -> "server";
"servlets" -> "servlet";
"setuid" -> "server";
"spring" -> "server";
"ssl" -> "server";
"stats" -> "server";
"webapp" -> "servlet";
"webapp" -> "security";
"websocket" -> "annotations";
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

View File

@ -0,0 +1,66 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
....
[mybase]$ java -jar /opt/jetty-distribution/start.jar --list-config
Java Environment:
-----------------
java.home = /lib/jvm/jdk-8u45/jre
java.vm.vendor = Oracle Corporation
java.vm.version = 25.45-b02
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
java.vm.info = mixed mode
java.runtime.name = Java(TM) SE Runtime Environment
java.runtime.version = 1.8.0_45-b14
java.io.tmpdir = /tmp
user.dir = /home/jetty/mybase
user.language = en
user.country = US
Jetty Environment:
-----------------
jetty.version = @project.version@
jetty.home = /opt/jetty-distribution
jetty.base = /home/jetty/mybase
Config Search Order:
--------------------
<command-line>
${jetty.base} -> /home/jetty/mybase
${jetty.home} -> /opt/jetty-distribution
JVM Arguments:
--------------
(no jvm args specified)
System Properties:
------------------
(no system properties specified)
Properties:
-----------
(no properties specified)
Jetty Server Classpath:
-----------------------
No classpath entries and/or version information available show.
Jetty Active XMLs:
------------------
(no xml files specified)
....

View File

@ -0,0 +1,22 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
....
WARNING: Nothing to start, exiting ...
Usage: java -jar start.jar [options] [properties] [configs]
java -jar start.jar --help # for more information
....

View File

@ -0,0 +1,81 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
....
[mybase]$ java -jar /opt/jetty-distribution/start.jar --list-config
Java Environment:
-----------------
java.home = /lib/jvm/jdk-8u31-x64/jre
java.vm.vendor = Oracle Corporation
java.vm.version = 25.31-b07
java.vm.name = Java HotSpot(TM) 64-Bit Server VM
java.vm.info = mixed mode
java.runtime.name = Java(TM) SE Runtime Environment
java.runtime.version = 1.8.0_31-b13
java.io.tmpdir = /tmp
user.dir = /home/jetty/mybase
user.language = en
user.country = US
Jetty Environment:
-----------------
jetty.version = @project.version@
jetty.home = /opt/jetty-distribution
jetty.base = /home/jetty/mybase
Config Search Order:
--------------------
<command-line>
${jetty.base} -> /home/jetty/mybase
${jetty.home} -> /opt/jetty-distribution
JVM Arguments:
--------------
(no jvm args specified)
System Properties:
------------------
(no system properties specified)
Properties:
-----------
jetty.http.port = 8080
Jetty Server Classpath:
-----------------------
Version Information on 11 entries in the classpath.
Note: order presented here is how they would appear on the classpath.
changes to the --module=name command line options will be reflected here.
0: 3.1.0 | ${jetty.home}/lib/servlet-api-3.1.jar
1: 3.1.0.M0 | ${jetty.home}/lib/jetty-schemas-3.1.jar
2: @project.version@ | ${jetty.home}/lib/jetty-http-@project.version@.jar
3: @project.version@ | ${jetty.home}/lib/jetty-server-@project.version@.jar
4: @project.version@ | ${jetty.home}/lib/jetty-xml-@project.version@.jar
5: @project.version@ | ${jetty.home}/lib/jetty-util-@project.version@.jar
6: @project.version@ | ${jetty.home}/lib/jetty-io-@project.version@.jar
7: @project.version@ | ${jetty.home}/lib/jetty-security-@project.version@.jar
8: @project.version@ | ${jetty.home}/lib/jetty-servlet-@project.version@.jar
9: @project.version@ | ${jetty.home}/lib/jetty-webapp-@project.version@.jar
10: @project.version@ | ${jetty.home}/lib/jetty-deploy-@project.version@.jar
Jetty Active XMLs:
------------------
${jetty.home}/etc/jetty.xml
${jetty.home}/etc/jetty-http.xml
${jetty.home}/etc/jetty-deploy.xml
....

View File

@ -0,0 +1,28 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
....
[mybase]$ java -jar /opt/jetty-distribution/start.jar --add-to-start=http,webapp,deploy
INFO: server initialised (transitively) in ${jetty.base}/start.ini
INFO: http initialised in ${jetty.base}/start.ini
INFO: security initialised (transitively) in ${jetty.base}/start.ini
INFO: servlet initialised (transitively) in ${jetty.base}/start.ini
INFO: webapp initialised in ${jetty.base}/start.ini
INFO: deploy initialised in ${jetty.base}/start.ini
MKDIR: ${jetty.base}/webapps
INFO: Base directory was modified
....

View File

@ -0,0 +1,349 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
....
[mybase]$ java -jar /opt/jetty-distribution/start.jar --list-modules
Jetty All Available Modules:
----------------------------
[ ] Module: alpn
Depend: ssl
Depend: alpn-impl/alpn-${java.version}
LIB: lib/jetty-alpn-client-${jetty.version}.jar
LIB: lib/jetty-alpn-server-${jetty.version}.jar
XML: etc/jetty-alpn.xml
Enabled: <not enabled in this configuration>
[ ] Module: protonego-boot
Ref: alpn-impl/alpn-1.8.0_45
Enabled: <not enabled in this configuration>
[ ] Module: annotations
Depend: plus
LIB: lib/jetty-annotations-${jetty.version}.jar
LIB: lib/annotations/*.jar
XML: etc/jetty-annotations.xml
Enabled: <not enabled in this configuration>
[ ] Module: apache-jsp
LIB: lib/apache-jsp/*.jar
Enabled: <not enabled in this configuration>
[ ] Module: apache-jstl
LIB: lib/apache-jstl/*.jar
Enabled: <not enabled in this configuration>
[ ] Module: cdi
Depend: deploy
Depend: annotations
Depend: plus
Depend: jsp
LIB: lib/cdi/*.jar
LIB: lib/cdi-core-${jetty.version}.jar
LIB: lib/cdi-servlet-${jetty.version}.jar
XML: etc/jetty-cdi.xml
Enabled: <not enabled in this configuration>
[ ] Module: client
LIB: lib/jetty-client-${jetty.version}.jar
Enabled: <not enabled in this configuration>
[ ] Module: continuation
LIB: lib/jetty-continuation-${jetty.version}.jar
Enabled: <not enabled in this configuration>
[ ] Module: debuglog
Depend: server
XML: etc/jetty-debug.xml
Enabled: <not enabled in this configuration>
[x] Module: deploy
Depend: webapp
LIB: lib/jetty-deploy-${jetty.version}.jar
XML: etc/jetty-deploy.xml
Enabled: <via> ${jetty.base}/start.ini
[ ] Module: ext
LIB: lib/ext/**.jar
Enabled: <not enabled in this configuration>
[ ] Module: fcgi
Depend: servlet
Depend: client
LIB: lib/jetty-proxy-${jetty.version}.jar
LIB: lib/fcgi/*.jar
Enabled: <not enabled in this configuration>
[ ] Module: gzip
Depend: server
XML: etc/jetty-gzip.xml
Enabled: <not enabled in this configuration>
[ ] Module: hawtio
Depend: stats
Depend: deploy
Depend: jmx
XML: etc/hawtio.xml
Enabled: <not enabled in this configuration>
[ ] Module: home-base-warning
XML: etc/home-base-warning.xml
Enabled: <not enabled in this configuration>
[x] Module: http
Depend: server
XML: etc/jetty-http.xml
Enabled: <via> ${jetty.base}/start.ini
[ ] Module: http2
Depend: ssl
Depend: alpn
LIB: lib/http2/*.jar
XML: etc/jetty-http2.xml
Enabled: <not enabled in this configuration>
[ ] Module: http2c
Depend: http
LIB: lib/http2/*.jar
XML: etc/jetty-http2c.xml
Enabled: <not enabled in this configuration>
[ ] Module: https
Depend: ssl
XML: etc/jetty-https.xml
Enabled: <not enabled in this configuration>
[ ] Module: infinispan
Depend: annotations
Depend: webapp
LIB: lib/jetty-infinispan-${jetty.version}.jar
LIB: lib/infinispan/*.jar
XML: etc/jetty-infinispan.xml
Enabled: <not enabled in this configuration>
[ ] Module: ipaccess
Depend: server
XML: etc/jetty-ipaccess.xml
Enabled: <not enabled in this configuration>
[ ] Module: jaas
Depend: server
LIB: lib/jetty-jaas-${jetty.version}.jar
XML: etc/jetty-jaas.xml
Enabled: <not enabled in this configuration>
[ ] Module: jamon
Depend: stats
Depend: deploy
Depend: jmx
Depend: jsp
LIB: lib/jamon/**.jar
XML: etc/jamon.xml
Enabled: <not enabled in this configuration>
[ ] Module: jaspi
Depend: security
LIB: lib/jetty-jaspi-${jetty.version}.jar
LIB: lib/jaspi/*.jar
Enabled: <not enabled in this configuration>
[ ] Module: jdbc-sessions
Depend: annotations
Depend: webapp
XML: etc/jetty-jdbc-sessions.xml
Enabled: <not enabled in this configuration>
[ ] Module: jminix
Depend: stats
Depend: jmx
LIB: lib/jminix/**.jar
XML: etc/jminix.xml
Enabled: <not enabled in this configuration>
[ ] Module: jmx
Depend: server
LIB: lib/jetty-jmx-${jetty.version}.jar
XML: etc/jetty-jmx.xml
Enabled: <not enabled in this configuration>
[ ] Module: jmx-remote
Depend: jmx
XML: etc/jetty-jmx-remote.xml
Enabled: <not enabled in this configuration>
[ ] Module: jndi
Depend: server
LIB: lib/jetty-jndi-${jetty.version}.jar
LIB: lib/jndi/*.jar
Enabled: <not enabled in this configuration>
[ ] Module: jolokia
Depend: stats
Depend: deploy
Depend: jmx
XML: etc/jolokia.xml
Enabled: <not enabled in this configuration>
[ ] Module: jsp
Depend: servlet
Depend: annotations
Depend: apache-jsp
Enabled: <not enabled in this configuration>
[ ] Module: jstl
Depend: jsp
Depend: apache-jstl
Enabled: <not enabled in this configuration>
[ ] Module: jvm
Enabled: <not enabled in this configuration>
[ ] Module: logging
LIB: lib/logging/**.jar
LIB: resources/
XML: etc/jetty-logging.xml
Enabled: <not enabled in this configuration>
[ ] Module: lowresources
Depend: server
XML: etc/jetty-lowresources.xml
Enabled: <not enabled in this configuration>
[ ] Module: monitor
Depend: server
Depend: client
LIB: lib/monitor/jetty-monitor-${jetty.version}.jar
XML: etc/jetty-monitor.xml
Enabled: <not enabled in this configuration>
[ ] Module: nosql
Depend: webapp
LIB: lib/jetty-nosql-${jetty.version}.jar
LIB: lib/nosql/*.jar
XML: etc/jetty-nosql.xml
Enabled: <not enabled in this configuration>
[ ] Module: plus
Depend: server
Depend: security
Depend: jndi
Depend: webapp
LIB: lib/jetty-plus-${jetty.version}.jar
XML: etc/jetty-plus.xml
Enabled: <not enabled in this configuration>
[ ] Module: proxy
Depend: servlet
Depend: client
LIB: lib/jetty-proxy-${jetty.version}.jar
XML: etc/jetty-proxy.xml
Enabled: <not enabled in this configuration>
[ ] Module: quickstart
Depend: server
Depend: plus
Depend: annotations
LIB: lib/jetty-quickstart-${jetty.version}.jar
Enabled: <not enabled in this configuration>
[ ] Module: requestlog
Depend: server
XML: etc/jetty-requestlog.xml
Enabled: <not enabled in this configuration>
[ ] Module: resources
LIB: resources/
Enabled: <not enabled in this configuration>
[ ] Module: rewrite
Depend: server
LIB: lib/jetty-rewrite-${jetty.version}.jar
XML: etc/jetty-rewrite.xml
Enabled: <not enabled in this configuration>
[x] Module: security
Depend: server
LIB: lib/jetty-security-${jetty.version}.jar
Enabled: <via> <transitive from> ${jetty.base}/start.ini
Enabled: <via> ${jetty.base}/start.ini
[x] Module: server
LIB: lib/servlet-api-3.1.jar
LIB: lib/jetty-schemas-3.1.jar
LIB: lib/jetty-http-${jetty.version}.jar
LIB: lib/jetty-server-${jetty.version}.jar
LIB: lib/jetty-xml-${jetty.version}.jar
LIB: lib/jetty-util-${jetty.version}.jar
LIB: lib/jetty-io-${jetty.version}.jar
XML: etc/jetty.xml
Enabled: <via> <transitive from> ${jetty.base}/start.ini
Enabled: <via> ${jetty.base}/start.ini
[x] Module: servlet
Depend: server
LIB: lib/jetty-servlet-${jetty.version}.jar
Enabled: <via> <transitive from> ${jetty.base}/start.ini
Enabled: <via> ${jetty.base}/start.ini
[ ] Module: servlets
Depend: servlet
LIB: lib/jetty-servlets-${jetty.version}.jar
Enabled: <not enabled in this configuration>
[ ] Module: setuid
Depend: server
LIB: lib/setuid/jetty-setuid-java-1.0.3.jar
XML: etc/jetty-setuid.xml
Enabled: <not enabled in this configuration>
[ ] Module: spring
Depend: server
LIB: lib/spring/*.jar
Enabled: <not enabled in this configuration>
[ ] Module: ssl
Depend: server
XML: etc/jetty-ssl.xml
XML: etc/jetty-ssl-context.xml
Enabled: <not enabled in this configuration>
[ ] Module: stats
Depend: server
XML: etc/jetty-stats.xml
Enabled: <not enabled in this configuration>
[x] Module: webapp
Depend: servlet
Depend: security
LIB: lib/jetty-webapp-${jetty.version}.jar
Enabled: <via> ${jetty.base}/start.ini
Enabled: <via> <transitive from> ${jetty.base}/start.ini
[ ] Module: websocket
Depend: annotations
LIB: lib/websocket/*.jar
Enabled: <not enabled in this configuration>
Jetty Selected Module Ordering:
-------------------------------
1) server ${jetty.base}/start.ini
2) http ${jetty.base}/start.ini
2) security ${jetty.base}/start.ini
2) servlet ${jetty.base}/start.ini
3) webapp ${jetty.base}/start.ini
4) deploy ${jetty.base}/start.ini
....

View File

@ -0,0 +1,213 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[start-jar]]
=== Using start.jar
The most basic way of starting the Jetty standalone server is to execute
the `start.jar`, which is a bootstrap for starting Jetty with the
configuration you want.
....
[jetty-distribution-@project.version@]$ java -jar start.jar
2013-09-23 11:27:06.654:INFO:oejs.Server:main: jetty-@project.version@
...
....
Jetty is a highly modularized web server container. Very little is
mandatory and required, and most components are optional; you enable or
disable them according to the needs of your environment.
At its most basic, you configure Jetty from two elements:
1. A set of libraries and directories that make up the server
classpath.
2. A set of Jetty XML configuration files (IoC style) that establish
how to build the Jetty server and its components.
Starting with Jetty 9.1 you have more options on how to configure Jetty
(these are merely syntactic sugar that eventually resolve into the two
basic configuration components).
Jetty 9.1 Startup Features include:
* A separation of the Jetty distribution binaries in `${jetty.home}` and
the environment specific configurations (and binaries) found in
`${jetty.base}` (detailed in
link:#startup-jetty-base-and-jetty-home[Managing Jetty Base and Jetty
Home.])
* You can enable a set of libraries and XML configuration files via the
newly introduced link:#startup-modules[module system.]
* All of the pre-built XML configuration files shipped in Jetty are now
parameterized with properties that you can specify in your
`${jetty.base}/start.ini` (demonstrated in
link:#quick-start-configure[Quick Start Configuration]).
+
There is no longer a
These are powerful new features, made to support a variety of styles of
configuring Jetty, from a simple property based configuration, to
handling multiple installations on a server, to customized stacks of
technology on top of Jetty, and even the classic, custom XML
configurations of old.
For example, if you use the `${jetty.base}` concepts properly, you can
upgrade the Jetty distribution without having to remake your entire tree
of modifications to Jetty. Simply separate out your specific
modifications to the `${jetty.base}`, and in the future, just upgrade
your `${jetty.home}` directory with a new Jetty distribution.
* Loads and parses all INIs found in `${jetty.base}/start.d/*.ini` as
command line arguments.
* Loads and parses `${jetty.base}/start.ini` as command line arguments.
* Parses actual command line arguments used to execute `start.jar`
itself.
* Resolves any XML configuration files, modules, and libraries using
base vs. home resolution steps:
1. Checks whether file exists as relative reference to `${jetty.base}.`
2. Checks whether file exists as relative reference to `${jetty.home}.`
3. Uses default behavior of `java.io.File.`
+
(Relative to `System.getProperty` ("user.dir") and then as absolute file
system path)
* Loads any dependent modules (merges XXNK, library, and properties
results with active command line).
* Builds out server classpath.
* Determines run mode:
** Shows informational command line options and exit.
** Executes Jetty normally, waits for Jetty to stop.
** Executes a forked JVM to run Jetty in, waits for forked JVM to exit.
* If you want to start Jetty:
** Load each XML configuration (in the order determined by the INIs and
module system).
** Let XML configuration start Jetty.
==== start.jar Command Line Options
--help::
Obtains the current list of command line options and some basic usage
help.
--version::
Shows the list of server classpath entries, and prints version
information found for each entry.
--list-classpath::
Similar to --version, shows the server classpath.
--list-config::
Lists the resolved configuration that will start Jetty.
+
* Java environment
* Jetty environment
* JVM arguments
* Properties
* Server classpath
* Server XML configuration files
--dry-run::
Prints the resolved command line that `start.jar` should use to start
a forked instance of Jetty.
--exec::
Starts a forked instance of Jetty.
--debug::
Enables debugging output of the startup procedure.
+
Note: This does not set up debug logging for Jetty itself.
--start-log-file=<filename>::
Sends all startup output to the filename specified.
+
Filename is relative to `${jetty.base}`.
+
This is useful for capturing startup issues where the Jetty-specific
logger has not yet kicked in due to a possible startup configuration
error.
--list-modules::
Lists all the modules defined by the system.
+
Looks for module files using the link:#startup-base-and-home[normal
`${jetty.base}` and `${jetty.home}` resolution logic].
+
Also lists enabled state based on information present on the command
line, and all active startup INI files.
--module=<name>,(<name>)*::
Enables one or more modules by name (use --list-modules to see the
list of available modules).
+
This enables all transitive (dependent) modules from the module system
as well.
+
If you use this from the shell command line, it is considered a
temporary effect, useful for testing out a scenario. If you want this
module to always be enabled, add this command to your
`${jetty.base}/start.ini.`
--add-to-start=<name>,(<name>)*::
Enables a module by appending lines to the `${jetty.base}/start.ini`
file.
+
The lines that are added are provided by the module-defined INI
templates.
+
Note: Transitive modules are also appended.
--add-to-startd=<name>,(<name>)*::
Enables a module via creation of a module-specific INI file in the
`${jetty.base}/start.d/` directory.
+
The content of the new INI is provided by the module-defined ini
templates.
+
Note: Transitive modules are also created in the same directory as
their own INI files.
--write-module-graph=<filename>::
Advanced feature: Creates a graphviz
http://graphviz.org/content/dot-language[dot file] of the module graph
as it exists for the active `${jetty.base}`.
+
....
# generate module.dot
$ java -jar start.jar --module=websocket --write-module-graph=modules.dot
# post process to a PNG file
$ dot -Tpng -o modules.png modules.dot
....
+
See http://graphviz.org/[graphviz.org] for details on
http://graphviz.org/content/command-line-invocation[how to
post-process this dotty file] into the output best suited for your
needs.
--stop::
Sends a stop signal to the running Jetty instance.
+
Note: The server must have been started with various stop properties
for this to work.
+
STOP.PORT=<number>;;
The port to use to stop the running Jetty server. This is an
internal port, opened on localhost, used solely for stopping the
running Jetty server. Choose a port that you do not use to serve web
traffic.
+
Required for --stop to function.
STOP.KEY=<alphanumeric>;;
The passphrase defined to stop the server.
+
Required for --stop to function.
STOP.WAIT=<number>;;
The time (in seconds) to wait for confirmation that the running
Jetty server has stopped. If not specified, the stopper waits
indefinitely for the server to stop.
+
If the time specified elapses, without a confirmation of server
stop, then the --stop command exits with a non-zero return code.

View File

@ -0,0 +1,20 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[advanced-start-matrix]]
=== Start Option Matrix [deprecated]
Content from: http://wiki.eclipse.org/Jetty/Reference/Start_Options

View File

@ -0,0 +1,331 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup-base-and-home]]
=== Managing Jetty Base and Jetty Home
Starting with Jetty 9.1, it is now possible to maintain a separation
between the binary installation of the standalone Jetty (known as
`${jetty.home}`), and the customizations for your specific environment
(known as `${jetty.base}`).
Jetty Base::
Also known as the `${jetty.base}` property
+
This is the location for your configurations and customizations to the
Jetty distribution.
Jetty Home::
Also known as the `${jetty.home}` property.
+
This is the location for the Jetty distribution binaries, default XML
IoC configurations, and default module definitions.
Potential configuration is resolved from these 2 directory locations.
Check Jetty Base::
If the referenced configuration exists, relative to the defined Jetty
Base, use it.
Check Jetty Home::
If the referenced configuration exists, relative to the defined Jetty
Home, use it.
Use java.io.File(String pathname) Logic::
Lastly, use the reference as a `java.io.File(String
pathname)` reference, following the default resolution rules
outlined by that constructor.
+
In brief, the reference will be used as-is, be it relative (to current
working directory, aka $\{user.dir}) or absolute path, or even network
reference (such as on Windows and use of UNC paths).
For more details on how startup with start.jar works, see
link:#execute-start-jar[Using start.jar: Executing]
[[demo-base]]
==== Demo-Base in the Jetty Distribution
The Jetty Distribution comes with an example $\{jetty.base} which
enables the various demonstration webapps and server configurations.
How to use the demo-base directory as a Jetty Base directory.
....
[jetty-distribution-@project.version@]$ ls -la
total 496
drwxrwxr-x 11 user group 4096 Oct 8 15:23 ./
drwxr-xr-x 14 user group 4096 Oct 8 13:04 ../
drwxrwxr-x 2 user group 4096 Oct 8 06:54 bin/
drwxrwxr-x 6 user group 4096 Oct 8 06:54 demo-base/
drwxrwxr-x 2 user group 4096 Oct 11 15:14 etc/
drwxrwxr-x 11 user group 4096 Oct 8 06:54 lib/
-rw-rw-r-- 1 user group 30012 Sep 30 19:55 license-eplv10-aslv20.html
drwxrwxr-x 2 user group 4096 Oct 8 06:54 logs/
drwxrwxr-x 2 user group 4096 Oct 8 06:54 modules/
-rw-rw-r-- 1 user group 6262 Sep 30 19:55 notice.html
-rw-rw-r-- 1 user group 1249 Sep 30 19:55 README.TXT
drwxrwxr-x 2 user group 4096 Oct 8 06:54 resources/
drwxrwxr-x 2 user group 4096 Oct 8 06:54 start.d/
-rw-rw-r-- 1 user group 1780 Sep 30 19:55 start.ini
-rw-rw-r-- 1 user group 71921 Sep 30 19:55 start.jar
-rw-rw-r-- 1 user group 336468 Sep 30 19:55 VERSION.txt
drwxrwxr-x 2 user group 4096 Oct 8 06:54 webapps/
[jetty-distribution-@project.version@]$ cd demo-base
[demo-base]$ java -jar $JETTY_HOME/start.jar
2013-10-16 09:08:47.800:WARN::main: demo test-realm is deployed. DO NOT USE IN PRODUCTION!
2013-10-16 09:08:47.802:INFO:oejs.Server:main: jetty-@project.version@
2013-10-16 09:08:47.817:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/user/jetty-distribution-@project.version@/demo-base/webapps/] at interval 1
2013-10-16 09:08:48.072:WARN::main: async-rest webapp is deployed. DO NOT USE IN PRODUCTION!
...
....
As you can see above, you are executing the demo-base configuration
using the Jetty Base concepts.
If you want to see what the Jetty Base looks like without executing
Jetty, you can simply list the configuration
....
[my-base]$ java -jar $JETTY_HOME/start.jar --list-config
Java Environment:
-----------------
java.home=/usr/lib/jvm/jdk-7u21-x64/jre
java.vm.vendor=Oracle Corporation
java.vm.version=23.21-b01
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vm.info=mixed mode
java.runtime.name=Java(TM) SE Runtime Environment
java.runtime.version=1.7.0_21-b11
java.io.tmpdir=/tmp
Jetty Environment:
-----------------
jetty.home=/home/user/jetty-distribution-@project.version@
jetty.base=/home/user/jetty-distribution-@project.version@/demo-base
jetty.version=@project.version@
JVM Arguments:
--------------
(no jvm args specified)
System Properties:
------------------
jetty.base = /home/user/jetty-distribution-@project.version@/demo-base
jetty.home = /home/user/jetty-distribution-@project.version@
Properties:
-----------
demo.realm = etc/realm.properties
https.port = 8443
https.timeout = 30000
jaas.login.conf = etc/login.conf
jetty.dump.start = false
jetty.dump.stop = false
jetty.keymanager.password = OBF:1u2u1wml1z7s1z7a1wnl1u2g
jetty.keystore = etc/keystore
jetty.keystore.password = OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4
jetty.http.port = 8080
jetty.secure.port = 8443
jetty.truststore = etc/keystore
jetty.truststore.password = OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4
org.eclipse.jetty.websocket.jsr356 = false
threads.max = 200
threads.min = 10
threads.timeout = 60000
Jetty Server Classpath:
-----------------------
Version Information on 42 entries in the classpath.
Note: order presented here is how they would appear on the classpath.
changes to the --module=name command line options will be reflected here.
0: @project.version@ | ${jetty.home}/lib/jetty-client-@project.version@.jar
1: 1.4.1.v201005082020 | ${jetty.base}/lib/ext/javax.mail.glassfish-1.4.1.v201005082020.jar
2: @project.version@ | ${jetty.base}/lib/ext/test-mock-resources-@project.version@.jar
3: (dir) | ${jetty.home}/resources
4: 3.1.0 | ${jetty.home}/lib/servlet-api-3.1.jar
5: 3.1.RC0 | ${jetty.home}/lib/jetty-schemas-3.1.jar
6: @project.version@ | ${jetty.home}/lib/jetty-http-@project.version@.jar
7: @project.version@ | ${jetty.home}/lib/jetty-continuation-@project.version@.jar
8: @project.version@ | ${jetty.home}/lib/jetty-server-@project.version@.jar
9: @project.version@ | ${jetty.home}/lib/jetty-xml-@project.version@.jar
10: @project.version@ | ${jetty.home}/lib/jetty-util-@project.version@.jar
11: @project.version@ | ${jetty.home}/lib/jetty-io-@project.version@.jar
12: @project.version@ | ${jetty.home}/lib/jetty-jaas-@project.version@.jar
13: @project.version@ | ${jetty.home}/lib/jetty-jndi-@project.version@.jar
14: 1.1.0.v201105071233 | ${jetty.home}/lib/jndi/javax.activation-1.1.0.v201105071233.jar
15: 1.4.1.v201005082020 | ${jetty.home}/lib/jndi/javax.mail.glassfish-1.4.1.v201005082020.jar
16: 1.2 | ${jetty.home}/lib/jndi/javax.transaction-api-1.2.jar
17: @project.version@ | ${jetty.home}/lib/jetty-rewrite-@project.version@.jar
18: @project.version@ | ${jetty.home}/lib/jetty-security-@project.version@.jar
19: @project.version@ | ${jetty.home}/lib/jetty-servlet-@project.version@.jar
20: 3.0.0 | ${jetty.home}/lib/jsp/javax.el-3.0.0.jar
21: 1.2.0.v201105211821 | ${jetty.home}/lib/jsp/javax.servlet.jsp.jstl-1.2.0.v201105211821.jar
22: 2.3.2 | ${jetty.home}/lib/jsp/javax.servlet.jsp-2.3.2.jar
23: 2.3.1 | ${jetty.home}/lib/jsp/javax.servlet.jsp-api-2.3.1.jar
24: 2.3.3 | ${jetty.home}/lib/jsp/jetty-jsp-jdt-2.3.3.jar
25: 1.2.0.v201112081803 | ${jetty.home}/lib/jsp/org.apache.taglibs.standard.glassfish-1.2.0.v201112081803.jar
26: 3.8.2.v20130121-145325 | ${jetty.home}/lib/jsp/org.eclipse.jdt.core-3.8.2.v20130121.jar
27: @project.version@ | ${jetty.home}/lib/jetty-plus-@project.version@.jar
28: @project.version@ | ${jetty.home}/lib/jetty-webapp-@project.version@.jar
29: @project.version@ | ${jetty.home}/lib/jetty-annotations-@project.version@.jar
30: 4.1 | ${jetty.home}/lib/annotations/asm-4.1.jar
31: 4.1 | ${jetty.home}/lib/annotations/asm-commons-4.1.jar
32: 1.2 | ${jetty.home}/lib/annotations/javax.annotation-api-1.2.jar
33: @project.version@ | ${jetty.home}/lib/jetty-deploy-@project.version@.jar
34: 1.0 | ${jetty.home}/lib/websocket/javax.websocket-api-1.0.jar
35: @project.version@ | ${jetty.home}/lib/websocket/javax-websocket-client-impl-@project.version@.jar
36: @project.version@ | ${jetty.home}/lib/websocket/javax-websocket-server-impl-@project.version@.jar
37: @project.version@ | ${jetty.home}/lib/websocket/websocket-api-@project.version@.jar
38: @project.version@ | ${jetty.home}/lib/websocket/websocket-client-@project.version@.jar
39: @project.version@ | ${jetty.home}/lib/websocket/websocket-common-@project.version@.jar
40: @project.version@ | ${jetty.home}/lib/websocket/websocket-server-@project.version@.jar
41: @project.version@ | ${jetty.home}/lib/websocket/websocket-servlet-@project.version@.jar
Jetty Active XMLs:
------------------
${jetty.home}/etc/jetty.xml
${jetty.home}/etc/jetty-http.xml
${jetty.home}/etc/jetty-jaas.xml
${jetty.home}/etc/jetty-rewrite.xml
${jetty.home}/etc/jetty-ssl.xml
${jetty.home}/etc/jetty-https.xml
${jetty.home}/etc/jetty-plus.xml
${jetty.home}/etc/jetty-annotations.xml
${jetty.home}/etc/jetty-deploy.xml
${jetty.base}/etc/demo-rewrite-rules.xml
${jetty.base}/etc/test-realm.xml
....
This demonstrates the powerful `--list-config` command line option and
how you can use it to see what the configuration will look like when
starting Jetty. From the Java environment, to the system properties, to
the classpath, and finally the Active Jetty IoC XML used to build up
your Jetty server configuration.
Of note, is that the output will make it known where the configuration
elements came from, be it in either in `${jetty.home}` or
`${jetty.base}`.
If you look at the $\{jetty.base}/start.ini you will see something like
the following.
....
[my-base]$ cat start.ini
# Enable security via jaas, and configure it
--module=jaas
jaas.login.conf=etc/login.conf
# Enable rewrite examples
--module=rewrite
etc/demo-rewrite-rules.xml
# Websocket chat examples needs websocket enabled
# Don't start for all contexts (set to true in test.xml context)
org.eclipse.jetty.websocket.jsr356=false
--module=websocket
# Create and configure the test realm
etc/test-realm.xml
demo.realm=etc/realm.properties
# Initialize module server
--module=server
threads.min=10
threads.max=200
threads.timeout=60000
jetty.dump.start=false
jetty.dump.stop=false
--module=deploy
--module=jsp
--module=ext
--module=resources
--module=client
--module=annotations
....
The $\{jetty.base}/start.ini is the main startup configuration entry
point for Jetty. In this example you will see that we are enabling a few
modules for Jetty, specifying some properties, and also referencing some
Jetty IoC XML files (namely the `etc/demo-rewrite-rules.xml` and
`etc/test-realm.xml` files)
When Jetty's `start.jar` resolves the entries in the start.ini, it will
follow the link:#base-vs-home-resolution[resolution rules above].
For example, the reference to `etc/demo-rewrite-rules.xml` was found in
`${jetty.base}/etc/demo-rewrite-rules.xml`.
==== Declaring Jetty Base
The Jetty Distribution's start.jar is the component that manages the
behavior of this separation.
The Jetty start.jar and XML files always assume that both
`${jetty.home}` and `${jetty.base}` are defined when starting Jetty.
You can opt to manually define the `${jetty.home}` and `${jetty.base}`
directories, such as this:
....
[jetty-distribution-@project.version@]$ pwd
/home/user/jetty-distribution-@project.version@
[jetty-distribution-@project.version@]$ java -jar start.jar \
jetty.home=/home/user/jetty-distribution-@project.version@ \
jetty.base=/home/user/my-base
2013-10-16 09:08:47.802:INFO:oejs.Server:main: jetty-@project.version@
2013-10-16 09:08:47.817:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/user/my-base/webapps/] at interval 1
...
....
Or you can declare one directory and let the other one be discovered.
The following example uses default discovery of `${jetty.home}` by using
the parent directory of wherever start.jar itself is, and a manual
declaration of `${jetty.base}`.
....
[jetty-distribution-@project.version@]$ pwd
/home/user/jetty-distribution-@project.version@
[jetty-distribution-@project.version@]$ java -jar start.jar jetty.base=/home/user/my-base
2013-10-16 09:08:47.802:INFO:oejs.Server:main: jetty-@project.version@
2013-10-16 09:08:47.817:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/user/my-base/webapps/] at interval 1
...
....
But Jetty recommends that you always start Jetty by sitting in the
directory that is your $\{jetty.base} and starting Jetty by referencing
the start.jar remotely.
The following demonstrates this by allowing default discovery of
`${jetty.home}` via locating the `start.jar`, and using the `user.dir`
System Property for `${jetty.base}`.
....
[jetty-distribution-@project.version@]$ pwd
/home/user/jetty-distribution-@project.version@
[jetty-distribution-@project.version@]$ cd /home/user/my-base
[my-base]$ java -jar /home/user/jetty-distribution-@project.version@/start.jar
2013-10-16 09:08:47.802:INFO:oejs.Server:main: jetty-@project.version@
2013-10-16 09:08:47.817:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/user/my-base/webapps/] at interval 1
...
....
____
[IMPORTANT]
Be aware of the `user.dir` system property, it can only be safely set when the JVM starts, and many 3rd party libraries (especially logging) use this system property.
+
It is strongly recommended that you sit in the directory that is your desired `${jetty.base}` when starting Jetty to have consistent behavior and use of the `user.dir` system property.
____

View File

@ -0,0 +1,124 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup-classpath]]
=== Managing Server Classpath
Jetty Server Classpath is determined by a combination of factors.
The java.class.path System Property::
If you start Jetty with a JVM specified classpath, then Jetty will use
the java.class.path System Property to populate the initial classpath.
Module specified Libraries::
With Jetty 9.1+ the module system declares various libraries that are
required for that module to operate, these module defined libraries
are added to the Jetty Server classpath when any module is activated
with library declarations.
Command Line Libraries::
The command line option `--lib=<path>`can be used as a final means to
add arbitrary entries to the Jetty Server classpath.
Of special note, there are 2 structural modules defined to ease some of
this for you.
--module=ext::
The `ext` module will enable the `lib/ext/*.jar` logic.
+
If this module is activated, then all jar files found in the lib/ext/
paths will be automatically added to the Jetty Server Classpath.
--module=resources::
The `resources` module will add the `resources/` directory the
classpath.
+
If you have 3rd party libraries that lookup resources from the
classpath, put your files in here.
+
Logging libraries often have classpath lookup of their configuration
files (eg: `log4j.properties`, `log4j.xml`, `logging.properties`, and
`logback.xml`), so this would be the ideal setup for this sort of
configuration demand.
____
[NOTE]
Both the `ext` and `resources` modules declare relative paths that follow link:#base-vs-home-resolution[Jetty Base and Jetty Home path resolution rules].
____
==== Interrogating the Server Classpath
The Jetty start.jar has the ability to resolve the classpath from the
command line + modules + configuration, and list the classpath entries
it will use to start jetty.
The `--list-classpath` command line option is used as such.
(Demonstrated with the link:#demo-base[demo-base from the Jetty
Distribution])
....
[demo-base]$ java -jar $JETTY_HOME/start.jar --list-classpath
Jetty Server Classpath:
-----------------------
Version Information on 42 entries in the classpath.
Note: order presented here is how they would appear on the classpath.
changes to the --module=name command line options will be reflected here.
0: @project.version@ | ${jetty.home}/lib/jetty-client-@project.version@.jar
1: 1.4.1.v201005082020 | ${jetty.base}/lib/ext/javax.mail.glassfish-1.4.1.v201005082020.jar
2: @project.version@ | ${jetty.base}/lib/ext/test-mock-resources-@project.version@.jar
3: (dir) | ${jetty.home}/resources
4: 3.1.0 | ${jetty.home}/lib/servlet-api-3.1.jar
5: 3.1.RC0 | ${jetty.home}/lib/jetty-schemas-3.1.jar
6: @project.version@ | ${jetty.home}/lib/jetty-http-@project.version@.jar
7: @project.version@ | ${jetty.home}/lib/jetty-continuation-@project.version@.jar
8: @project.version@ | ${jetty.home}/lib/jetty-server-@project.version@.jar
9: @project.version@ | ${jetty.home}/lib/jetty-xml-@project.version@.jar
10: @project.version@ | ${jetty.home}/lib/jetty-util-@project.version@.jar
11: @project.version@ | ${jetty.home}/lib/jetty-io-@project.version@.jar
12: @project.version@ | ${jetty.home}/lib/jetty-jaas-@project.version@.jar
13: @project.version@ | ${jetty.home}/lib/jetty-jndi-@project.version@.jar
14: 1.1.0.v201105071233 | ${jetty.home}/lib/jndi/javax.activation-1.1.0.v201105071233.jar
15: 1.4.1.v201005082020 | ${jetty.home}/lib/jndi/javax.mail.glassfish-1.4.1.v201005082020.jar
16: 1.2 | ${jetty.home}/lib/jndi/javax.transaction-api-1.2.jar
17: @project.version@ | ${jetty.home}/lib/jetty-rewrite-@project.version@.jar
18: @project.version@ | ${jetty.home}/lib/jetty-security-@project.version@.jar
19: @project.version@ | ${jetty.home}/lib/jetty-servlet-@project.version@.jar
20: 3.0.0 | ${jetty.home}/lib/jsp/javax.el-3.0.0.jar
21: 1.2.0.v201105211821 | ${jetty.home}/lib/jsp/javax.servlet.jsp.jstl-1.2.0.v201105211821.jar
22: 2.3.2 | ${jetty.home}/lib/jsp/javax.servlet.jsp-2.3.2.jar
23: 2.3.1 | ${jetty.home}/lib/jsp/javax.servlet.jsp-api-2.3.1.jar
24: 2.3.3 | ${jetty.home}/lib/jsp/jetty-jsp-jdt-2.3.3.jar
25: 1.2.0.v201112081803 | ${jetty.home}/lib/jsp/org.apache.taglibs.standard.glassfish-1.2.0.v201112081803.jar
26: 3.8.2.v20130121-145325 | ${jetty.home}/lib/jsp/org.eclipse.jdt.core-3.8.2.v20130121.jar
27: @project.version@ | ${jetty.home}/lib/jetty-plus-@project.version@.jar
28: @project.version@ | ${jetty.home}/lib/jetty-webapp-@project.version@.jar
29: @project.version@ | ${jetty.home}/lib/jetty-annotations-@project.version@.jar
30: 4.1 | ${jetty.home}/lib/annotations/asm-4.1.jar
31: 4.1 | ${jetty.home}/lib/annotations/asm-commons-4.1.jar
32: 1.2 | ${jetty.home}/lib/annotations/javax.annotation-api-1.2.jar
33: @project.version@ | ${jetty.home}/lib/jetty-deploy-@project.version@.jar
34: 1.0 | ${jetty.home}/lib/websocket/javax.websocket-api-1.0.jar
35: @project.version@ | ${jetty.home}/lib/websocket/javax-websocket-client-impl-@project.version@.jar
36: @project.version@ | ${jetty.home}/lib/websocket/javax-websocket-server-impl-@project.version@.jar
37: @project.version@ | ${jetty.home}/lib/websocket/websocket-api-@project.version@.jar
38: @project.version@ | ${jetty.home}/lib/websocket/websocket-client-@project.version@.jar
39: @project.version@ | ${jetty.home}/lib/websocket/websocket-common-@project.version@.jar
40: @project.version@ | ${jetty.home}/lib/websocket/websocket-server-@project.version@.jar
41: @project.version@ | ${jetty.home}/lib/websocket/websocket-servlet-@project.version@.jar
....
Of note is that an attempt is made to list the internally declared
version of each artifact on the Server Classpath, of potential help when
diagnosing classpath issues.

View File

@ -0,0 +1,168 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup-modules]]
=== Managing Startup Modules
Starting with Jetty 9.1, a new Module system was introduced. (It
replaced the old `start.config` + `OPTIONS` techniques from past Jetty
Distributions).
The standard Jetty Distribution ships with several modules defined in
`${jetty.home}/modules/`
What a Jetty Startup Module Defines:
A Module Name::
The name of the module is the keyword used by the `--module=<name>`
command line argument to activate/enable modules, and also find
dependant modules.
+
The filename of the module defines its name. (eg: server.mod becomes
the module named "server")
List of Dependant Modules::
All modules can declare that they depend on other modules with the
`[depend]` section.
+
The list of dependencies is used to transitively resolve other modules
that are deemed to be required based on the modules that you activate.
+
The order of modules defined in the graph of active modules is used to
determine various execution order for configuration, such as Jetty IoC
XML configurations, and to resolve conflicting property declarations.
+
Of note: there is a special section `[optional]` used to describe
structurally dependant modules that are not technically required, but
might be of use to your specific configuration.
List of Libraries::
Module can optionally declare that they have libraries that they need
to function properly.
+
The `[lib]` section declares a set of pathnames that follow the
link:#base-vs-home-resolution[Jetty Base and Jetty Home path
resolution rules].
List of Jetty IoC XML Configurations::
A Module can optionally declare a list of Jetty IoC XML configurations
used to wire up the functionality that this module defines.
+
The `[xml]` section declares a set of pathnames that follow the
link:#base-vs-home-resolution[Jetty Base and Jetty Home path
resolution rules].
+
Ideally, all XML files are parameterized to accept properties to
configure the various elements of the standard configuration. Allowing
for a simplified configuration of Jetty for the vast majority of
deployments.
+
The execution order of the Jetty IoC XML configurations is determined
by the graph of active module dependencies resolved via the `[depend]`
sections.
+
If the default XML is not sufficient to satisfy your needs, you can
override this XML by making your own in the $\{jetty.base}/etc/
directory, with the same name. The resolution steps for Jetty Base and
Jetty Home will ensure that your copy from $\{jetty.base} will be
picked up over the default one in $\{jetty.home}.
Jetty INI Template::
Each module can optionally declare a startup ini template that is used
to insert/append/inject sample configuration elements into the
`start.ini` or `start.d/*.ini` files when using the
`--add-to-start=<name>` or `--add-to-startd=<name>` command line
arguments in `start.jar`.
+
Commonly used to present some of the parameterized property options
from the Jetty IoC XML configuration files also referenced in the same
module.
+
The `[ini-template]` section declares this section of sample
configuration.
Required Files and Directories::
If the activation of a module requires some paths to exist, the
`[files]` section defines them.
+
There are 2 modes of operation of the entries in this section.
+
Ensure Directory Exists;;
If you add a pathname that ends in `"/"` (slash), such as
`"webapps/"`, then that directory will be created if it does not yet
exist in `${jetty.base}/<pathname>` (eg: `"webapps/"` will result in
`${jetty.base}/webapps/` being created)
Download File;;
There is a special syntax to allow you to download a file into a
specific location if it doesn't exist yet.
+
`<url>:<pathname>`
+
Currently, the `<url>` must be a `http://` scheme URL
(link:#bugs[file a bug] if you want more schemes supported). The
`<pathname>` portion follows the link:#base-vs-home-resolution[Jetty
Base and Jetty Home path resolution rules].
+
Example:
+
`http://repo.corp.com/maven/corp-security-policy-1.0.jar:lib/corp-security-policy.jar`
+
This will check for the existence of `lib/corp-security-policy.jar`,
and if it doesn't exist, it will download the jar file from
`http://repo.corp.com/maven/corp-security-policy-1.0.jar`
[[enabling-modules]]
==== Enabling Modules
Jetty ships with many modules defined, and a small subset predefined in
the `start.ini` found in the jetty distribution.
____
[TIP]
The default distribution has a co-mingled `${jetty.home}` and `${jetty.base}`. Where the directories for `${jetty.home}` and `${jetty.base}` point to the same location.
+
It is highly encouraged that you learn about the differences in link:#startup-base-and-home[Jetty Base vs Jetty Home] and take full advantage of this setup.
____
When you want enable a module, you can use the `--module=<modulename>`
syntax on the command line (or start.ini) to enable that module and all
of its dependant modules.
An example of this, with a new, empty, base directory.
We can see from this output, that the directory is new (it is empty
after all).
Lets see what the configuration looks like so far
Lets try adding some basic support for webapps, with automatic deploy
(hot deploy), and a single basic HTTP/1.1 connector.
That just created what we need in the `${jetty.base}` directory. Lets
see what it looks like configuration wise.
You now have a configured and functional server, albiet with no webapps
deployed. At this point you can toss a webapp (war file) into
`mybase/webapps/` directory and and start Jetty
[[startup-listing-modules]]
==== Listing Available and Active Modules
To see which modules are __available__, use the `--list-modules` command
line argument. This command will also show you which modules are
__enabled__. Here's an example
Wow, are there really that many modules available?
Yes, the module system has grown a fair bit since it was introduced in
Jetty 9
image:images/modules-9.3-simplified.png[image,width=768]

View File

@ -0,0 +1,265 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup-overview]]
=== Startup Overview
The `start.jar` bootstrap manages the startup of standalone Jetty. It is
responsible for:
Building the classpath::
The `start.jar` bootstrap builds a classpath for all the required
Jetty features and their dependencies. It builds the classpath using
either the `--lib` option to `start.jar` to add an individual
classpath entry, or with the `--module` option that includes all the
libs and their dependencies for a module (a named Jetty feature).
Instantiating the Server Components::
The server and its components are instantiated using either Jetty IoC
XML or spring. The Jetty server is just a collection of java POJOs for
the server, connectors, session managers and others. These are
instantiated, injected, and wired up together in XML files, commonly
one per module/feature, that are passed as arguments to `start.jar`.
Resolving Server Filesystem Locations::
The `start.jar` mechanism resolves canonical locations for the
`${jetty.home}` and the `${jetty.base}` directories.
+
The `${jetty.home}` directory is the location of the standard
distribution of Jetty.
+
The `${jetty.base}` directory is the location of the local server
customization and configurations.
+
If you want to modify the Jetty distribution, base and home can be the
same directory. Separating the base and home directories allows the
distribution to remain unmodified, with all customizations in the base
directory, and thus simplifies subsequent server version upgrades.
Parameterizing the Server Configuration::
XML files primarily determine the server configuration. Many of these
files are parameterized to allow simple injection of host names,
ports, passwords and more. The `start.jar` mechanism allows you to set
parameters on the command line or in properties files.
To achieve these start up mechanisms, the `start.jar` uses:
Command line arguments::
You can configure the entire server with command line arguments that
specify libraries, properties and XML files. However in practice the
INI and modules mechanisms (below) reduce the verbosity of the command
line.
INI files::
The `start.jar` mechanism uses the contents of the
`${jetty.base}/start.ini` and `${jetty.base}/start.d/*.ini` files with
each line equivalent to a `start.jar` command line argument. This
means that either a global `start.ini` file or multiple
`start.d/feature.ini` files control the configuration of the server.
Modules::
Instead of explicitly listing all the libraries, properties and XML
files for a feature, the `start.jar` mechanism allows you to create
modules. You define a module in a `modules/*.mod` file, including the
libraries, dependencies, XML, and template INI files for a Jetty
feature. Thus you can use a single `--module=name` command line option
as the equivalent of specifying many `--lib=location`, feature.xml,
name=value arguments for a feature and all its dependencies. Modules
also use their dependencies to control the ordering of libraries and
XML files.
XML Files::
XML files in either Jetty IoC or Spring format instantiate the actual
POJO components of the server. This includes all major components such
as connectors, keystores, session managers, and data sources.
Typically there are one or more XML files per module, and these are
defined and activated in the corresponding module.
==== Startup Example
The simplest way to start Jetty is via the `start.jar` mechanism using
the following Java command line:
....
[user]$ cd jetty-distribution-@project.version@
[jetty-distribution-@project.version@]$ java -jar start.jar --module=http jetty.http.port=8080
....
This command uses the `start.jar` mechanism to bootstrap the classpath,
properties, and XML files with the metadata obtained from the `http`
module. Specifically the `http` module is defined in the
`${jetty.home}/modules/http.mod` file, and includes the following:
....
[jetty-distribution-@project.version@]$ cat modules/http.mod
[depend]
server
[xml]
etc/jetty-http.xml
[ini-template]
jetty.http.port=8080
http.timeout=30000
....
The `http` module declares that `http` depends on the server module,
uses the `jetty-http.xml` file, and can be parameterized with
`jetty.http.port` and `http.timeout` parameters. The INI-template
section is not actually used by the command above, so the
`jetty.http.port` must still be defined on the command line.
Following the server dependency, the `${jetty.home}/modules/server.mod`
file includes:
....
[jetty-distribution-@project.version@]$ cat modules/server.mod
[lib]
lib/servlet-api-3.1.jar
lib/jetty-http-${jetty.version}.jar
lib/jetty-server-${jetty.version}.jar
lib/jetty-xml-${jetty.version}.jar
lib/jetty-util-${jetty.version}.jar
lib/jetty-io-${jetty.version}.jar
[xml]
etc/jetty.xml
[ini-template]
threads.min=10
threads.max=200
....
The `server` module declares the libraries the server needs and t0 use
`jetty.xml` file. The combined metadata of the `http` and `server`
modules results in `start.jar` generating the effective Java command
line required to start Jetty.
Another way to see this is by asking Jetty what its configuration looks
like:
....
[jetty-distribution-@project.version@]$ java -jar start.jar --module=http jetty.http.port=9099 --list-config
Java Environment:
-----------------
java.home=/user/lib/jvm/jdk-7u21-x64/jre
java.vm.vendor=Oracle Corporation
java.vm.version=23.25-b01
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vm.info=mixed mode
java.runtime.name=Java(TM) SE Runtime Environment
java.runtime.version=1.7.0_25-b15
java.io.tmpdir=/tmp
Jetty Environment:
-----------------
jetty.home=/opt/jetty/jetty-distribution-@project.version@
jetty.base=/opt/jetty/jetty-distribution-@project.version@
jetty.version=@project.version@
JVM Arguments:
--------------
(no jvm args specified)
System Properties:
------------------
jetty.home = /opt/jetty/jetty-distribution-@project.version@
jetty.base = /opt/jetty/jetty-distribution-@project.version@
Properties:
-----------
jetty.http.port = 9099
Jetty Server Classpath:
-----------------------
Version Information on 7 entries in the classpath.
Note: order presented here is how they would appear on the classpath.
changes to the --module=name command line options will be reflected here.
0: 3.1.0 | ${jetty.home}/lib/servlet-api-3.1.jar
1: 3.1.RC0 | ${jetty.home}/lib/jetty-schemas-3.1.jar
2: @project.version@ | ${jetty.home}/lib/jetty-http-@project.version@.jar
3: @project.version@ | ${jetty.home}/lib/jetty-server-@project.version@.jar
4: @project.version@ | ${jetty.home}/lib/jetty-xml-@project.version@.jar
5: @project.version@ | ${jetty.home}/lib/jetty-util-@project.version@.jar
6: @project.version@ | ${jetty.home}/lib/jetty-io-@project.version@.jar
Jetty Active XMLs:
------------------
${jetty.home}/etc/jetty.xml
${jetty.home}/etc/jetty-http.xml
....
This represents the entirety of the configuration that is applied to
start Jetty.
If you don't want to use the `start.jar` bootstrap, you can start Jetty
using a traditional Java command line.
The following is the equivalent `java` command line for what the
`start.jar` bootstrap above performs.
....
[user]$ cd jetty-distribution-@project.version@
[jetty-distribution-@project.version@]$ echo jetty.http.port=8080 > /tmp/jetty.properties
[jetty-distribution-@project.version@]$ export JETTY_HOME=`pwd`
[jetty-distribution-@project.version@]$ export JETTY_BASE=`pwd`
[jetty-distribution-@project.version@]$ export JETTY_VERSION="${project.version}"
[jetty-distribution-@project.version@]$ java -Djetty.home=$JETTY_HOME \
-Djetty.base=$JETTY_BASE \
-cp \
$JETTY_HOME/lib/servlet-api-3.1.jar\
:$JETTY_HOME/lib/jetty-schemas-3.1.jar\
:$JETTY_HOME/lib/jetty-http-$JETTY_VERSION.jar\
:$JETTY_HOME/lib/jetty-server-$JETTY_VERSION.jar \
:$JETTY_HOME/lib/jetty-xml-$JETTY_VERSION.jar\
:$JETTY_HOME/lib/jetty-util-$JETTY_VERSION.jar\
:$JETTY_HOME/lib/jetty-io-$JETTY_VERSION.jar\
org.eclipse.jetty.xml.XmlConfiguration \
/tmp/jetty.properties \
$JETTY_HOME/etc/jetty.xml \
$JETTY_HOME/etc/jetty-http.xml
....
The java command line sets up the classpath with the core Jetty jars and
the servlet API, executes the XmlConfiguration class, and passes it some
XML files that define the server and an HTTP connector running on the
port defined in the `jetty.properties` file.
You can further simplify the startup of this server by using the INI
template defined by the modules to create a `start.ini` file with the
command:
....
[user]$ cd jetty-distribution-@project.version@
[jetty-distribution-@project.version@]$ mkdir example-base
[example-base]$ cd example-base
[example-base]$ ls -la
total 8
drwxrwxr-x 2 user webgroup 4096 Oct 4 11:49 ./
drwxrwxr-x 12 user webgroup 4096 Oct 4 11:49 ../
[example-base]$ java -jar $JETTY_HOME/start.jar --add-to-start=http
WARNING: http initialised in ${jetty.base}/start.ini (appended)
WARNING: http enabled in ${jetty.base}/start.ini
WARNING: server initialised in ${jetty.base}/start.ini (appended)
WARNING: server enabled in ${jetty.base}/start.ini
[example-base]$ ls -la
total 12
drwxrwxr-x 2 user webgroup 4096 Oct 4 11:55 ./
drwxrwxr-x 12 user webgroup 4096 Oct 4 11:49 ../
-rw-rw-r-- 1 user webgroup 250 Oct 4 11:55 start.ini
....
Once complete, you can edit the `start.ini` file to modify any
parameters and you can run the server with the simple command:
....
[example-base]$ java -jar $JETTY_HOME/start.jar
....

View File

@ -0,0 +1,20 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup-troubleshooting]]
=== Startup Troubleshooting
[troubleshooting startup]

View File

@ -0,0 +1,291 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup-unix-service]]
=== Startup a Unix Service using jetty.sh
The Standalone Jetty distribution ships with a `bin/jetty.sh` script
that can be used by various Unix (including OSX) to manage jetty
startup.
This script is suitable for setting up Jetty as a service in Unix.
==== Quick-Start a Jetty Service
The minimum steps to get Jetty to run as a Service
....
[/opt/jetty]# tar -zxf /home/user/downloads/jetty-distribution-@project.version@.tar.gz
[/opt/jetty]# cd jetty-distribution-@project.version@/
[/opt/jetty/jetty-distribution-@project.version@]# ls
bin lib modules resources start.jar
demo-base license-eplv10-aslv20.html notice.html start.d VERSION.txt
etc logs README.TXT start.ini webapps
[/opt/jetty/jetty-distribution-@project.version@]# cp bin/jetty.sh /etc/init.d/jetty
[/opt/jetty/jetty-distribution-@project.version@]# echo JETTY_HOME=`pwd` > /etc/default/jetty
[/opt/jetty/jetty-distribution-@project.version@]# cat /etc/default/jetty
JETTY_HOME=/opt/jetty/jetty-distribution-@project.version@
[/opt/jetty/jetty-distribution-@project.version@]# service jetty start
Starting Jetty: OK Wed Nov 20 10:26:53 MST 2013
....
From this simple demonstration we can see that Jetty started
successfully as a Unix Service from the
`/opt/jetty/jetty-distribution-@project.version@` directory.
This looks all fine and dandy, however you are running a default Jetty
on the root user id.
==== Practical Setup of a Jetty Service
There are various ways this can be accomplished, mostly depending on
your Unix environment (and possibly corporate policies)
The techniques outlined here assume an installation on Linux
(demonstrated on Ubuntu 12.04.3 LTS).
Prepare some empty directories to work with.
....
# mkdir -p /opt/jetty
# mkdir -p /opt/web/mybase
# mkdir -p /opt/jetty/temp
....
The directory purposes are as follows:
/opt/jetty::
Where the Jetty Distribution will be unpacked into
/opt/web/mybase::
Where your specific set of webapps will be located, including all of
the configuration required of the server to make them operational.
/opt/jetty/temp::
This is the temporary directory assigned to Java by the Service Layer
(this is what Java sees as the `java.io.tmpdir` System Property)
+
This is intentionally kept separate from the standard temp directory
of `/tmp`, as this location doubles as the Servlet Spec work
directory. (It is our experience that the standard temp directory is
often managed by various cleanup scripts that wreak havoc on a long
running Jetty server
Jetty $\{project.version} requires Java 7 (or greater) to run. Make sure
you have it installed.
....
# apt-get install openjdk-7-jdk
....
Or download Java 7 from:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
....
# java -version
java version "1.6.0_27"
OpenJDK Runtime Environment (IcedTea6 1.12.6) (6b27-1.12.6-1ubuntu0.12.04.2)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)
# update-alternatives --list java
/usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java
/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
# update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java 1061 auto mode
1 /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java 1061 manual mode
2 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1051 manual mode
Press enter to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java to provide /usr/bin/java (java) in manual mode.
# java -version
java version "1.7.0_25"
OpenJDK Runtime Environment (IcedTea 2.3.10) (7u25-2.3.10-1ubuntu0.12.04.2)
OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)
....
It is recommended that you create a user to specifically run Jetty. This
user should have the minimum set of privileges needed to run Jetty.
....
# useradd --user-group --shell /bin/false --home-dir /opt/jetty/temp jetty
....
This will create a user called `jetty`, belonging to the group called
`jetty`, with no shell access (aka `/bin/false`), and home directory at
`/opt/jetty/temp`.
Grab a copy of the distribution from the
link:#jetty-downloading[Official Eclipse Download Site]
Unpack it into place.
....
[/opt/jetty]# tar -zxf /home/user/Downloads/jetty-distribution-@project.version@.tar.gz
[/opt/jetty]# ls -F
jetty-distribution-@project.version@/
[/opt/jetty]# mkdir /opt/jetty/temp
....
It might seem strange or undesirable to unpack the first portion of the
jetty-distribution directory name too. But starting with Jetty 9.1 the
split between `${jetty.home}` and `${jetty.base}` allows for easier
upgrades of Jetty itself while isolating your webapp specific
configuration.
The `/opt/jetty/temp` directory is created as a durable place for Jetty
to use for temp and working directories. Many Unix systems will
periodically clean out the /tmp directory, this behavior is undesired in
a Servlet container and has been known to cause problems. This durable
directory at `/opt/jetty/temp` solves for that behavior.
The directory at `/opt/web/mybase` is going to be a `${jetty.base}`, so
lets configure it to hold your webapp and its configuration.
____
[TIP]
In past versions of Jetty, you would configure / modify / add to the jetty-distribution directory directly. While this is still supported, we encourage you to setup a proper `${jetty.base}` directory, as it will benefit you with easier jetty-distribution upgrades in the future.
____
....
# cd /opt/web/mybase/
[/opt/web/mybase]# ls
[/opt/web/mybase]# java -jar /opt/jetty/jetty-distribution-@project.version@/start.jar \
--add-to-start=deploy,http,logging
WARNING: deploy initialised in ${jetty.base}/start.ini (appended)
WARNING: deploy enabled in ${jetty.base}/start.ini
WARNING: server initialised in ${jetty.base}/start.ini (appended)
WARNING: server enabled in ${jetty.base}/start.ini
WARNING: http initialised in ${jetty.base}/start.ini (appended)
WARNING: http enabled in ${jetty.base}/start.ini
WARNING: server enabled in ${jetty.base}/start.ini
WARNING: logging initialised in ${jetty.base}/start.ini (appended)
WARNING: logging enabled in ${jetty.base}/start.ini
[/opt/web/mybase]# ls -F
start.ini webapps/
....
At this point you have configured your `/opt/web/mybase` to enable the
following modules:
deploy::
This is the module that will perform deployment of web applications
(WAR files or exploded directories), or Jetty IoC XML context
deployables, from the `/opt/web/mybase/webapps` directory.
http::
This sets up a single Connector that listens for basic HTTP requests.
+
See the created `start.ini` for configuring this connector
logging::
When running Jetty as a service it is very important to have logging
enabled. This module will enable the basic STDOUT and STDERR capture
logging to the `/opt/web/mybase/logs/` directory.
See xref:start-jar[] for more details and options on setting
up and configuring a `${jetty.base}` directory.
Copy your war file into place.
....
# cp /home/user/projects/mywebsite.war /opt/web/mybase/webapps/
....
Most service installations will want jetty to run on port 80, now is
your opportunity to change this from the default value of `8080` to
`80`.
Edit the `/opt/web/mybase/start.ini` and change the `jetty.http.port`
value.
....
# grep jetty.http.port /opt/web/mybase/start.ini
jetty.port=80
....
Change the permissions on the Jetty distribution, and your webapp
directories so that the user you created can access it.
....
# chown --recursive jetty /opt/jetty
# chown --recursive jetty /opt/web/mybase
....
Next we need to make the Unix System aware that we have a new Jetty
Service that can be managed by the standard `service` calls.
....
# cp /opt/jetty/jetty-distribution-@project.version@/bin/jetty.sh /etc/init.d/jetty
# echo "JETTY_HOME=/opt/jetty/jetty-distribution-@project.version@" > /etc/default/jetty
# echo "JETTY_BASE=/opt/web/mybase" >> /etc/default/jetty
# echo "TMPDIR=/opt/jetty/temp" >> /etc/default/jetty
....
Test out the configuration
....
# service jetty status
Checking arguments to Jetty:
START_INI = /opt/web/mybase/start.ini
JETTY_HOME = /opt/jetty/jetty-distribution-@project.version@
JETTY_BASE = /opt/web/mybase
JETTY_CONF = /opt/jetty/jetty-distribution-@project.version@/etc/jetty.conf
JETTY_PID = /var/run/jetty.pid
JETTY_START = /opt/jetty/jetty-distribution-@project.version@/start.jar
JETTY_LOGS = /opt/web/mybase/logs
CLASSPATH =
JAVA = /usr/bin/java
JAVA_OPTIONS = -Djetty.state=/opt/web/mybase/jetty.state
-Djetty.logs=/opt/web/mybase/logs
-Djetty.home=/opt/jetty/jetty-distribution-@project.version@
-Djetty.base=/opt/web/mybase
-Djava.io.tmpdir=/opt/jetty/temp
JETTY_ARGS = jetty-logging.xml jetty-started.xml
RUN_CMD = /usr/bin/java
-Djetty.state=/opt/web/mybase/jetty.state
-Djetty.logs=/opt/web/mybase/logs
-Djetty.home=/opt/jetty/jetty-distribution-@project.version@
-Djetty.base=/opt/web/mybase
-Djava.io.tmpdir=/opt/jetty/temp
-jar /opt/jetty/jetty-distribution-@project.version@/start.jar
jetty-logging.xml
jetty-started.xml
....
You now have a configured `${jetty.base}` in `/opt/web/mybase` and a
jetty-distribution in `/opt/jetty/jetty-distribution-@project.version@`,
along with the service level files necessary to start the service.
Go ahead, start it.
....
# service jetty start
Starting Jetty: OK Wed Nov 20 12:35:28 MST 2013
# service jetty check
..(snip)..
Jetty running pid=2958
[/opt/web/mybase]# ps u 2958
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
jetty 2958 5.3 0.1 11179176 53984 ? Sl 12:46 0:00 /usr/bin/java -Djetty...
....
You should now have your server running. Try it out

View File

@ -0,0 +1,329 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup-windows-service]]
=== Startup via Windows Service
There are no components that ship with the Jetty Distribution to make it
a formal Windows Service.
However, we recommend the use of
https://commons.apache.org/proper/commons-daemon/procrun.html[Apache
ProcRun's Daemon].
The techniques outlined here are based on Windows 7 (64-bit), using JDK
7 (64-bit), running on an Intel i7 architecture machine.
Prepare some empty directories to work with.
....
C:\> mkdir opt
C:\> cd opt
C:\opt> mkdir jetty
C:\opt> mkdir logs
C:\opt> mkdir myappbase
C:\opt> mkdir temp
C:\opt> dir
Volume in drive C has no label.
Volume Serial Number is DEAD-BEEF
Directory of C:\opt
11/21/2013 04:06 PM <DIR> .
11/21/2013 04:06 PM <DIR> ..
11/21/2013 04:06 PM <DIR> jetty
11/21/2013 04:06 PM <DIR> logs
11/21/2013 04:06 PM <DIR> myappbase
11/21/2013 04:06 PM <DIR> temp
0 File(s) 0 bytes
....
The directory purposes are as follows:
C:\opt::
Where the service layer utilities, scripts, and binaries will
eventually be
C:\opt\logs::
Where the logs for the service layer will put its own logs.
+
Typically you will see the audit logs (install/update/delete),
StdOutput, and StdError logs here.
C:\opt\jetty::
Where the Jetty Distribution will be unpacked into
C:\opt\myappbase::
Where your specific set of webapps will be located, including all of
the configuration required of the server to make them operational.
C:\opt\temp::
This is the temporary directory assigned to Java by the Service Layer
(this is what Java sees as the `java.io.tmpdir` System Property)
+
This is intentionally kept separate from the standard temp directories
of Windows, as this location doubles as the Servlet Spec work
directory.
Or download Java 7 from:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
....
C:\opt>java -version
java version "1.7.0_45"
Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)
....
Grab a copy of the ZIP distribution from the
link:#jetty-downloading[Official Eclipse Download Site]
Open it up the downloaded Zip in Windows Explorer and drag the contents
of the `jetty-distribution-@project.version@` directory into place at
`C:\opt\jetty`
Once you are complete, the contents of the `C:\opt\jetty` directory
should look like this:
....
C:\opt\jetty>dir
Volume in drive C has no label.
Volume Serial Number is C8CF-820B
Directory of C:\opt\jetty
11/21/2013 12:13 PM <DIR> .
11/21/2013 12:13 PM <DIR> ..
11/21/2013 12:13 PM <DIR> bin
11/21/2013 12:13 PM <DIR> demo-base
11/21/2013 12:13 PM <DIR> etc
11/21/2013 12:13 PM <DIR> lib
11/21/2013 12:13 PM 30,012 license-eplv10-aslv20.html
11/21/2013 12:13 PM <DIR> logs
11/21/2013 12:13 PM <DIR> modules
11/21/2013 12:13 PM 6,262 notice.html
11/21/2013 12:13 PM 1,249 README.TXT
11/21/2013 12:13 PM <DIR> resources
11/21/2013 12:13 PM <DIR> start.d
11/21/2013 12:13 PM 2,126 start.ini
11/21/2013 12:13 PM 72,226 start.jar
11/21/2013 12:13 PM 341,784 VERSION.txt
11/21/2013 12:13 PM <DIR> webapps
6 File(s) 453,659 bytes
11 Dir(s) 306,711,420,928 bytes free
....
Download a copy of the
https://commons.apache.org/proper/commons-daemon/binaries.html[native
binaries] of
https://commons.apache.org/proper/commons-daemon/binaries.html[Apache
ProcRun].
You should have downloaded a file named
`commons-daemon-1.0.15-bin-windows.zip` (version might be different).
Open this ZIP file in Windows Explorer and drag `prunmgr.exe` and
`prunsrv.exe` files into the `C:\opt` directory.
Make sure to get the right version of `prunsrv.exe` for your
environment. The ZIP file has both 32 bit and 64 bit versions of this
file.
Once you are complete, the contents of `C:\opt` directory should look
like this:
....
C:\opt> dir
Volume in drive C has no label.
Volume Serial Number is DEAD-BEEF
Directory of C:\opt
11/21/2013 04:06 PM <DIR> .
11/21/2013 04:06 PM <DIR> ..
11/21/2013 04:06 PM <DIR> jetty
11/21/2013 04:06 PM <DIR> logs
11/21/2013 04:06 PM <DIR> myappbase
11/21/2013 04:06 PM <DIR> temp
11/21/2013 04:11 PM 104,448 prunmgr.exe
11/21/2013 04:11 PM 80,896 prunsrv.exe
2 File(s) 185,344 bytes
....
Now it's time to setup your new `${jetty.base}` directory to have all of
your WebApps and the configurations that they need.
We'll start by specifying which modules we want to use (this will create
a start.ini file and also create a few empty directories for you)
....
C:\opt\myappbase>java -jar ..\jetty\start.jar --add-to-start=deploy,http,logging
WARNING: deploy initialised in ${jetty.base}\start.ini (appended)
WARNING: deploy enabled in ${jetty.base}\start.ini
MKDIR: ${jetty.base}\webapps
WARNING: server initialised in ${jetty.base}\start.ini (appended)
WARNING: server enabled in ${jetty.base}\start.ini
WARNING: http initialised in ${jetty.base}\start.ini (appended)
WARNING: http enabled in ${jetty.base}\start.ini
WARNING: server enabled in ${jetty.base}\start.ini
WARNING: logging initialised in ${jetty.base}\start.ini (appended)
WARNING: logging enabled in ${jetty.base}\start.ini
MKDIR: ${jetty.base}\logs
C:\opt\myappbase>dir
Volume in drive C has no label.
Volume Serial Number is C8CF-820B
Directory of C:\opt\myappbase
11/21/2013 12:49 PM <DIR> .
11/21/2013 12:49 PM <DIR> ..
11/21/2013 12:49 PM <DIR> logs
11/21/2013 12:49 PM 1,355 start.ini
11/21/2013 12:49 PM <DIR> webapps
1 File(s) 1,355 bytes
4 Dir(s) 306,711,064,576 bytes free
....
At this point you have configured your `C:\opt\myappbase` to enable the
following modules:
deploy::
This is the module that will perform deployment of web applications
(WAR files or exploded directories), or Jetty IoC XML context
deployables, from the `C:\opt\myappbase\webapps` directory.
http::
This sets up a single Connector that listens for basic HTTP requests.
+
See the created `start.ini` for configuring this connector
logging::
When running Jetty as a service it is very important to have logging
enabled. This module will enable the basic STDOUT and STDERR capture
logging to the `C:\opt\myappbase\logs` directory.
See xref:start-jar[] for more details and options on setting
up and configuring a `${jetty.base}` directory.
At this point you merely have to copy your WAR files into the webapps
directory.
....
C:\opt\myappbase> copy C:\projects\mywebsite.war webapps\
....
At this point you should have your directories, Java, the Jetty
distribution, and your webapp specifics setup and ready for operation.
We will use the
https://commons.apache.org/proper/commons-daemon/binaries.html[Apache
ProcRun's prunsrv.exe] to install a Jetty Service.
The basic command line syntax is outlined in the link above.
A example `install-jetty-service.bat` is provided here as an example,
based on the above directories.
[source,bat]
----
@echo off
set SERVICE_NAME=JettyService
set JETTY_HOME=C:\opt\jetty
set JETTY_BASE=C:\opt\myappbase
set STOPKEY=secret
set STOPPORT=50001
set PR_INSTALL=C:\opt\prunsrv.exe
@REM Service Log Configuration
set PR_LOGPREFIX=%SERVICE_NAME%
set PR_LOGPATH=C:\opt\logs
set PR_STDOUTPUT=auto
set PR_STDERROR=auto
set PR_LOGLEVEL=Debug
@REM Path to Java Installation
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45
set PR_JVM=%JAVA_HOME%\jre\bin\server\jvm.dll
set PR_CLASSPATH=%JETTY_HOME%\start.jar;%JAVA_HOME%\lib\tools.jar
@REM JVM Configuration
set PR_JVMMS=128
set PR_JVMMX=512
set PR_JVMSS=4000
set PR_JVMOPTIONS=-Duser.dir="%JETTY_BASE%";-Djava.io.tmpdir="C:\opt\temp";-Djetty.home="%JETTY_HOME%";-Djetty.base="%JETTY_BASE%"
@REM Startup Configuration
set JETTY_START_CLASS=org.eclipse.jetty.start.Main
set PR_STARTUP=auto
set PR_STARTMODE=java
set PR_STARTCLASS=%JETTY_START_CLASS%
set PR_STARTPARAMS=STOP.KEY="%STOPKEY%";STOP.PORT=%STOPPORT%
@REM Shutdown Configuration
set PR_STOPMODE=java
set PR_STOPCLASS=%JETTY_START_CLASS%
set PR_STOPPARAMS=--stop;STOP.KEY="%STOPKEY%";STOP.PORT=%STOPPORT%;STOP.WAIT=10
"%PR_INSTALL%" //IS/%SERVICE_NAME% ^
--DisplayName="%SERVICE_NAME%" ^
--Install="%PR_INSTALL%" ^
--Startup="%PR_STARTUP%" ^
--LogPath="%PR_LOGPATH%" ^
--LogPrefix="%PR_LOGPREFIX%" ^
--LogLevel="%PR_LOGLEVEL%" ^
--StdOutput="%PR_STDOUTPUT%" ^
--StdError="%PR_STDERROR%" ^
--JavaHome="%JAVA_HOME%" ^
--Jvm="%PR_JVM%" ^
--JvmMs="%PR_JVMMS%" ^
--JvmMx="%PR_JVMMX%" ^
--JvmSs="%PR_JVMSS%" ^
--JvmOptions="%PR_JVMOPTIONS%" ^
--Classpath="%PR_CLASSPATH%" ^
--StartMode="%PR_STARTMODE%" ^
--StartClass="%JETTY_START_CLASS%" ^
--StartParams="%PR_STARTPARAMS%" ^
--StopMode="%PR_STOPMODE%" ^
--StopClass="%PR_STOPCLASS%" ^
--StopParams="%PR_STOPPARAMS%"
if not errorlevel 1 goto installed
echo Failed to install "%SERVICE_NAME%" service. Refer to log in %PR_LOGPATH%
goto end
:installed
echo The Service "%SERVICE_NAME%" has been installed
:end
----
Configuration's of note in this batch file:
SERVICE_NAME::
This is the name of the service that Windows sees. The name in the
Services window will show this name.
STOPKEY::
This is the secret key (password) for the ShutdownMonitor, used to
issue a formal command to stop the server.
STOPPORT::
The port that the Shutdown Monitor listens on for the stop command.
+
If you have multiple Jetty servers on the same machine, this port will
need to be different for each Service.
Once you have run `prunsrv.exe //IS/<service-name>` (done for you in the
above batch file) to install the service, you can use the standard
Windows utilities to manage (start/stop/restart) the Jetty service.
Open the Service View and start your service.
image:images/windows-service-jetty.png[image,width=576]

View File

@ -0,0 +1,32 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[startup-xml-config]]
=== Managing XML Based Startup Configuration
When you see XML files on the command line for startup of Jetty, they
are always part of the Jetty IoC Configuration mechanism.
Internally, Jetty uses these XML files to build up Jetty with the
features that you wan to use.
The module mechanism present in Jetty determines the load order of the
XML files.
The Jetty Base and Jetty Home resolution logic also applies, which
allows you to override a XML file declared by a module with your XML by
simply having the same named XML in your `${jetty.base}` directory
location.

View File

@ -0,0 +1,28 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[optimizing]]
== Optimizing Jetty
There are many ways to optimize Jetty, which vary depending on the situation.
Are you trying to optimize for number of requests within a given amount of time?
Are you trying to optimize the serving of static content?
Do you have a large bit of hardware that you want to give entirely over to Jetty to use to its heart's delight?
Here are a few of the many different ways to optimize Jetty.
include::garbage-collection.adoc[]
include::high-load.adoc[]
include::limit-load.adoc[]

View File

@ -0,0 +1,70 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[garbage-collection]]
=== Garbage Collection
Tuning the JVM garbage collection (GC) can greatly improve Jetty performance.
Specifically, you can avoid pauses while the system performs full garbage collections.
Optimal tuning of the GC depends on the behaviour of the application and requires detailed analysis, however there are general recommendations.
See official https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/[Java 8 Garbage Collection documentation] for further assistance.
[[tuning-examples]]
==== Tuning Examples
These options are general to the Oracle JVM, and work in a Java 8 installation.
They provide good information about how your JVM is running; based on that initial information, you can then tune more finely.
The most important thing you can do for yourself when worrying about GC is to capture the GC activity so that you can analyze what is happening and how often it happens.
....
-verbose:gc
-Xloggc:/path/to/myjettybase/logs/gc.log
-XX:+PrintGCDateStamps
-XX:+PrintGCTimeStamps
-XX:+PrintGCDetails
-XX:+PrintTenuringDistribution
-XX:+PrintCommandLineFlags
-XX:+PrintReferenceGC
-XX:+PrintAdaptiveSizePolicy
....
There are not many recommended options for GC that can apply to nearly all users.
However, the most obvious one is to disable explicit GC (this is performed regularly by RMI and can introduce an abnormal amount of GC pauses)
....
-XX:+DisableExplicitGC
....
Before you apply any other GC tuning options, monitor your GC logs to see if https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/cms.html[tuning the CMS] makes sense for your environment.
A common setup for those just starting out with GC tuning is included below for reference reasons.
____
[CAUTION]
This example configuration below could have a negative effect on your application performance, so continued monitoring of your GC log before and after is highly recommended to know if the configuration was beneficial or not.
____
....
-XX:MaxGCPauseMillis=250
-XX:+UseConcMarkSweepGC
-XX:ParallelCMSThreads=2
-XX:+CMSClassUnloadingEnabled
-XX:+UseCMSCompactAtFullCollection
-XX:CMSInitiatingOccupancyFraction=80
....

View File

@ -0,0 +1,157 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[high-load]]
=== High Load
Configuring Jetty for high load, whether for load testing or for production, requires that the operating system, the JVM, Jetty, the application, the network and the load generation all be tuned.
==== Load Generation for Load Testing
The load generation machines must have their OS, JVM, etc., tuned just as much as the server machines.
The load generation should not be over the local network on the server machine, as this has unrealistic performance and latency as well as different packet sizes and transport characteristics.
The load generator should generate a realistic load:
* A common mistake is that load generators often open relatively few connections that are extremely busy sending as many requests as possible over each connection.
This causes the measured throughput to be limited by request latency (see http://blogs.webtide.com/gregw/entry/lies_damned_lies_and_benchmarks[Lies, Damned Lies and Benchmarks] for an analysis of such an issue).
* Another common mistake is to use TCP/IP for a single request, and to open many, many short-lived connections.
This often results in accept queues filling and limitations due to file descriptor and/or port starvation.
* A load generator should model the traffic profile from the normal clients of the server.
For browsers, this is often between two and six connections that are mostly idle and that are used in sporadic bursts with read times in between.
The connections are typically long held HTTP/1.1 connections.
* Load generators should be written in asynchronous programming style, so that a limited number of threads does not restrict the maximum number of users that can be simulated.
If the generator is not asynchronous, a thread pool of 2000 may only be able to simulate 500 or fewer users.
The Jetty HttpClient is an ideal choice for building a load generator, as it is asynchronous and can simulate many thousands of connections (see the CometD Load Tester for a good example of a realistic load generator).
==== Operating System Tuning
Both the server machine and any load generating machines need to be tuned to support many TCP/IP connections and high throughput.
===== Linux
Linux does a reasonable job of self-configuring TCP/IP, but there are a few limits and defaults that you should increase. You can configure most of them in `/etc/security/limits.conf` or via `sysctl`.
====== TCP Buffer Sizes
You should increase TCP buffer sizes to at least 16MB for 10G paths and tune the auto-tuning (although you now need to consider buffer bloat).
....
$ sysctl -w net.core.rmem_max=16777216
$ sysctl -w net.core.wmem_max=16777216
$ sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216"
$ sysctl -w net.ipv4.tcp_wmem="4096 16384 16777216"
....
====== Queue Sizes
`net.core.somaxconn` controls the size of the connection listening queue.
The default value is 128; if you are running a high-volume server and connections are getting refused at a TCP level, you need to increase this.
This is a very tweakable setting in such a case: if you set it too high, resource problems occur as it tries to notify a server of a large number of connections, and many remain pending, but if you set it too low, refused connections occur.
....
$ sysctl -w net.core.somaxconn=4096
....
The `net.core.netdev_max_backlog` controls the size of the incoming packet queue for upper-layer (java) processing.
The default (2048) may be increased and other related parameters (TODO MORE EXPLANATION) adjusted with:
....
$ sysctl -w net.core.netdev_max_backlog=16384
$ sysctl -w net.ipv4.tcp_max_syn_backlog=8192
$ sysctl -w net.ipv4.tcp_syncookies=1
....
====== Ports
If many outgoing connections are made (for example, on load generators), the operating system might run low on ports. Thus it is best to increase the port range, and allow reuse of sockets in TIME_WAIT:
....
$ sysctl -w net.ipv4.ip_local_port_range="1024 65535"
$ sysctl -w net.ipv4.tcp_tw_recycle=1
....
====== File Descriptors
Busy servers and load generators may run out of file descriptors as the system defaults are normally low.
These can be increased for a specific user in `/etc/security/limits.conf`:
....
theusername hard nofile 40000
theusername soft nofile 40000
....
====== Congestion Control
Linux supports pluggable congestion control algorithms.
To get a list of congestion control algorithms that are available in your kernel run:
....
$ sysctl net.ipv4.tcp_available_congestion_control
....
If cubic and/or htcp are not listed, you need to research the control algorithms for your kernel.
You can try setting the control to cubic with:
....
$ sysctl -w net.ipv4.tcp_congestion_control=cubic
....
====== Mac OS
Tips welcome.
====== Windows
Tips welcome.
====== Network Tuning
Intermediaries such as nginx can use a non-persistent HTTP/1.0 connection.
Make sure to use persistent HTTP/1.1 connections.
====== JVM Tuning
* Tune the link:garbage-collection.html#examples[Garbage Collection]
* Allocate sufficient memory
* Use the -server option
* Jetty Tuning
====== Connectors
====== Acceptors
The standard rule of thumb for the number of Accepters to configure is one per CPU on a given machine.
====== Low Resource Limits
Must not be configured for less than the number of expected connections.
====== Thread Pool
Configure with goal of limiting memory usage maximum available.
Typically >50 and <500

View File

@ -0,0 +1,45 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[limit-load]]
=== Limiting Load
To achieve optimal fair handling for all users of a server, it can be necessary to limit the resources that each user/connection can utilize so as to maximize throughput for the server or to ensure that the entire server runs within the limitations of it's runtime
==== Low Resources Monitor
An instance of link:{JDURL}/org/eclipse/jetty/server/LowResourcesMonitor.html[LowResourcesMonitor] may be added to a Jetty Server to monitor for low resources situations and to take action to limit the number of idle connections on the server.
To configure the low resources monitor, you can uncomment the jetty-lowresources.xml line from the start.ini configuration file, which has the effect of including the following XML configuration:
[source,xml]
----
include::{SRCDIR}/jetty-server/src/main/config/etc/jetty-lowresources.xml[]
----
The monitor is configured with a period in milliseconds at which it will scan the server looking for a low resources condition, which may be one of:
* If monitorThreads is configured as true and a connectors Executor is an instance of link:{JDURL}/org/eclipse/jetty/util/thread/ThreadPool.html[ThreadPool], then its isLowOnThreads() method is used to detect low resources.
* If maxConnections is configured to a number >0 then if the total number of connections from all monitored connectors exceeds this value, then low resources state is entered.
* If the maxMemory field is configured to a number of bytes >0 then if the JVMs total memory minus its idle memory exceeds this value, then low resources state is entered.
Once low resources state is detected, then the monitor will iterate over all existing connections and set their IdleTimeout to its configured lowResourcesIdleTimeout in milliseconds.
This allows the idle time of existing connections to be reduced so that the connection is quickly closed if no further request are received.
If the low resources state persists longer than the time in milliseconds configured for the maxLowResourcesTime field, the the lowResourcesIdleTimeout is repeatedly applied so that new connections as well as existing connections will be limited.
==== Denial Of Service Filter
TBD (see http://wiki.eclipse.org/Jetty/Reference/DoSFilter[DoSFilter]).

View File

@ -0,0 +1,24 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[configuring-connectors]]
== Configuring Jetty Connectors
This chapter discusses various options for configuring Jetty connectors.
include::configuring-connectors.adoc[]
include::configuring-ssl.adoc[]
include::setting-port80-access-for-non-root-user.adoc[]

View File

@ -0,0 +1,366 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[jetty-connectors]]
=== Connector Configuration Overview
Connectors are the mechanism through which Jetty accepts network
connections for various protocols. Configuring a connector is a
combination of configuring the following:
* Network parameters on the connector itself (for example: the listening
port).
* Services the connector uses (for example: executors, schedulers).
* Connection factories that instantiate and configure the protocol for
an accepted connection.
Jetty primarily uses a single connector type called
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[ServerConnector].
____
[NOTE]
Prior to Jetty 9, the type of the connector specified both the protocol and the implementation used (for example, selector-based non blocking I/O vs blocking I/O, or SSL connector vs non-SSL connector).
Jetty 9 has only a selector-based non blocking I/O connector, and a collection of link:{JDURL}/org/eclipse/jetty/server/ConnectionFactory.html[`ConnectionFactories`] now configure the protocol on the connector.
____
The standard Jetty distribution comes with the following Jetty XML files
that create and configure connectors; you should examine them as you
read this section:
link:{SRCDIR}/jetty-server/src/main/config/etc/jetty-http.xml[`jetty-http.xml`]::
Instantiates a
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`]
that accepts HTTP connections (that may be upgraded to WebSocket
connections).
link:{SRCDIR}/jetty-server/src/main/config/etc/jetty-ssl.xml[`jetty-ssl.xml`]::
Instantiates a
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`]
that accepts SSL/TLS connections. On it's own, this connector is not
functional and requires one or more of the following files to also be
configured to add
link:{JDURL}/org/eclipse/jetty/server/ConnectionFactory.html[`ConnectionFactories`]
to make the connector functional.
link:{SRCDIR}/jetty-server/src/main/config/etc/jetty-https.xml[`jetty-https.xml`]::
Adds a
link:{JDURL}/org/eclipse/jetty/server/HttpConnectionFactory.html[`HttpConnectionFactory`]
to the
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`]
configured by `jetty-ssl.xml` which combine to provide support for
HTTPS.
link:{SRCDIR}/jetty-http2/http2-server/src/main/config/etc/jetty-http2.xml[`jetty-http2.xml`]::
Adds a
link:{JDURL}/org/eclipse/jetty/http2/server/HTTP2ServerConnectionFactory.html[`Http2ServerConnectionFactory`]
to the
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`]
configured by `jetty-ssl.xml to support the http2
protocol.` Also prepends either `protonego-alpn.xml` or
`protonego-npn.xml` so that the next protocol can be negotiated, which
allows the same SSL port to handle multiple protocols.
link:{SRCDIR}/jetty-alpn/jetty-alpn-server/src/main/config/etc/jetty-alpn.xml[`jetty-alpn.xml`]::
Adds an
link:{JDURL}/org/eclipse/jetty/alpn/server/ALPNServerConnectionFactory.html[`ALPNServerConnectionFactory`]
to the
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`]
configured by `jetty-ssl.xml` which allows the one SSL connector to
support multiple protocols with the ALPN extension used to select the
protocol to be used for each connection.
Typically you need to configure very little on connectors other than set
the listening port (see link:#jetty-connectors-network-settings[Network
Settings]), and perhaps enable `X-Forwarded-For` customization (see
link:#jetty-connectors-http-configuration[HTTP Configuration]). Most
other settings are for expert configuration only.
==== Constructing a `ServerConnector`
The services a
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`]
instance uses are set by constructor injection and once instantiated
cannot be changed. Most of the services may be defaulted with null or 0
values so that a reasonable default is used, thus for most purposes only
the Server and the connection factories need to be passed to the
connector constructor. In Jetty XML (that is, in
link:{SRCDIR}/jetty-server/src/main/config/etc/jetty-http.xml[`jetty-http.xml`]),
you can do this with:
[source,xml]
----
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<!-- insert one or more factories here -->
</Array>
</Arg>
<!-- set connector fields here -->
</New>
----
You can see the other arguments that can be passed when constructing a
`ServerConnector` in the
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html#ServerConnector%28org.eclipse.jetty.server.Server,%20java.util.concurrent.Executor,%20org.eclipse.jetty.util.thread.Scheduler,%20org.eclipse.jetty.io.ByteBufferPool,%20int,%20int,%20org.eclipse.jetty.server.ConnectionFactory...%29[Javadoc].
Typically the defaults are sufficient for almost all deployments.
[[jetty-connectors-network-settings]]
==== Network Settings.
You configure connector network settings by calling setters on the
connector before it is started. For example, you can set the port with
the Jetty XML:
[source,xml]
----
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories"><!-- insert one or more factories here --></Arg>
<Set name="port">8080</Set>
</New>
----
Values in Jetty XML can also be parameterized so that they may be passed
from property files or set on the command line. Thus typically the port
is set within Jetty XML, but uses the `Property` element to be
customizable:
[source,xml]
----
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories"><!-- insert one or more factories here --></Arg>
<Set name="port"><Property name="jetty.http.port" default="8080"/></Set>
</New>
----
The network settings that you can set on the
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`]
include:
.Connector Configuration
[width="100%",cols="22%,78%",options="header",]
|=======================================================================
|Field |Description
|host |The network interface this connector binds to as an IP address or
a hostname. If null or 0.0.0.0, bind to all interfaces.
|port |The configured port for the connector or 0 a random available
port may be used (selected port available via `getLocalPort()`).
|idleTimeout |The time in milliseconds that the connection can be idle
before it is closed.
|defaultProtocol |The name of the default protocol used to select a
`ConnectionFactory` instance. This defaults to the first
`ConnectionFactory` added to the connector.
|stopTimeout |The time in milliseconds to wait before gently stopping a
connector.
|acceptQueueSize |The size of the pending connection backlog. The exact
interpretation is JVM and operating system specific and you can ignore
it. Higher values allow more connections to wait pending an acceptor
thread. Because the exact interpretation is deployment dependent, it is
best to keep this value as the default unless there is a specific
connection issue for a specific OS that you need to address.
|reuseAddress |Allow the server socket to be rebound even if in
http://www.ssfnet.org/Exchange/tcp/tcpTutorialNotes.html[TIME_WAIT]. For
servers it is typically OK to leave this as the default true.
|soLingerTime |A value >=0 set the socket
http://stackoverflow.com/questions/3757289/tcp-option-so-linger-zero-when-its-required[SO_LINGER]
value in milliseconds. Jetty attempts to gently close all TCP/IP
connections with proper half close semantics, so a linger timeout should
not be required and thus the default is -1.
|=======================================================================
[[jetty-connectors-http-configuration]]
==== HTTP Configuration
The
link:{JDURL}/org/eclipse/jetty/server/HttpConfiguration.html[HttpConfiguration]
class holds the configuration for
link:{JDURL}/org/eclipse/jetty/server/HttpChannel.html[`HTTPChannel`]s,
which you can create 1:1 with each HTTP connection or 1:n on a
multiplexed HTTP/2 connection. Thus a `HTTPConfiguration` object is
injected into both the HTTP and HTTP/2 connection factories. To avoid
duplicate configuration, the standard Jetty distribution creates the
common `HttpConfiguration` instance in
link:{SRCDIR}/jetty-server/src/main/config/etc/jetty.xml[`jetty.xml`],
which is a `Ref` element then used in
link:{SRCDIR}/jetty-server/src/main/config/etc/jetty-http.xml[`jetty-http.xml`],
link:{SRCDIR}/jetty-server/src/main/config/etc/jetty-https.xml[`jetty-https.xml`]
and in
link:{SRCDIR}/jetty-http2/http2-server/src/main/config/etc/jetty-http2.xml[`jetty-http2.xml`]
A typical configuration of
link:{JDURL}/org/eclipse/jetty/server/HttpConfiguration.html[HttpConfiguration]
is:
[source,xml]
----
<New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Set name="secureScheme">https</Set>
<Set name="securePort"><Property name="jetty.ssl.port" default="8443" /></Set>
<Set name="outputBufferSize">32768</Set>
<Set name="requestHeaderSize">8192</Set>
<Set name="responseHeaderSize">8192</Set>
</New>
----
This example HttpConfiguration may be used by reference to the ID
"httpConfig":
[source,xml]
----
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<Item>
<New class="org.eclipse.jetty.server.HttpConnectionFactory">
<Arg name="config"><Ref refid="httpConfig" /></Arg>
</New>
</Item>
</Array>
</Arg>
<!-- ... -->
</New>
</Arg>
</Call>
----
For SSL based connectors (in `jetty-https.xml` and `jetty-http2.xml`),
the common "httpConfig" instance is used as the basis to create an SSL
specific configuration with ID "sslHttpConfig":
[source,xml]
----
<New id="sslHttpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Arg><Ref refid="httpConfig"/></Arg>
<Call name="addCustomizer">
<Arg><New class="org.eclipse.jetty.server.SecureRequestCustomizer"/></Arg>
</Call>
</New>
----
This adds a `SecureRequestCustomizer` which adds SSL Session IDs and
certificate information as request attributes.
==== SSL Context Configuration
The SSL/TLS connectors for HTTPS and HTTP/2 require a certificate to
establish a secure connection. Jetty holds certificates in standard JVM
keystores and are configured as keystore and truststores on a
link:{JDURL}/org/eclipse/jetty/util/ssl/SslContextFactory.html[`SslContextFactory`]
instance that is injected into an
link:{JDURL}/org/eclipse/jetty/server/SslConnectionFactory.html[`SslConnectionFactory`]
instance. An example using the keystore distributed with Jetty
(containing a self signed test certificate) is in
link:{SRCDIR}/jetty-server/src/main/config/etc/jetty-https.xml[`jetty-https.xml`].
Read more about SSL keystores in link:#configuring-ssl[Configuring SSL].
==== Proxy / Load Balancer Connection Configuration
Often a Connector needs to be configured to accept connections from an
intermediary such as a Reverse Proxy and/or Load Balancer deployed in
front of the server. In such environments, the TCP/IP connection
terminating on the server does not originate from the client, but from
the intermediary, so that the Remote IP and port number can be reported
incorrectly in logs and in some circumstances the incorrect server
address and port may be used.
Thus Intermediaries typically implement one of several de facto
standards to communicate to the server information about the orginal
client connection terminating on the intermediary. Jetty supports the
`X-Forwarded-For` header and the
http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt[Proxy
Protocol] mechanisms as described below.
____
[NOTE]
The XML files in the jetty distribution contain commented out examples of both the `X-Forwarded-For` and http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt[Proxy Protocol] mechanisms.
When using those examples, it is recommended that the XML in the jetty distribution is not edited.
Rather the files should be copied into a jetty base directory and then modified.
____
===== X-Forward-for Configuration
The `X-Forwarded-for` header and associated headers are a defacto
standard where intermediaries add HTTP headers to each request they
forward to describe the originating connection. These headers can be
interpreted by an instance of
link:{JDURL}/org/eclipse/jetty/server/ForwardedRequestCustomizer.html[`ForwardedRequestCustomizer`]
which can be added to a HttpConfiguration as follows:
[source,xml]
----
<New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Set name="outputBufferSize">32768</Set>
<Set name="requestHeaderSize">8192</Set>
<Set name="responseHeaderSize">8192</Set>
<Call name="addCustomizer">
<Arg><New class="org.eclipse.jetty.server.ForwardedRequestCustomizer"/></Arg>
</Call>
</New>
----
===== Proxy Protocol
The http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt[Proxy
Protocol] is a defacto standard created by HAProxy and used by
environments such as Amazon Elastic Cloud. This mechanism is independent
of any protocol, so it can be used for HTTP2, TLS etc. The information
about the client connection is sent as a small data frame on each newly
established connection. In Jetty, this protocol can be handled by the
link:{JDURL}/org/eclipse/jetty/server/ProxyConnectionFactory.html[`ProxyConnectionFactory`]
which parses the data frame and then instantiates the next
ConnectionFactory on the connection with and EndPoint that has been
customized with the data obtained about the orginal client connection.
The connection factory can be added to any
link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`]
and should be the first
link:{JDURL}/org/eclipse/jetty/server/ConnectionFactory.html[`ConnectionFactory`].
An example of adding the factory to a HTTP connector is:
[source,xml]
----
<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.ServerConnector">
<Arg name="server"><Ref refid="Server" /></Arg>
<Arg name="factories">
<Array type="org.eclipse.jetty.server.ConnectionFactory">
<Item>
<New class="org.eclipse.jetty.server.ProxyConnectionFactory"/>
</Item>
<Item>
<New class="org.eclipse.jetty.server.HttpConnectionFactory">
<Arg name="config"><Ref refid="httpConfig" /></Arg>
</New>
</Item>
</Array>
</Arg>
<Set name="host"><Property name="jetty.host" /></Set>
<Set name="port"><Property name="jetty.http.port" default="80" /></Set>
</New>
</Arg>
</Call>
----

View File

@ -0,0 +1,684 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[configuring-ssl]]
=== Configuring SSL/TLS
This document provides an overview of how to configure SSL and TLS for
Jetty.
[[tls-and-ssl-versions]]
==== TLS and SSL versions
Which browser/OS supports which protocols can be
https://en.wikipedia.org/wiki/Transport_Layer_Security#Web_browsers[found
on Wikipedia]
* TLS v1.1 and v1.2: The protocols which should be used wherever
possible. All CBC based ciphers are supported since Java 7, the new GCM
modes are supported since Java 8.
* TLS v1.0: still OK but affected by the POODLE attack too. To support
older browsers this protocol version is still needed.
* SSL v3: is now deprecated and should only be enabled if you still need
to support very old browsers like Internet Explorer 6 on Windows XP
which does not support TLS 1.0 (or is disabled by default).
[[understanding-certificates-and-keys]]
==== Understanding Certificates and Keys
Configuring SSL can be a confusing experience of keys, certificates,
protocols and formats, thus it helps to have a reasonable understanding
of the basics. The following links provide some good starting points:
* Certificates:
** http://en.tldp.org/HOWTO/SSL-Certificates-HOWTO/index.html[SSL
Certificates HOWTO]
** http://mindprod.com/jgloss/certificate.html[Mindprod Java Glossary:
Certificates]
* Keytool:
** http://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html[Keytool
for Unix]
** http://docs.oracle.com/javase/8/docs/technotes/tools/windows/keytool.html[Keytool
for Windows]
* Other tools:
** https://www.ibm.com/developerworks/mydeveloperworks/groups/service/html/communityview?communityUuid=6fb00498-f6ea-4f65-bf0c-adc5bd0c5fcc[IBM
Keyman]
* OpenSSL:
** http://www.openssl.org/support/faq.html[OpenSSL FAQ]
[[openssl-vs-keytool]]
===== OpenSSL vs. Keytool
For testing, the `keytool` utility bundled with the JDK provides the
simplest way to generate the key and certificate you need.
You can also use the OpenSSL tools to generate keys and certificates, or
to convert those that you have used with Apache or other servers. Since
Apache and other servers commonly use the OpenSSL tool suite to generate
and manipulate keys and certificates, you might already have some keys
and certificates created by OpenSSL, or you might also prefer the
formats OpenSSL produces.
If you want the option of using the same certificate with Jetty or a web
server such as Apache not written in Java, you might prefer to generate
your private key and certificate with OpenSSL.
[[configuring-jetty-for-ssl]]
===== Configuring Jetty for SSL
To configure Jetty for SSL, complete the tasks in the following
sections:
* xref:generating-key-pairs-and-certificates[]
* xref:requesting-trusted-certificate[]
* xref:loading-keys-and-certificates[]
* xref:configuring-sslcontextfactory[]
[[generating-key-pairs-and-certificates]]
===== Generating Key Pairs and Certificates
The simplest way to generate keys and certificates is to use the
`keytool` application that comes with the JDK, as it generates keys and
certificates directly into the keystore. See
xref:generating-key-pairs-and-certificates-JDK-keytool[].
If you already have keys and certificates, see
xref:loading-keys-and-certificates[] to load them into a
JSSE keystore. This section also applies if you have a renewal
certificate to replace one that is expiring.
The examples below generate only basic keys and certificates. You should
read the full manuals of the tools you are using if you want to specify:
* the key size
* the certificate expiration date
* alternate security providers
[[generating-key-pairs-and-certificates-JDK-keytool]]
====== Generating Keys and Certificates with JDK's keytool
The following command generates a key pair and certificate directly into
file `keystore`:
....
$ keytool -keystore keystore -alias jetty -genkey -keyalg RSA
....
____
[NOTE]
The DSA key algorithm certificate produces an error after loading several pages.
In a browser, it displays a message "Could not establish an encrypted connection because certificate presented by localhost as an invalid signature."
The solution is to use RSA for the key algorithm.
____
This command prompts for information about the certificate and for
passwords to protect both the keystore and the keys within it. The only
mandatory response is to provide the fully qualified host name of the
server at the "first and last name" prompt. For example:
....
$ keytool -keystore keystore -alias jetty -genkey -keyalg RSA -sigalg SHA256withRSA
Enter keystore password: password
What is your first and last name?
[Unknown]: jetty.eclipse.org
What is the name of your organizational unit?
[Unknown]: Jetty
What is the name of your organization?
[Unknown]: Mort Bay Consulting Pty. Ltd.
What is the name of your City or Locality?
[Unknown]:
What is the name of your State or Province?
[Unknown]:
What is the two-letter country code for this unit?
[Unknown]:
Is CN=jetty.eclipse.org, OU=Jetty, O=Mort Bay Consulting Pty. Ltd.,
L=Unknown, ST=Unknown, C=Unknown correct?
[no]: yes
Enter key password for <jetty>
(RETURN if same as keystore password):
$
....
You now have the minimal requirements to run an SSL connection and could
proceed directly to link:#configuring-sslcontextfactory[configure an SSL
connector]. However the browser will not trust the certificate you have
generated, and prompts the user to this effect. While what you have at
this point is often sufficient for testing, most public sites need a
trusted certificate, as shown in the section
link:#generating-csr-from-keytool[generating a CSR with keytool].
If you want to use only a self signed certificate for some kind of
internal admin panel add -validity <days> to the keytool call above,
otherwise your certificate is only valid for one month.
If you are using java 8 or later, then you may also use the SAN
extension to set one or more names that the certificate applies to:
....
$ keytool -keystore keystore -alias jetty -genkey -keyalg RSA -sigalg SHA256withRSA -ext 'SAN=dns:jetty.eclipse.org,dns:*.jetty.org'
...
....
[[generating-keys-and-certificates-openssl]]
====== Generating Keys and Certificates with OpenSSL
The following command generates a key pair in the file `jetty.key`:
....
$ openssl genrsa -aes128 -out jetty.key
....
You might also want to use the `-rand` file argument to provide an
arbitrary file that helps seed the random number generator.
The following command generates a certificate for the key into the file
` jetty.crt`:
....
$ openssl req -new -x509 -newkey rsa:2048 -sha256 -key jetty.key -out jetty.crt
....
Adding -sha256 ensures to get a certificate with the now recommended
SHA-256 signature algorithm. For the paranoid ones add -b4096 to get a
4069bits long key.
The next command prompts for information about the certificate and for
passwords to protect both the keystore and the keys within it. The only
mandatory response is to provide the fully qualified host name of the
server at the "Common Name" prompt. For example:
....
$ openssl genrsa -aes128 -out jetty.key
Generating RSA private key, 2048 bit long modulus
..............+++
......................................................................+++
e is 65537 (0x10001)
Enter pass phrase for jetty.key:
Verifying - Enter pass phrase for jetty.key:
$ openssl req -new -x509 -newkey rsa:2048 -sha256 -key jetty.key -out jetty.crt
Enter pass phrase for jetty.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Mort Bay Consulting Pty. Ltd.
Organizational Unit Name (eg, section) []:Jetty
Common Name (e.g. server FQDN or YOUR name) []:jetty.eclipse.org
Email Address []:
$
....
You now have the minimal requirements to run an SSL connection and could
proceed directly to xref:loading-keys-and-certificates[]
to load these keys and certificates into a JSSE keystore. However the
browser will not trust the certificate you have generated, and prompts
the user to this effect. While what you have at this point is often
sufficient for testing, most public sites need a trusted certificate, as
shown in the section, xref:generating-csr-from-openssl[]
to obtain a certificate.
[[using-keys-and-certificates-from-other-sources]]
====== Using Keys and Certificates from Other Sources
If you have keys and certificates from other sources, you can proceed
directly to xref:loading-keys-and-certificates[].
[[requesting-trusted-certificate]]
===== Requesting a Trusted Certificate
The keys and certificates generated with JDK's `keytool` and OpenSSL are
sufficient to run an SSL connector. However the browser will not trust
the certificate you have generated, and it will prompt the user to this
effect.
To obtain a certificate that most common browsers will trust, you need
to request a well-known certificate authority (CA) to sign your
key/certificate. Such trusted CAs include: AddTrust, Entrust, GeoTrust,
RSA Data Security, Thawte, VISA, ValiCert, Verisign, and beTRUSTed,
among others. Each CA has its own instructions (look for JSSE or OpenSSL
sections), but all involve a step that generates a certificate signing
request (CSR).
[[generating-csr-from-keytool]]
====== Generating a CSR with keytool
The following command generates the file `jetty.csr` using `keytool` for
a key/cert already in the keystore:
....
$ keytool -certreq -alias jetty -keystore keystore -file jetty.csr
....
[[generating-csr-from-openssl]]
====== Generating a CSR from OpenSSL
The following command generates the file `jetty.csr` using OpenSSL for a
key in the file `jetty.key`:
....
$ openssl req -new -key jetty.key -out jetty.csr
....
Notice that this command uses only the existing key from `jetty.key`
file, and not a certificate in `jetty.crt` as generated with OpenSSL.
You need to enter the details for the certificate again.
[[loading-keys-and-certificates]]
===== Loading Keys and Certificates
Once a CA has sent you a certificate, or if you generated your own
certificate without `keytool`, you need to load it into a JSSE keystore.
____
[NOTE]
You need both the private key and the certificate in the JSSE keystore.
You should load the certificate into the keystore used to generate the
CSR with `keytool`. If your key pair is not already in a keystore (for
example, because it has been generated with OpenSSL), you need to use
the PKCS12 format to load both key and certificate (see
link:#loading-keys-and-certificates-via-pkcks12[PKCKS12 Keys &
Certificates]).
____
[[loading-certificates-with-keytool]]
====== Loading Certificates with keytool
You can use `keytool` to load a certificate in PEM form directly into a
keystore. The PEM format is a text encoding of certificates; it is
produced by OpenSSL, and is returned by some CAs. An example PEM file
is:
....
jetty.crt
-----BEGIN CERTIFICATE-----
MIICSDCCAfKgAwIBAgIBADANBgkqhkiG9w0BAQQFADBUMSYwJAYDVQQKEx1Nb3J0
IEJheSBDb25zdWx0aW5nIFB0eS4gTHRkLjEOMAwGA1UECxMFSmV0dHkxGjAYBgNV
BAMTEWpldHR5Lm1vcnRiYXkub3JnMB4XDTAzMDQwNjEzMTk1MFoXDTAzMDUwNjEz
MTk1MFowVDEmMCQGA1UEChMdTW9ydCBCYXkgQ29uc3VsdGluZyBQdHkuIEx0ZC4x
DjAMBgNVBAsTBUpldHR5MRowGAYDVQQDExFqZXR0eS5tb3J0YmF5Lm9yZzBcMA0G
CSqGSIb3DQEBAQUAA0sAMEgCQQC5V4oZeVdhdhHqa9L2/ZnKySPWUqqy81riNfAJ
7uALW0kEv/LtlG34dOOcVVt/PK8/bU4dlolnJx1SpiMZbKsFAgMBAAGjga4wgasw
HQYDVR0OBBYEFFV1gbB1XRvUx1UofmifQJS/MCYwMHwGA1UdIwR1MHOAFFV1gbB1
XRvUx1UofmifQJS/MCYwoVikVjBUMSYwJAYDVQQKEx1Nb3J0IEJheSBDb25zdWx0
aW5nIFB0eS4gTHRkLjEOMAwGA1UECxMFSmV0dHkxGjAYBgNVBAMTEWpldHR5Lm1v
cnRiYXkub3JnggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADQQA6NkaV
OtXzP4ayzBcgK/qSCmF44jdcARmrXhiXUcXzjxsLjSJeYPJojhUdC2LQKy+p4ki8
Rcz6oCRvCGCe5kDB
-----END CERTIFICATE-----
....
The following command loads a PEM encoded certificate in the `jetty.crt`
file into a JSSE keystore:
....
$ keytool -keystore keystore -import -alias jetty -file jetty.crt -trustcacerts
....
If the certificate you receive from the CA is not in a format that
`keytool` understands, you can use the `openssl` command to convert
formats:
....
$ openssl x509 -in jetty.der -inform DER -outform PEM -out jetty.crt
....
[[loading-keys-and-certificates-via-pkcks12]]
====== Loading Keys and Certificates via PKCS12
If you have a key and certificate in separate files, you need to combine
them into a PKCS12 format file to load into a new keystore. The
certificate can be one you generated yourself or one returned from a CA
in response to your CSR.
The following OpenSSL command combines the keys in `jetty.key` and the
certificate in the `jetty.crt` file into the `jetty.pkcs12` file:
....
$ openssl pkcs12 -inkey jetty.key -in jetty.crt -export -out jetty.pkcs12
....
If you have a chain of certificates, because your CA is an intermediary,
build the PKCS12 file as follows:
....
$ cat example.crt intermediate.crt [intermediate2.crt] ... rootCA.crt > cert-chain.txt
$ openssl pkcs12 -export -inkey example.key -in cert-chain.txt -out example.pkcs12
....
The order of certificates must be from server to rootCA, as per RFC2246
section 7.4.2.
OpenSSL asks for an __export password__. A non-empty password is
required to make the next step work. Then load the resulting PKCS12 file
into a JSSE keystore with `keytool`:
....
$ keytool -importkeystore -srckeystore jetty.pkcs12 -srcstoretype PKCS12 -destkeystore keystore
....
[[renewing-certificates]]
===== Renewing Certificates
If you are updating your configuration to use a newer certificate, as
when the old one is expiring, just load the newer certificate as
described in the section,
xref:loading-keys-and-certificates[]. If you imported the
key and certificate originally using the PKCS12 method, use an alias of
"1" rather than "jetty", because that is the alias the PKCS12 process
enters into the keystore.
[[configuring-sslcontextfactory]]
==== Configuring the Jetty SslContextFactory
The generated SSL certificates from above are held in the key store are
configured in an instance of
link:{JDURL}/org/eclipse/jetty/util/ssl/SslContextFactory.html[SslContextFactory]
object.
The SslContextFactory is responsible for:
* Creating the Java `SslEngine` used by Jetty's Connectors and Jetty's
Clients (HTTP/1, HTTP/2, and WebSocket).
* Managing Keystore Access
* Managing Truststore Access
* Managing Protocol selection via Excludes / Includes list
* Managing Cipher Suite selection via Excludes / Includes list
* Managing order of Ciphers offered (important for TLS/1.2 and HTTP/2
support)
* SSL Session Caching options
* Certificate https://en.wikipedia.org/wiki/Revocation_list[Revocation
Lists] and Distribution Points (CRLDP)
* https://en.wikipedia.org/wiki/Online_Certificate_Status_Protocol[OCSP]
Support
* Client Authentication Support
For Jetty Connectors, the configured `SslContextFactory` is injected
into a specific `ServerConnector` `SslConnectionFactory`.
For Jetty Clients, the various constructors support using a configured
`SslContextFactory`.
While the SslContextFactory can operate without a keystore (this mode is
most suitable for the various Jetty Clients) it is best if you at least
configure the Keystore you are using.
setKeyStorePath::
The configured keystore to use for all SSL/TLS in configured Jetty
Connector (or Client).
+
____
[NOTE]
as a keystore is vital security information, it can be desirable to locate the file in a directory with very restricted access.
____
setKeyStorePassword::
The keystore password may be set here in plain text, or as some
protection from casual observation, it may be obfuscated using the
link:{JDURL}/org/eclipse/jetty/util/security/Password.html[Password]
class.
setTrustStorePath::
This is used if validating client certificates and is typically set to
the same path as the keystore.
setKeyManagerPassword::
is a password that is passed to the `KeyManagerFactory.init(...)`. If
there is no keymanagerpassword, then the keystorepassword is used
instead. If there is no trustmanager set, then the keystore is used as
the trust store and the keystorepassword is used as the truststore
password
setExcludeCipherSuites / setIncludeCipherSuites::
This allows for the customization of the selected Cipher Suites that
will be used by SSL/TLS
setExcludeProtocols / setIncludeProtocols::
This allows for the customization of the selected Protocols that will
be used by SSL/TLS
____
[NOTE]
When working with Includes / Excludes, it is important to know that Excludes will always win.
+
The selection process is to process the JVM list of available Cipher Suites or Protocols against the include list, then remove the excluded ones.
+
Be aware that each Include / Exclude list has a Set method (replace the
list) or Add method (append the list)
____
____
[CAUTION]
The key and truststore passwords may also be set using the system properties: `org.eclipse.jetty.ssl.keypassword` `org.eclipse.jetty.ssl.password`.
+
This is _not_ a recommended usage.
____
==== Configuring SSL in Jetty Distribution
For those of you using the Jetty Distribution, the provided modules for
https and http2 will automatically setup the SslContextFactory, the
appropriate SslConnectionFactory, and associated ServerConnectors for
you, in the correct order.
An example of this setup:
[source,plain]
----
$ cd /path/to/mybase
$ java -jar /path/to/jetty-dist/start.jar --add-to-start=https
INFO: ssl initialised (transitively) in ${jetty.base}/start.ini
INFO: https initialised in ${jetty.base}/start.ini
INFO: Base directory was modified
$ ls -l
drwxrwxr-x. 2 user group 4096 Feb 2 11:47 etc/
-rw-rw-r--. 1 user group 4259 Feb 2 11:47 start.ini
$ ls -l etc
-rw-rw-r--. 1 user group 3697 Feb 2 11:47 keystore
----
When you check your start.ini, you'll see many commented properties
ready for you to configure the SslContextFactory basics.
To highlight some of the more commonly used properties:
jetty.ssl.host::
Configures which interfaces the SSL/TLS Connector should listen on
jetty.ssl.port::
Configures which port the SSL/TLS Connector should listen on
jetty.httpConfig.securePort::
If a webapp needs to redirect to a secure version of the same
resource, then this is the port reported back on the Response
`Location` line (Having this be separate is useful if you have
something sitting in front of Jetty, such as a Load Balancer or proxy)
jetty.sslContext.keyStorePath::
Sets the location of the `keystore` that you configured with your
certificates
jetty.sslContext.keyStorePassword::
Sets the Password for the `keystore`
==== Configuring SNI
From java8, the JVM contains support for the
http://en.wikipedia.org/wiki/Server_Name_Indication[Server Name
Indicator (SNI)] extension, which allows a SSL connection handshake to
indicate one or more DNS names that it applies to. To support this, the
ExtendedSslContextFactory is used that will look for multiple X509
certificates within the keystore, each of which may have multiple DNS
names (including wildcards) associated with the
http://en.wikipedia.org/wiki/SubjectAltName[Subject Alternate Name]
extension. When using the ExtendedSSlContextFactory, the correct
certificate is automatically selected if the SNI extension is present in
the handshake.
[[configuring-sslcontextfactory-cipherSuites]]
==== Disabling/Enabling Specific Cipher Suites
For example to avoid the BEAST attack it is necessary to configure a
specific set of cipher suites. This can either be done via
link:{JDURL}/org/eclipse/jetty/util/ssl/SslContextFactory.html#setIncludeCipherSuites(java.lang.String...)[SslContext.setIncludeCipherSuites(java.lang.String...)]
or
vialink:{JDURL}/org/eclipse/jetty/util/ssl/SslContextFactory.html#setExcludeCipherSuites(java.lang.String...)[SslContext.setExcludeCipherSuites(java.lang.String...)].
____
[NOTE]
It's crucial that you use the exact names of the cipher suites as used/known by the JDK.
You can get them by obtaining an instance of SSLEngine and call getSupportedCipherSuites().
Tools like ssllabs.com might report slightly different names which will be ignored.
____
____
[NOTE]
It's recommended to install the Java Cryptography Extension (JCE) Unlimited Strength policy files in your JRE to get full strength ciphers like AES-256.
They can be found on the http://www.oracle.com/technetwork/java/javase/downloads/index.html[Java download page].
Just overwrite the two present JAR files in `<JRE_HOME>/lib/security/`
____
Both setIncludeCipherSuites and setExcludeCipherSuites can be feed by
the exact cipher suite name used in the JDK or by using regular
expressions.
If you have a need to adjust the Includes or Excludes, then this is best
done with a custom blow-in XML that configures the SslContextFactory to
suit your needs.
To do this, first create a new `${jetty.base}/etc/tweak-ssl.xml` (this
can be any name, just avoid prefixing it with "jetty-")
[source,xml]
----
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
"http://www.eclipse.org/jetty/configure_9_3.dtd">
<!-- Tweak SsslContextFactory Includes / Excludes -->
<Configure id="sslContextFactory" class="org.eclipse.jetty.util.ssl.SslContextFactory">
<!-- Mitigate SLOTH Attack -->
<Call name="addExcludeCipherSuites">
<Arg>
<Array type="String">
<Item>.*_RSA_.*SHA1$</Item>
<Item>.*_RSA_.*SHA$</Item>
<Item>.*_RSA_.*MD5$</Item>
</Array>
</Arg>
</Call>
</Configure>
----
This new XML will configure the id `sslContextFactory` some more (this
id is first created by the `ssl` module and its associated
`${jetty.home}/etc/jetty-ssl-context.xml`). You can do anything you want
with the `SslContextFactory` in use by the Jetty Distribution from this
tweak XML.
To make sure that your `${jetty.base}` uses this new XML, add it to the
end of your `${jetty.base}/start.ini`
[source,plain]
----
$ cd /path/to/mybase
$ ls -l
drwxrwxr-x. 2 user group 4096 Feb 2 11:47 etc/
-rw-rw-r--. 1 user group 4259 Feb 2 11:47 start.ini
$ tail start.ini
# Module: https
--module=https
etc/tweak-ssl.xml
$
----
____
[NOTE]
The default SslContextFactory implementation applies the latest SSL/TLS recommendations surrounding vulnerabilities in SSL/TLS.
Check the release notes (The `VERSION.txt` found in the root of the Jetty Distribution, or the http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.eclipse.jetty%22%20AND%20a%3A%22jetty-project%22[alternate (classified 'version') artifacts for the `jetty-project` component]on Maven Central) for updates.
+
The Java JVM is also applying exclusions at the JVM level, and as such, if you have a need to enable something that is generally accepted by the industry as being insecure or vulnerable you will likely have to enable it in BOTH the Java JVM and the Jetty configuration.
____
____
[TIP]
You can enable the `org.eclipse.jetty.util.ssl` named logger at DEBUG
level to see what the list of selected Protocols and Cipher suites are
at startup of Jetty.
____
Some other Include / Exclude examples:
Example: Include all ciphers which support
https://en.wikipedia.org/wiki/Forward_secrecy[Forward Secrecy] using
regex:
[source,xml]
----
<!-- Enable Forward Secrecy Ciphers.
Note: this replaces the default Include Cipher list -->
<Set name="IncludeCipherSuites">
<Array type="String">
<Item>TLS_DHE_RSA.*</Item>
<Item>TLS_ECDHE.*</Item>
</Array>
</Set>
----
Example: Exclude all old, insecure or anonymous cipher suites:
[source,xml]
----
<!-- Eliminate Old / Insecure / Anonymous Ciphers -->
<Call name="addExcludeCipherSuites">
<Arg>
<Array type="String">
<Item>.*NULL.*</Item>
<Item>.*RC4.*</Item>
<Item>.*MD5.*</Item>
<Item>.*DES.*</Item>
<Item>.*DSS.*</Item>
</Array>
</Arg>
</Call>
----
Example: Since 2014 SSLv3 is considered insecure and should be disabled.
[source,xml]
----
<!-- Eliminate Insecure Protocols -->
<Call name="addExcludeProtocols">
<Arg>
<Array type="java.lang.String">
<Item>SSL</Item>
<Item>SSLv2</Item>
<Item>SSLv2Hello</Item>
<Item>SSLv3</Item>
</Array>
</Arg>
</Call>
----
____
[NOTE]
Note that disabling SSLv3 prevents very old browsers like Internet Explorer 6 on Windows XP from connecting.
____
Example: TLS renegotiation could be disabled too to prevent an attack based on this feature.
[source,xml]
----
<Set name="renegotiationAllowed">FALSE</Set>
----

View File

@ -0,0 +1,165 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[setting-port80-access]]
=== Setting Port 80 Access for a Non-Root User
On Unix-based systems, port 80 is protected; typically only the
superuser root can open it. For security reasons, it is not desirable to
run the server as root. This page presents several options to access
port 80 as a non-root user, including using ipchains, iptables, Jetty's
SetUID feature, xinetd, and the Solaris 10 User Rights Management
Framework.
[[using-ipchains]]
==== Using ipchains
On some Linux systems you can use the _ipchains REDIRECT_ mechanism to
redirect from one port to another inside the kernel (if ipchains is not
available, then usually iptables is):
....
# /sbin/ipchains -I input --proto TCP --dport 80 -j REDIRECT 8080
....
This command instructs the system as follows: "Insert into the kernel's
packet filtering the following as the first rule to check on incoming
packets: if the protocol is TCP and the destination port is 80, redirect
the packet to port 8080". Be aware that your kernel must be compiled
with support for ipchains (virtually all stock kernels are). You must
also have the ipchains command-line utility installed. You can run this
command at any time, preferably just once, since it inserts another copy
of the rule every time you run it.
[[using-iptables]]
==== Using iptables
On many Linux systems you can use the iptables REDIRECT mechanism to
redirect from one port to another inside the kernel (if iptables is not
available, then usually ipchains is).
You need to add something like the following to the startup scripts or
your firewall rules:
....
# /sbin/iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
....
The underlying model of iptables is different from ipchains, so the
forwarding normally happens only to packets originating off-box. You
also need to allow incoming packets to port 8080 if you use iptables as
a local firewall.
Be careful to place rules like this one early in your _input_ chain.
Such rules must precede any rule that accepts the packet, otherwise the
redirection won't occur. You can insert as many rules as required if
your server needs to listen on multiple ports, as for HTTPS.
[[configuring-jetty-setuid-feature]]
==== Configuring Jetty's SetUID Feature
http://en.wikipedia.org/wiki/Setuid[SetUID] is a technique that uses
Unix-like file system access right to allow users to run an executable
that would otherwise require higher privileges.
Jetty's SetUID module allows you to run Jetty as a normal user even when
you need to run Jetty on port 80 or 443.
To use it with the jetty distribution:
1. Ensure that you have the http.mod (and
link:#quickstart-starting-https[https.mod] if you are using SSL)
link:#startup-modules[modules enabled] for the
link:#creating-jetty-base[base] you are using. The http.mod is enabled
by default in the distribution, while the
link:#quickstart-starting-https[https.mod] is only enabled in the
link:#demo-webapps-base[demo-base] directory.
2. Ensure that you have link:#quickstart-changing-jetty-port[changed
the http port] to 80 (and link:#quickstart-changing-https-port[changed
the https port] to 443 if you are using SSL).
3. Enable the setuid.mod module:
+
....
# java -jar start.jar --add-to-start=setuid
....
+
____
[NOTE]
The --add-to-start command will enable the setuid module for this and all subsequent executions of jetty.
There are other ways to enable the module, such as just for this execution.
For more information on the alternatives see the section on link:#startup-modules[Managing Startup Modules].
____
4. Edit the configuration for the setuid module to substitute the userid and groupid of the user to switch to after starting.
If you used the `--add-to-start` command, this configuration is in the `start.ini` file.
If you used the `--add-to-startd` command instead, this configuration is in the `start.d/setuid.ini `file instead.
Here are the lines to configure:
+
[source,text]
----
jetty.startServerAsPrivileged=false
jetty.username=foo
jetty.groupname=bar
jetty.umask=002
----
+
____
[NOTE]
As well as opening the connectors as root, you can also have jetty start the Server as root before changing to the non-root user.
____
5. You now need a native code library to do the user switching. This
code is hosted as part of the Jetty ToolChain project and it is released
independently from Jetty itself. You can find the source code
https://github.com/eclipsejetty.toolchain[here] in the
https://github.com/eclipse/jetty.toolchain/jetty-setuid[jetty-setuid]
project. Build it locally, which will produce a native library
appropriate for the operating system:
+
....
# mvn clean install
....
+
If you built on a linux machine you will find the native library in
`jetty-setuid/libsetuid-linux/target/libsetuid-linux.so`. If you built
on a different operating system you will find the library in a different
subdirectory, with the name containing the name of the operating system.
You might like to copy this file into your jetty distribution's lib
directory.
6. Start jetty as the root user in your base directory, providing the
location of the native library to java. Here's an example of how to do
it on the command line, assuming were are in the
link:#demo-webapps-base[demo-base] directory:
+
....
# sudo java -Djava.library.path=libsetuid-linux -jar $JETTY_HOME/start.jar
....
[[using-solaris10-user-rights-management-framework]]
==== Using the Solaris 10 User Rights Management Framework
Solaris 10 provides a User Rights Management framework that can permit
users and processes superuser-like abilities:
....
usermod -K defaultpriv=basic,net_privaddr myself
....
Now the `myself` user can bind to port 80.
Refer to the
http://docs.oracle.com/cd/E23823_01/html/816-4557/prbactm-1.html#scrolltoc[Solaris
10] and
http://docs.oracle.com/cd/E23824_01/html/821-1456/prbactm-1.html#scrolltoc[Solaris
11 Security Services documentation] for more information.

View File

@ -0,0 +1,27 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[configuring-contexts]]
== Configuring Contexts
This chapter discusses various options for configuring Jetty contexts.
include::setting-context-path.adoc[]
include::configuring-virtual-hosts.adoc[]
include::temporary-directories.adoc[]
include::serving-webapp-from-particular-port.adoc[]
include::custom-error-pages.adoc[]
include::setting-form-size.adoc[]

View File

@ -0,0 +1,268 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[configuring-virtual-hosts]]
=== Configuring Virtual Hosts
A virtual host is an alternative name, registered in DNS, for an IP
address such that multiple domain names will resolve to the same IP of a
shared server instance. If the content to be served to the aliases names
is link:#different-virtual-hosts-different-contexts[different], then a
virtual host needs to be configured for each deployed
link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html[context]
to indicate which names a context will respond to.
Virtual hosts are set on a
link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html[context]
by calling the
link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html#setVirtualHosts-java.lang.String:A-[`setVirtualHosts`]
or
link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html#addVirtualHosts-java.lang.String:A-[`addVirtualHost`]
method which can be done either
* Using a link:#deployable-descriptor-file[context XML] file in the
webapps directory (see the example in
link:{SRCDIR}/tests/test-webapps/test-jetty-webapp/src/main/config/demo-base/webapps/test.xml[test.xml]
in the jetty distribution).
* Using a `WEB-INF/jetty-web.xml` file (deprecated).
* Creating a link:#deployment-architecture[custom deployer] with a
binding to configure virtual hosts for all contexts found in the same
webapps directory.
* Calling the
link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html#setVirtualHosts-java.lang.String:A-[API]
directly on an link:#advanced-embedding[embedded] usage.
[[configuring-a-virtual-host]]
==== Virtual Host Names
Jetty supports the following styles of virtual host name:
www.hostname.com::
A fully qualified host name. It is important to list all variants as a
site may receive traffic from both www.hostname.com and just
hostname.com
*.hostname.com::
A wildcard qualified host which will match only one level of arbitrary
names. *.foo.com will match www.foo.com and m.foo.com, but not
www.other.foo.com
10.0.0.2::
An IP address may be given as a virtual host name to indicate that a
context should handle requests received on that server port that do
not have a host name specified (HTTP/0.9 or HTTP/1.0)
@ConnectorName::
A connector name, which is not strictly a virtual host, but instead
will only match requests that are received on connectors that have a
matching name set with
link:{JDURL}/org/eclipse/jetty/server/AbstractConnector.html#setName(java.lang.String)[Connector.setName(String)].
www.√integral.com::
Non ascii and
http://en.wikipedia.org/wiki/Internationalized_domain_name[IDN] domain
names can be set as virtual hosts using
http://en.wikipedia.org/wiki/Punycode[Puny Code] equivalents that may
be obtained from a
http://network-tools.com/idn-convert.asp[Punycode/IDN converters]. For
example if the non ascii domain name `www.√integral.com` is given to a
browser, then it will make a request that uses the domain name
`www.xn--integral-7g7d.com`, which is the name that should be added as
the virtual host name.
==== Example Virtual Host Configuration
Virtual hosts can be used with any context that is a subclass of
link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html[ContextHandler].
Lets look at an example where we configure a web application -
represented by the
link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[WebAppContext]
class - with virtual hosts. You supply a list of IP addresses and names
at which the web application is reachable. Suppose you have a machine
with these IP addresses and these DNS resolvable names:
* `333.444.555.666`
* `127.0.0.1`
* `www.blah.com`
* `www.blah.net`
* `www.blah.org`
Suppose you have a webapp called `blah.war`, that you want all of the
above names and addresses to be served at path "`/blah`". Here's how you
would configure the virtual hosts with a
link:#deployable-descriptor-file[context XML] file:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/blah</Set>
<Set name="war"><Property name="jetty.webapps"/>/webapps/blah.war</Set>
<Set name="virtualHosts">
<Array type="java.lang.String">
<Item>333.444.555.666</Item>
<Item>127.0.0.1</Item>
<Item>www.blah.com</Item>
<Item>www.blah.net</Item>
<Item>www.blah.org</Item>
</Array>
</Set>
</Configure>
----
[[different-virtual-hosts-different-contexts]]
==== Using Different Sets of Virtual Hosts to Select Different Contexts
You can configure different contexts to respond on different virtual
hosts by supplying a specific list of virtual hosts for each one.
For example, suppose your imaginary machine has these DNS names:
* `www.blah.com`
* `www.blah.net`
* `www.blah.org`
* `www.other.com`
* `www.other.net`
* `www.other.org `
Suppose also you have 2 webapps, one called `blah.war` that you would
like served from the `*.blah.*` names, and one called `other.war` that
you want served only from the `*.other.*` names.
Using the method of preparing link:#deployable-descriptor-files[context
XML] files, one for each webapp yields the following:
For `blah` webapp:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/blah</Set>
<Set name="war"><Property name="jetty.webapps"/>/webapps/blah.war</Set>
<Set name="virtualHosts">
<Array type="java.lang.String">
<Item>www.blah.com</Item>
<Item>www.blah.net</Item>
<Item>www.blah.org</Item>
</Array>
</Set>
</Configure>
----
These urls now resolve to the blah context (ie `blah.war`):
* `http://www.blah.com/blah`
* `http://www.blah.net/blah`
* `http://www.blah.org/blah`
For `other` webapp:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/other</Set>
<Set name="war"><Property name="jetty.webapps"/>/webapps/other.war</Set>
<Set name="virtualHosts">
<Array type="java.lang.String">
<Item>www.other.com</Item>
<Item>www.other.net</Item>
<Item>www.other.org</Item>
</Array>
</Set>
</Configure>
----
These urls now resolve to the other context (ie other.war):
* `http://www.other.com/other`
* `http://www.other.net/other`
* `http://www.other.org/other`
[[different-virtual-hosts-different-context-same-path]]
==== Using Different Sets of Virtual Hosts to Select Different Contexts at the Same Context Path
In the previous section we setup 2 different contexts to be served from
different virtual hosts at _different_ context paths. However, there is
no requirement that the context paths must be distinct: you may use the
same context path for multiple contexts, and use virtual hosts to
determine which one is served for a given request.
Consider an example where we have the same set of DNS names as before,
and the same webapps `blah.war` and `other.war`. We still want
`blah.war` to be served in response to hostnames of `*.blah.*`, and we
still want `other.war` to be served in response to `*.other.*` names.
However, we would like__all__ of our clients to use the `"/"` context
path, no matter which context is being targeted.
In other words, we want all of the following urls to map to `blah.war`:
* `http://www.blah.com/`
* `http://www.blah.net/`
* `http://www.blah.org/`
Similarly, we want the following urls to map to `other.war`:
* `http://www.other.com/`
* `http://www.other.net/`
* `http://www.other.org/`
To achieve this, we simply use the same context path of "/" for each of
our webapps, whilst still applying our different set of virtual host
names.
For foo webapp:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/</Set>
<Set name="war"><Property name="jetty.webapps"/>/webapps/foo.war</Set>
<Set name="virtualHosts">
<Array type="java.lang.String">
<Item>www.blah.com</Item>
<Item>www.blah.net</Item>
<Item>www.blah.org</Item>
</Array>
</Set>
</Configure>
----
For bar webapp:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_0.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/</Set>
<Set name="war"><Property name="jetty.webapps"/>/webapps/bar.war</Set>
<Set name="virtualHosts">
<Array type="java.lang.String">
<Item>www.other.com</Item>
<Item>www.other.net</Item>
<Item>www.other.org</Item>
</Array>
</Set>
</Configure>
----

View File

@ -0,0 +1,202 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[custom-error-pages]]
=== Creating Custom Error Pages
The following sections describe several ways to create custom error
pages in Jetty.
==== Defining error pages in web.xml
You can use the standard webapp configuration file located in
`webapp/WEB-INF/web.xml` to map errors to specific URLs with the
error-page element. This element creates a mapping between the
error-code or exception-type to the location of a resource in the web
application.
* error-code - an integer value
* exception-type - a fully qualified class name of a Java Exception type
* location - location of the resource in the webapp relative to the root
of the web application. Value should start with "/".
Error code example:
[source,xml]
----
<error-page>
<error-code>404</error-code>
<location>/jspsnoop/ERROR/404</location>
</error-page>
----
Exception example:
[source,xml]
----
<error-page>
<exception-type>java.io.IOException</exception-type>
<location>/jspsnoop/IOException</location>
</error-page>
----
The error page mappings created with the error-page element will
redirect to a normal URL within the web application and will be handled
as a normal request to that location and thus may be static content, a
JSP or a filter and/or servlet. When handling a request generated by an
error redirection, the following request attributes are set and are
available to generate dynamic content:
javax.servlet.error.exception::
The exception instance that caused the error (or null)
javax.servlet.error.exception_type::
The class name of the exception instance that caused the error (or
null)
javax.servlet.error.message::
The error message.
javax.servlet.error.request_uri::
The URI of the errored request.
javax.servlet.error.servlet_name::
The Servlet name of the servlet that the errored request was
dispatched to/
javax.servlet.error.status_code::
The status code of the error (e.g. 404, 500 etc.)
==== Configuring error pages context files
You can use context IoC XML files to configure the default error page
mappings with more flexibility than is available with `web.xml`,
specifically with the support of error code ranges. Context files are
normally located in `${jetty.home}/webapps/` (see DeployerManager for
more details) and an example of more flexible error page mapping is
below:
[source,xml]
----
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Mort Bay Consulting//DTD Configure//EN" "http://jetty.eclipse.org/configure.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/test</Set>
<Set name="war">
<SystemProperty name="jetty.home" default="."/>/webapps/test
</Set>
<!-- by Code -->
<Get name="errorHandler">
<Call name="addErrorPage">
<Arg type="int">404</Arg>
<Arg type="String">/jspsnoop/ERROR/404</Arg>
</Call>
</Get>
<!-- by Exception -->
<Get name="errorHandler">
<Call name="addErrorPage">
<Arg>
<Call class="java.lang.Class" name="forName">
<Arg type="String">java.io.IOException</Arg>
</Call>
</Arg>
<Arg type="String">/jspsnoop/IOException</Arg>
</Call>
</Get>
<!-- by Code Range -->
<Get name="errorHandler">
<Call name="addErrorPage">
<Arg type="int">500</Arg>
<Arg type="int">599</Arg>
<Arg type="String">/dump/errorCodeRangeMapping</Arg>
</Call>
</Get>
</Configure>
----
==== Custom ErrorHandler class
If no error page mapping is defined, or if the error page resource
itself has an error, then the error page will be generated by an
instance of ErrorHandler configured either the Context or the Server. An
ErrorHandler may extend the ErrorHandler class and may totally replace
the handle method to generate an error page, or it can implement some or
all of the following methods to partially modify the error pages:
[source,java]
----
void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException
void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException
void writeErrorPageHead(HttpServletRequest request, Writer writer, int code, String message) throws IOException
void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks) throws IOException
void writeErrorPageMessage(HttpServletRequest request, Writer writer, int code, String message, String uri) throws IOException
void writeErrorPageStacks(HttpServletRequest request, Writer writer) throws IOException
----
An ErrorHandler instance may be set on a Context by calling the
ContextHandler.setErrorHandler method. This can be done by embedded code
or via context IoC XML. For example:
[source,xml]
----
<Configure class="org.eclipse.jetty.server.handler.ContextHandler">
...
<Set name="errorHandler">
<New class="com.acme.handler.MyErrorHandler"/>
</Set>
...
</Configure>
----
An ErrorHandler instance may be set on the entire server by setting it
as a dependent bean on the Server instance. This can be done by calling
Server.addBean(Object) via embedded code or in jetty.xml IoC XML like:
[source,xml]
----
<Configure id="Server" class="org.eclipse.jetty.server.Server">
...
<Call name="addBean">
<Arg>
<New class="com.acme.handler.MyErrorHandler"/>
</Arg>
</Call>
...
</Configure>
----
==== Server level 404 error
You might get a 'page not found' when a request is made to the server
for a resource that is outside of any registered contexts. As an
example, you have a domain name pointing to your public server IP, yet
no context is registered with jetty to serve pages for that domain. As a
consequence, the server, by default, gives a listing of all contexts
running on the server.
One of the quickest ways to avoid this behavior is to create a catch all
context. Create a "root" web app mapped to the "/" URI. Have the
index.html redirect to whatever place with a header directive.

View File

@ -0,0 +1,80 @@
// ========================================================================
// Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
// ========================================================================
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
[[serving-webapp-from-particular-port]]
=== Serving a WebApp from a Particular Port/Connector
Sometimes it is required to serve different web applications from
different ports/connectors. The simplest way to do this is to create
multiple `Server` instances, however if contexts need to share resources
(eg data sources, authentication), or if the mapping of ports to web
applications is not cleanly divided, then the named connector mechanism
can be used.
[[creating-server-instances]]
==== Creating Multiple Server Instances
How to create multiple server instances is simply done when writing
embedded jetty code by creating multiples instances of the Server class
and configuring them as needed. This is also easy to achieve if you are
configuring your servers in XML. The id field in the Configure element
of jetty.xml files is used to identify the instance that the
configuration applies to, so to run two instances of the Server, you can
copy the jetty.xml, jetty-http.xml and other jetty configuration files
used and change the "Server" id to a new name. This can be done in the
same style and layout as the existing jetty.xml files or the multiple
XML files may be combined to a single file.
When creating new configurations for alternative server:
* Change all id="Server" to the new server
name:`<Configure id="OtherServer"
class="org.eclipse.jetty.server.Server"> `
* For all connectors for the new server change the refid in the server
argument: `<Arg name="server"><Ref
refid="OtherServer" /></Arg>`
* Make sure that any references to properties like jetty.http.port are
either renamed or replaced with absolute values
* Make sure that any deployers AppProviders refer to a different
"webapps" directory so that a different set of applications are
deployed.
[[jetty-otherserver.xml]]
===== Example Other Server XML
The following example creates another server instance and configures it
with a connector and deployer:
[source,xml]
----
include::{SRCDIR}/examples/embedded/src/main/resources/jetty-otherserver.xml[]
----
To run the other server, simply add the extra configuration file(s) to
the command line:
....
java -jar start.jar jetty-otherserver.xml
....
[[alternative]]
==== Named Connectors
It is also possible to use an extension to the virtual host mechanism
with named to connectors to make some web applications only accessible
by specific connectors. If a connector has a name "MyConnector" set
using the setName method, then this can be referenced with the special
virtual host name "@MyConnector".

Some files were not shown because too many files have changed in this diff Show More