diff --git a/documentation/jetty-asciidoctor-extensions/pom.xml b/documentation/jetty-asciidoctor-extensions/pom.xml deleted file mode 100644 index 6b538a64e505..000000000000 --- a/documentation/jetty-asciidoctor-extensions/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - 4.0.0 - - org.eclipse.jetty.documentation - documentation-parent - 10.0.22-SNAPSHOT - - jetty-asciidoctor-extensions - jar - Jetty :: Documentation :: AsciiDoctor Extensions - - - ${project.groupId}.asciidoctor.extensions - - - - - org.asciidoctor - asciidoctorj - - - jakarta.annotation - jakarta.annotation-api - - - - org.jruby - jruby-stdlib - - - - - org.eclipse.jetty.tests - jetty-home-tester - compile - - - diff --git a/documentation/jetty-asciidoctor-extensions/src/main/java/org/eclipse/jetty/docs/JavadocIncludeExtension.java b/documentation/jetty-asciidoctor-extensions/src/main/java/org/eclipse/jetty/docs/JavadocIncludeExtension.java deleted file mode 100644 index 94fe1c44620d..000000000000 --- a/documentation/jetty-asciidoctor-extensions/src/main/java/org/eclipse/jetty/docs/JavadocIncludeExtension.java +++ /dev/null @@ -1,235 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs; - -import java.io.StringReader; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Deque; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; - -import org.asciidoctor.Asciidoctor; -import org.asciidoctor.ast.Document; -import org.asciidoctor.extension.IncludeProcessor; -import org.asciidoctor.extension.PreprocessorReader; -import org.asciidoctor.jruby.extension.spi.ExtensionRegistry; -import org.xml.sax.InputSource; - -/** - *

Asciidoctor include extension that includes into - * the document the output produced by an XSL transformation of - * parts of the javadoc of a file.

- *

Example usage in an Asciidoc page:

- *
- * include::javadoc[file=Source.java,xsl=source.xsl,tags=docs]
- * 
- *

Available configuration parameters are:

- *
- *
file
- *
Mandatory, specifies the file to read the javadoc from, relative to the root of the Jetty Project source.
- *
xsl
- *
Mandatory, specifies the XSL file to use to transform the javadoc, relative to the root of the documentation source.
- *
tags
- *
Optional, specifies the name of the tagged regions of the javadoc to include.
- *
replace
- *
Optional, specifies a comma-separated pair where the first element is a regular - * expression and the second is the string replacement, applied to each included line.
- *
- *

An example javadoc could be:

- *
- * /**
- *  * <p>Class description.</p>
- *  * <!-- tag::docs -->
- *  * <p>Parameters</p>
- *  * <table>
- *  *   <tr>
- *  *     <td>param</td>
- *  *     <td>value</td>
- *  *   </tr>
- *  * </table>
- *  * <!-- end::docs -->
- *  */
- *  public class A
- *  {
- *  }
- * 
- *

The javadoc lines included in the tagged region "docs" (between {@code tag::docs} and {@code end::docs}) - * will be stripped of the asterisk at the beginning of the line and wrapped - * into a {@code <root>} element, so that it becomes a well-formed XML document.

- *

Each line of the XML document is then passed through the regular expression specified by the {@code replace} - * parameter (if any), and then transformed using the XSL file specified by the {@code xsl} parameter, - * which should produce a valid Asciidoc block which is then included in the Asciidoc documentation page.

- */ -public class JavadocIncludeExtension implements ExtensionRegistry -{ - @Override - public void register(Asciidoctor asciidoctor) - { - asciidoctor.javaExtensionRegistry().includeProcessor(JavadocIncludeExtension.JavadocIncludeProcessor.class); - } - - public static class JavadocIncludeProcessor extends IncludeProcessor - { - private static final Pattern JAVADOC_INITIAL_ASTERISK = Pattern.compile("^\\s*\\*\\s*(.*)$"); - private static final Pattern JAVADOC_INLINE_CODE = Pattern.compile("\\{@code ([^\\}]+)\\}"); - - @Override - public boolean handles(String target) - { - return "javadoc".equals(target); - } - - @Override - public void process(Document document, PreprocessorReader reader, String target, Map attributes) - { - try - { - // Document attributes are converted by Asciidoctor to lowercase. - Path jettyDocsPath = Path.of((String)document.getAttribute("project-basedir")); - Path jettyRoot = jettyDocsPath.resolve("../..").normalize(); - - String file = (String)attributes.get("file"); - if (file == null) - throw new IllegalArgumentException("Missing 'file' attribute"); - Path filePath = jettyRoot.resolve(file.trim()); - - String xsl = (String)attributes.get("xsl"); - if (xsl == null) - throw new IllegalArgumentException("Missing 'xsl' attribute"); - Path xslPath = jettyDocsPath.resolve(xsl.trim()); - - List tagList = new ArrayList<>(); - String tags = (String)attributes.get("tags"); - if (tags != null) - { - for (String tag : tags.split(",")) - { - tag = tag.trim(); - boolean exclude = tag.startsWith("!"); - if (exclude) - tag = tag.substring(1); - if (tag.isEmpty()) - throw new IllegalArgumentException("Invalid tag in 'tags' attribute: " + tags); - tagList.add(new Tag(tag, exclude)); - } - } - - String replace = (String)attributes.get("replace"); - - List contentLines = new ArrayList<>(); - contentLines.add(""); - Iterator lines = Files.lines(filePath, StandardCharsets.UTF_8).iterator(); - Deque tagStack = new ArrayDeque<>(); - while (lines.hasNext()) - { - String line = lines.next(); - - // Strip the initial Javadoc asterisk. - Matcher matcher = JAVADOC_INITIAL_ASTERISK.matcher(line); - if (matcher.matches()) - line = matcher.group(1); - - // Convert {@code X} into X - line = JAVADOC_INLINE_CODE.matcher(line).replaceAll("$1"); - - boolean keepLine = tagList.isEmpty() || tagList.stream().allMatch(tag -> tag.exclude); - - if (tagStack.isEmpty()) - { - for (Tag tag : tagList) - { - if (line.contains("tag::" + tag.name)) - tagStack.push(tag); - } - } - else - { - Tag currentTag = tagStack.peek(); - keepLine = !currentTag.exclude; - if (line.contains("end::" + currentTag.name)) - { - tagStack.pop(); - keepLine = false; - } - } - - if (keepLine) - { - if (replace == null) - contentLines.add(line); - else - contentLines.addAll(replace(line, replace)); - } - } - contentLines.add(""); - - String content = String.join("\n", contentLines); - - // Run the XML stylesheet over the remaining lines. - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - org.w3c.dom.Document xml = builder.parse(new InputSource(new StringReader(content))); - Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(xslPath.toFile())); - StringWriter output = new StringWriter(content.length()); - transformer.transform(new DOMSource(xml), new StreamResult(output)); - String asciidoc = output.toString(); - asciidoc = Arrays.stream(asciidoc.split("\n")).map(String::stripLeading).collect(Collectors.joining("\n")); - - reader.pushInclude(asciidoc, "javadoc", target, 1, attributes); - } - catch (Throwable x) - { - reader.pushInclude(x.toString(), "javadoc", target, 1, attributes); - x.printStackTrace(); - } - } - - private List replace(String line, String replace) - { - // Format is: (regexp,replacement). - String[] parts = replace.split(","); - String regExp = parts[0]; - String replacement = parts[1].replace("\\n", "\n"); - return List.of(line.replaceAll(regExp, replacement).split("\n")); - } - - private static class Tag - { - private final String name; - private final boolean exclude; - - private Tag(String name, boolean exclude) - { - this.name = name; - this.exclude = exclude; - } - } - } -} diff --git a/documentation/jetty-asciidoctor-extensions/src/main/java/org/eclipse/jetty/docs/JettyIncludeExtension.java b/documentation/jetty-asciidoctor-extensions/src/main/java/org/eclipse/jetty/docs/JettyIncludeExtension.java deleted file mode 100644 index 35d7abb9d167..000000000000 --- a/documentation/jetty-asciidoctor-extensions/src/main/java/org/eclipse/jetty/docs/JettyIncludeExtension.java +++ /dev/null @@ -1,270 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.asciidoctor.Asciidoctor; -import org.asciidoctor.ast.Document; -import org.asciidoctor.extension.IncludeProcessor; -import org.asciidoctor.extension.PreprocessorReader; -import org.asciidoctor.jruby.extension.spi.ExtensionRegistry; -import org.eclipse.jetty.tests.hometester.JettyHomeTester; - -/** - *

Asciidoctor include extension that includes into - * the document the output produced by starting a Jetty server.

- *

Example usage in an Asciidoc page:

- *
- * include::jetty[setupArgs="--add-modules=http,deploy,demo-simple",highlight="WebAppContext"]
- * 
- *

Available configuration parameters are:

- *
- *
setupModules
- *
Optional, specifies a comma-separated list of files to copy to {@code $JETTY_BASE/modules}.
- *
setupArgs
- *
Optional, specifies the arguments to use in a Jetty server setup run. - * If missing, no Jetty server setup run will be executed. - * The output produced by this run is ignored.
- *
args
- *
Optional, specifies the arguments to use in a Jetty server run. - * If missing, a Jetty server run will be executed with no arguments. - * The output produced by this run is included in the Asciidoc document.
- *
replace
- *
Optional, specifies a comma-separated pair where the first element is a regular - * expression and the second is the string replacement.
- *
delete
- *
Optional, specifies a regular expression that when matched deletes the line
- *
highlight
- *
Optional, specifies a regular expression that matches lines that should be highlighted. - * If missing, no line will be highlighted. - * If the regular expression contains capturing groups, only the text matching - * the groups is highlighted, not the whole line. - *
- *
callouts
- *
Optional, specifies a comma-separated pair where the first element is a callout - * pattern, and the second element is a comma-separated list of regular expressions, - * each matching a single line, that get a callout added at the end of the line.
- *
- * - * @see JettyHomeTester - */ -public class JettyIncludeExtension implements ExtensionRegistry -{ - public void register(Asciidoctor asciidoctor) - { - asciidoctor.javaExtensionRegistry().includeProcessor(JettyIncludeProcessor.class); - } - - public static class JettyIncludeProcessor extends IncludeProcessor - { - @Override - public boolean handles(String target) - { - return "jetty".equals(target); - } - - @Override - public void process(Document document, PreprocessorReader reader, String target, Map attributes) - { - try - { - String jettyVersion = (String)document.getAttribute("project-version"); - // Document attributes are converted by Asciidoctor to lowercase. - Path jettyDocsPath = Path.of((String)document.getAttribute("project-basedir")); - Path jettyHome = jettyDocsPath.resolve("target/jetty-home-" + jettyVersion).normalize(); - - JettyHomeTester jetty = JettyHomeTester.Builder.newInstance() - .jettyHome(jettyHome) - .mavenLocalRepository((String)document.getAttribute("maven-local-repo")) - .build(); - - String setupModules = (String)attributes.get("setupModules"); - if (setupModules != null) - { - Path jettyBaseModules = jetty.getJettyBase().resolve("modules"); - Files.createDirectories(jettyBaseModules); - String[] modules = setupModules.split(","); - for (String module : modules) - { - Path sourcePath = jettyDocsPath.resolve(module.trim()); - Files.copy(sourcePath, jettyBaseModules.resolve(sourcePath.getFileName())); - } - } - - String setupArgs = (String)attributes.get("setupArgs"); - if (setupArgs != null) - { - try (JettyHomeTester.Run setupRun = jetty.start(setupArgs.split(" "))) - { - setupRun.awaitFor(15, TimeUnit.SECONDS); - } - } - - String args = (String)attributes.get("args"); - args = args == null ? "" : args + " "; - args += jettyHome.resolve("etc/jetty-halt.xml"); - try (JettyHomeTester.Run run = jetty.start(args.split(" "))) - { - run.awaitFor(15, TimeUnit.SECONDS); - String output = captureOutput(document, attributes, run); - reader.pushInclude(output, "jettyHome_run", target, 1, attributes); - } - } - catch (Throwable x) - { - reader.pushInclude(x.toString(), "jettyHome_run", target, 1, attributes); - x.printStackTrace(); - } - } - - private String captureOutput(Document document, Map attributes, JettyHomeTester.Run run) - { - Stream lines = run.getLogs().stream() - .map(line -> redact(line, System.getProperty("java.home"), "/path/to/java.home")) - .map(line -> redact(line, run.getConfig().getMavenLocalRepository(), "/path/to/maven.repository")) - .map(line -> redact(line, run.getConfig().getJettyHome().toString(), "/path/to/jetty.home")) - .map(line -> redact(line, run.getConfig().getJettyBase().toString(), "/path/to/jetty.base")) - .map(line -> regexpRedact(line, "(^| )[^ ]+/etc/jetty-halt\\.xml", "")) - .map(line -> redact(line, (String)document.getAttribute("project-version"), (String)document.getAttribute("version"))); - lines = replace(lines, (String)attributes.get("replace")); - lines = delete(lines, (String)attributes.get("delete")); - lines = denoteLineStart(lines); - lines = highlight(lines, (String)attributes.get("highlight")); - lines = callouts(lines, (String)attributes.get("callouts")); - return lines.collect(Collectors.joining(System.lineSeparator())); - } - - private String redact(String line, String target, String replacement) - { - if (target != null && replacement != null) - return line.replace(target, replacement); - return line; - } - - private String regexpRedact(String line, String regexp, String replacement) - { - if (regexp != null && replacement != null) - return line.replaceAll(regexp, replacement); - return line; - } - - private Stream replace(Stream lines, String replace) - { - if (replace == null) - return lines; - - // Format is: (regexp,replacement). - String[] parts = replace.split(","); - String regExp = parts[0]; - String replacement = parts[1].replace("\\n", "\n"); - - return lines.flatMap(line -> Stream.of(line.replaceAll(regExp, replacement).split("\n"))); - } - - private Stream delete(Stream lines, String delete) - { - if (delete == null) - return lines; - Pattern regExp = Pattern.compile(delete); - return lines.filter(line -> !regExp.matcher(line).find()); - } - - private Stream denoteLineStart(Stream lines) - { - // Matches lines that start with a date such as "2020-01-01 00:00:00.000:". - Pattern regExp = Pattern.compile("(^\\d{4}[^:]+:[^:]+:[^:]+:)"); - return lines.map(line -> - { - Matcher matcher = regExp.matcher(line); - if (!matcher.find()) - return line; - return "**" + matcher.group(1) + "**" + line.substring(matcher.end(1)); - }); - } - - private Stream highlight(Stream lines, String highlight) - { - if (highlight == null) - return lines; - - Pattern regExp = Pattern.compile(highlight); - return lines.map(line -> - { - Matcher matcher = regExp.matcher(line); - if (!matcher.find()) - return line; - - int groupCount = matcher.groupCount(); - - // No capturing groups, highlight the whole line. - if (groupCount == 0) - return "##" + line + "##"; - - // Highlight the capturing groups. - StringBuilder result = new StringBuilder(line.length() + 4 * groupCount); - int start = 0; - for (int groupIndex = 1; groupIndex <= groupCount; ++groupIndex) - { - int matchBegin = matcher.start(groupIndex); - result.append(line, start, matchBegin); - result.append("##"); - int matchEnd = matcher.end(groupIndex); - result.append(line, matchBegin, matchEnd); - result.append("##"); - start = matchEnd; - } - result.append(line, start, line.length()); - return result.toString(); - }); - } - - private Stream callouts(Stream lines, String callouts) - { - if (callouts == null) - return lines; - - // Format is (prefix$Nsuffix,regExp...). - String[] parts = callouts.split(","); - String calloutPattern = parts[0]; - List regExps = Stream.of(parts) - .skip(1) - .map(Pattern::compile) - .collect(Collectors.toList()); - - AtomicInteger index = new AtomicInteger(); - - return lines.map(line -> - { - int regExpIndex = index.get(); - if (regExpIndex == regExps.size()) - return line; - Pattern regExp = regExps.get(regExpIndex); - if (!regExp.matcher(line).find()) - return line; - int calloutIndex = index.incrementAndGet(); - return line + calloutPattern.replace("$N", String.valueOf(calloutIndex)); - }); - } - } -} diff --git a/documentation/jetty-asciidoctor-extensions/src/main/resources/META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry b/documentation/jetty-asciidoctor-extensions/src/main/resources/META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry deleted file mode 100644 index b7e6f757272e..000000000000 --- a/documentation/jetty-asciidoctor-extensions/src/main/resources/META-INF/services/org.asciidoctor.jruby.extension.spi.ExtensionRegistry +++ /dev/null @@ -1,2 +0,0 @@ -org.eclipse.jetty.docs.JettyIncludeExtension -org.eclipse.jetty.docs.JavadocIncludeExtension diff --git a/documentation/jetty-documentation/pom.xml b/documentation/jetty-documentation/pom.xml deleted file mode 100644 index a920aa738573..000000000000 --- a/documentation/jetty-documentation/pom.xml +++ /dev/null @@ -1,283 +0,0 @@ - - - - 4.0.0 - - org.eclipse.jetty.documentation - documentation-parent - 10.0.22-SNAPSHOT - - jetty-documentation - jar - Jetty :: Documentation - - - ${project.groupId} - - - - - org.eclipse.jetty - jetty-alpn-server - - - org.eclipse.jetty - jetty-client - - - org.eclipse.jetty - jetty-home - ${project.version} - zip - true - - - org.eclipse.jetty - jetty-jmx - - - org.eclipse.jetty - jetty-nosql - - - org.eclipse.jetty - jetty-rewrite - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-servlet - - - org.eclipse.jetty - jetty-servlets - - - org.eclipse.jetty - jetty-unixdomain-server - - - org.eclipse.jetty - jetty-util-ajax - - - org.eclipse.jetty - jetty-webapp - - - org.eclipse.jetty.fcgi - fcgi-client - - - org.eclipse.jetty.http2 - http2-http-client-transport - - - org.eclipse.jetty.http2 - http2-server - - - org.eclipse.jetty.http3 - http3-http-client-transport - - - org.eclipse.jetty.http3 - http3-server - - - org.eclipse.jetty.memcached - jetty-memcached-sessions - - - org.eclipse.jetty.toolchain - jetty-servlet-api - - - org.eclipse.jetty.websocket - websocket-javax-server - - - org.eclipse.jetty.websocket - websocket-jetty-client - - - org.eclipse.jetty.websocket - websocket-jetty-server - - - org.eclipse.jetty - jetty-slf4j-impl - runtime - - - - - - - maven-assembly-plugin - - - src/main/assembly/html.xml - - - - - make-assembly - - single - - package - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - unpack-jetty-home - - unpack - - generate-resources - - - - org.eclipse.jetty - jetty-home - ${project.version} - zip - - - ${project.build.directory}/ - - - - - - maven-enforcer-plugin - - false - - - [17,) - [ERROR] OLD JDK [${java.version}] in use. Jetty documentation ${project.version} MUST use JDK 17 or newer - - - - - - org.asciidoctor - asciidoctor-maven-plugin - - html5 - - asciidoctor-diagram - - - ${project.basedir} - ${project.version} - ${settings.localRepository} - ${project.version} - ../programming-guide/index.html - ../operations-guide/index.html - https://eclipse.dev/jetty/javadoc/jetty-10 - - - - - org.apache.httpcomponents - httpclient - ${apache.httpclient.version} - - - org.apache.httpcomponents - httpcore - ${apache.httpcore.version} - - - org.asciidoctor - asciidoctorj-diagram - ${asciidoctorj-diagram.version} - - - org.eclipse.jetty.documentation - jetty-asciidoctor-extensions - ${project.version} - - - jakarta.annotation - jakarta.annotation-api - - - - - - - contribution-guide - - process-asciidoc - - prepare-package - - ${basedir}/src/main/asciidoc/contribution-guide - index.adoc - ${project.build.directory}/html/contribution-guide - - - - index - - process-asciidoc - - prepare-package - - src/main/asciidoc - index.adoc - ${project.build.directory}/html - - - - old_docs - - process-asciidoc - - prepare-package - - ${basedir}/src/main/asciidoc/old_docs - index.adoc - ${project.build.directory}/html/old_docs - - - - operations-guide - - process-asciidoc - - prepare-package - - src/main/asciidoc/operations-guide - index.adoc - ${project.build.directory}/html/operations-guide - - - - programming-guide - - process-asciidoc - - prepare-package - - ${basedir}/src/main/asciidoc/programming-guide - index.adoc - ${project.build.directory}/html/programming-guide - - - - - - - diff --git a/documentation/jetty-documentation/src/main/asciidoc/config.adoc b/documentation/jetty-documentation/src/main/asciidoc/config.adoc deleted file mode 100644 index e143005a083b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/config.adoc +++ /dev/null @@ -1,35 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -:author: Jetty Developers -:email: jetty-dev@eclipse.org -:revnumber: {version} -:revdate: {localdate} - -:toc: left -:toclevels: 5 - -:idseparator: - -:sectlinks: -:sectanchors: - -:source-highlighter: coderay - -// Use fonts for admonitions. -:icons: font - -// HTML specific directives -ifdef::backend-html5[] -:safe-mode-unsafe: -:linkcss: -endif::[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/index.adoc b/documentation/jetty-documentation/src/main/asciidoc/index.adoc deleted file mode 100644 index 82fdd11c0fa7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/index.adoc +++ /dev/null @@ -1,34 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -:doctitle: Eclipse Jetty Documentation - -include::config.adoc[] - -== xref:operations-guide/index.adoc[Jetty Operations Guide] - -The Eclipse Jetty Operations Guide targets sysops, devops, and developers who want to install Eclipse Jetty as a standalone server to deploy web applications. - -== xref:programming-guide/index.adoc[Jetty Programming Guide] - -The Eclipse Jetty Programming Guide targets developers who want to use the Eclipse Jetty libraries in their applications, and advanced sysops/devops that want to customize the deployment of web applications. - -== https://jetty.org/docs/contribution-guide/index.html[Jetty Contribution Guide] - -The Eclipse Jetty Programming Guide targets developers that wish to contribute to the Jetty Project with code patches or documentation improvements. - -== xref:old_docs/index.adoc[OLD Jetty Documentation] - -The guides above are a work in progress for the current Jetty version. - -The old Jetty documentation refers to old Jetty versions, and it is currently being ported to the current Jetty version. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/alpn/alpn.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/alpn/alpn.adoc deleted file mode 100644 index a0a80eb8515f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/alpn/alpn.adoc +++ /dev/null @@ -1,100 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[alpn]] -=== Introducing ALPN - -Application Layer Protocol Negotiation (ALPN) is a TLS extension that allows client and server to negotiate the application protocol that they will use to communicate within the encryption provided by TLS. - -Any protocol can be negotiated by ALPN within a TLS connection; the protocols that are most commonly negotiated are HTTP/2 and HTTP/1.1. - -Browsers only support HTTP/2 over TLS by negotiating the HTTP/2 protocol via ALPN. -You need to configure the server to support TLS and ALPN if you want browsers to use -the HTTP/2 protocol, otherwise they will default to HTTP/1.1. - -In the Jetty project, ALPN is _used_ in two artifacts: `jetty-alpn-client` and `jetty-alpn-server`, respectively for the client and for the server. - -When using Jetty as a standalone server via the Jetty distribution, the `jetty-alpn-server` artifact is automatically included in the server classpath by the Jetty module system. - -When using Jetty embedded, the `jetty-alpn-client` and `jetty-alpn-server` artifacts must be included in the classpath, respectively for client and server use cases. - -The ALPN implementation is _provided_ to these two artifacts with the following three options: - -* For JDK 8 or later, a provider based on the link:#conscrypt[Conscrypt security provider] -** Works with JDK 8 or later and provides improved performance -** Binds to the OpenSSL native library shipped by Conscrypt and is therefore only available on the platforms supported by Conscrypt -* For JDK 9 or later, a provider based on the ALPN APIs present in the JDK -** Works with JDK 9 or later, pure Java implementation -** Lower performance than Conscrypt - -The first, 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. - -Each provider above provides an ALPN _service_ implementation; Jetty uses the `ServiceLoader` mechanism to load these service implementations. -At least one valid provider must be present in the server classpath. -For example, using JDK 8 with the JDK 9 ALPN provider is an _invalid_ combination. -The absence of valid implementations is an error at startup (see also the link:#alpn-troubleshooting[troubleshooting section]). - -There may be multiple ALPN service providers in the server classpath. -When a new connection is created, an `SSLEngine` instance is associated to it; each `SSLEngine` is passed all service implementations, until one accepts it. - -It is therefore possible to have multiple providers active at the same time, for example the JDK 9 provider and the Conscrypt provider, and at runtime the correct one will be chosen by the Jetty runtime. - -[[alpn-conscrypt]] -==== ALPN and Conscrypt - -When using JDK 8 or later, you can use the https://conscrypt.org/[Conscrypt] security provider to provide the ALPN service implementation. - -Conscrypt binds natively to BoringSSL (a fork of OpenSSL by Google), so ALPN will be supported via the support provided by BoringSSL (bundled together with Conscrypt). - -When using Jetty as a standalone server via the Jetty distribution, ALPN is enabled by enabling the `conscrypt` module. - -When using Jetty embedded, ALPN is enabled by the `jetty-alpn-conscrypt-client` and `jetty-alpn-conscrypt-server` artifacts, respectively for client usage and server usage. -In addition, you also need the Conscrypt artifacts, typically the `org.conscrypt:conscrypt-openjdk-uber` artifact. -All these artifacts must be added to the classpath. - -[[alpn-jdk9]] -==== ALPN and JDK 9 - -When using JDK 9 or later and Jetty as a standalone server via the Jetty distribution, ALPN support is automatically enabled when the `http2` module is enabled. -This enables transitively the `alpn-9` module which puts the `jetty-alpn-java-server` artifact in the server classpath, providing the ALPN JDK 9 service implementation. - -When using JDK 9 or later and Jetty embedded, the ALPN service implementation is provided by the `jetty-alpn-java-client` and `jetty-alpn-java-server` artifacts, respectively for client usage and server usage, and must be added to the classpath. - -[[alpn-osgi]] -===== Starting in OSGi - -To use ALPN in an OSGi environment, in addition to what described above, 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 https://repo1.maven.org/maven2/org/eclipse/jetty/osgi/jetty-osgi-alpn/[jetty-osgi-alpn jar] from Maven Central. - -____ -[NOTE] -OSGi *requires* a `ServiceLoader` implementation for Jetty to function properly. -OSGi leverages http://aries.apache.org/modules/spi-fly.html[Apache Aries SPI Fly] for this functionality. -You can read more about OSGi and `ServiceLoader` http://blog.osgi.org/2013/02/javautilserviceloader-in-osgi.html[here.] -____ - -[[alpn-troubleshooting]] -==== ALPN Troubleshooting - -When starting the Jetty server, especially when using Jetty embedded, it may be possible that you see an error similar to this: - -[source, plain, subs="{sub-order}"] ----- -IllegalStateException: no ALPN processor ----- - -The error means that you don't have the ALPN dependencies setup correctly in your classpath. - -For example, you do not have the `jetty-alpn-java-server` artifact in the classpath. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/alpn/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/alpn/chapter.adoc deleted file mode 100644 index 45c5b86b2998..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/alpn/chapter.adoc +++ /dev/null @@ -1,28 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[alpn-chapter]] -== Application Layer Protocol Negotiation (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 ALPN (Application Layer Protocol Negotiation - -https://tools.ietf.org/html/rfc7301[RFC7301]) has been defined to accomplish this. - -ALPN has now replaced the older (and now fully deprecated) NPN in the general Web -as of 2016. - -For those browsers that support HTTP/2, they all now support ALPN. -Starting with Jetty 9.3.0, only ALPN is supported by Jetty. - -include::alpn.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/chapter.adoc deleted file mode 100644 index 8bc80aee5606..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/chapter.adoc +++ /dev/null @@ -1,22 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/quick-annotations-setup.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/quick-annotations-setup.adoc deleted file mode 100644 index cd85888c720c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/quick-annotations-setup.adoc +++ /dev/null @@ -1,40 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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. - -==== 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` class into the list of link:#webapp-configurations[Configuration classes] applied to the `org.eclipse.jetty.webapp.WebAppContext` class representing your webapp. - -Below is an example application that sets up the standard `test-spec.war` webapp from the distribution in embedded fashion. -It can also be found in the Jetty GitHub repository on the examples/embedded page as link:{GITBROWSEURL}/examples/embedded/src/main/java/org/eclipse/jetty/embedded[`ServerWithAnnotations.java`.] -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, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ServerWithAnnotations.java[] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/using-annotations-embedded.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/using-annotations-embedded.adoc deleted file mode 100644 index 6939b11fd66d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/annotations/using-annotations-embedded.adoc +++ /dev/null @@ -1,189 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[using-annotations-embedded]] -=== Using Annotations with Jetty Embedded - -==== Setting up the Classpath - -You will need to place the following Jetty jar files onto the classpath of your application. -You can obtain them from the https://jetty.org/download.html[Jetty distribution], or the https://repo1.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 link:{MVNCENTRAL}/org/eclipse/jetty/orbit/org.objectweb.asm/3.3.1.v201105211655/org.objectweb.asm-3.3.1.v201105211655.jar[this link.] - -==== Example - -Here's an example application that sets up a Jetty server, performs some setup to ensure that annotations are scanned, and then 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]. -The example also adds in the configuration classes that are responsible for JNDI (see line 19). - -The code is as follows: - -[source, java, subs="{sub-order}"] ----- -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 the configuration classes responsible for setting up JNDI and `java:comp/env` are added. - -On line 20 we add in the configuration class that ensures annotations are inspected. - -On lines 30, 33 and 37 JNDI resources that we will be able to reference with @Resource annotations are configured. - -With the setup above, a servlet that uses annotations and Jetty will honour the annotations when the webapp is deployed can be created: - -[source, java, subs="{sub-order}"] ----- -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(""); - out.println(""); - out.println("

Results

"); - out.println(myDS.toString()); - out.println("
"); - out.println(maxAmount.toString()); - out.println(""); - out.println(""); - out.flush(); - } - catch (Exception e) - { - throw new ServletException(e); - } - } -} ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/ant/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/ant/chapter.adoc deleted file mode 100644 index b497a9a15553..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/ant/chapter.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[ant-and-jetty]] -== Ant and Jetty - -This chapter explains how to use Jetty with Ant and the Jetty Ant tasks. - -include::jetty-ant.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/ant/jetty-ant.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/ant/jetty-ant.adoc deleted file mode 100644 index c82c31c1a6aa..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/ant/jetty-ant.adoc +++ /dev/null @@ -1,617 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-ant]] -=== Ant Jetty Plugin - -The Ant Jetty plugin is a part of Jetty 9 under the `jetty-ant` module. -This plugin makes it possible to start a Jetty web server directly from the Ant build script, and to embed the Jetty web server inside your build process. -Its purpose is to provide almost the same functionality as the Jetty plugin for Maven: dynamic application reloading, working directly on web application sources, and tightly integrating with the build system. - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty - jetty-ant - - ----- - -[[jetty-ant-preparation]] -==== Preparing Your Project - -To set up your project for Ant to run Jetty, you need a Jetty distribution and the jetty-ant Jar: - -1. https://jetty.org/download.html[Download] a Jetty distribution and unpack it in the local filesystem. -2. https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-ant/[Get] the jetty-ant Jar. -3. Make a directory in your project called `jetty-lib/`. -4. Copy all of the Jars in your Jetty distribution's `lib` directory, and all its subdirectories, into your new `jetty-lib` dir. -When copying the Jars, _don't_ preserve the Jetty distribution's lib dir hierarchy – all the jars should be directly inside your ` jetty-lib` dir. -5. Also copy the jetty-ant Jar you downloaded earlier into the `jetty-lib` dir. -6. Make a directory in your project called `jetty-temp`. - -Now you're ready to edit or create your Ant `build.xml` file. - -==== Preparing the `build.xml` file - -Begin with an empty `build.xml`: - -[source, xml, subs="{sub-order}"] ----- - - - ----- - -Add a `` that imports all available Jetty tasks: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - ----- - -Now you are ready to add a new target for running Jetty: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - ----- - -This is the minimal configuration you need. You can now start Jetty on the default port of 8080. - -==== Starting Jetty via Ant - -At the command line enter: - -[source, screen, subs="{sub-order}"] -.... -> ant jetty.run -.... - -==== Configuring the Jetty Container - -A number of configuration options can help you set up the Jetty environment so that your web application has all the resources it needs: - -ports and connectors::: - To configure the port that Jetty starts on you need to define a connector. - First you need to configure a `` for the Connector class and then define the connector in the Jetty tags: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - - ----- -+ -____ -[TIP] -You can set the port to 0, which starts the Jetty server connector on an arbitrary available port. -You can then access these values from system properties `jetty.ant.server.port` and `jetty.ant.server.host`. -____ - -login services::: - If your web application requires authentication and authorization services, you can configure these on the Jetty container. - Here's an example of how to set up an link:{JDURL}/org/eclipse/jetty/security/HashLoginService.html[org.eclipse.jetty.security.HashLoginService]: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - - ----- -request log::: - The `requestLog` option allows you to specify a request logger for the Jetty instance. - You can either use the link:{JDURL}/org/eclipse/jetty/server/NCSARequestLog.html[org.eclipse.jetty.server.NCSARequestLog] class, or supply the name of your custom class: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - ----- -temporary directory::: - You can configure a directory as a temporary file store for uses such as expanding files and compiling JSPs by supplying the `tempDirectory` option: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - ----- -other context handlers::: - You may need to configure some other context handlers to run at the same time as your web application. - You can specify these other context handlers using the `` element. - You need to supply a `` for it before you can use it: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - - ----- -system properties::: - As a convenience, you can configure system properties by using the `` element. - Be aware that, depending on the purpose of the system property, setting it from within the Ant execution may mean that it is evaluated too late, as the JVM evaluates some system properties on entry. -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - ----- -jetty XML file::: - If you have a lot of configuration to apply to the Jetty container, it can be more convenient to put it into a standard Jetty XML configuration file and have the Ant plugin apply it before starting Jetty: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - ----- -scanning for changes::: - The most useful mode in which to run the Ant plugin is for it to continue to execute Jetty and automatically restart your web application if any part of it changes (for example, your IDE - recompiles the classes of the web application). - The `scanIntervalSeconds` option controls how frequently the `` task scans your web application/WAR file for changes. - The default value of `0` disables scanning. Here's an example where Jetty checks for changes every five seconds: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - ----- -stopping::: - In normal mode (`daemon="false"`), the `` task runs until you `cntrl-c` it. It may be useful to script both the stop AND the start of Jetty. - For such a case, we provide the `` task. - + - To use it, you need to provide a port and an identifying string to both the ` ` and the `` tasks, where `` listens on the given port for a stop message containing the given string, and cleanly stops Jetty when it is received. - The `` task sends this stop message. - You can also optionally provide a `stopWait` value (in seconds), which is the length of time the `` task waits for confirmation that the stop succeeded: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - ----- -+ -To stop jetty via Ant, enter: -+ -[source, screen, subs="{sub-order}"] -.... -> ant jetty.stop -.... - - -execution without pausing ant::: - Usually, the `` task runs until you `cntrl-c` it, pausing the execution of Ant as it does so. In some cases, it may be useful to let Ant continue executing. - For example, to run your unit tests you may need other tasks to execute while Jetty is running. - For this case, we provide the `daemon` option. - This defaults to `false`. For `true`, Ant continues to execute after starting Jetty. - If Ant exits, so does Jetty. Understand that this option does _not_ fork a new process for Jetty. -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - ----- - -==== Deploying a Web Application - -Add a `` for the `org.eclipse.jetty.ant.AntWebAppContext` class with name __webApp__, then add a `` element to `` to describe your web application. -The following example deploys a web application that is expanded in the local directory `foo/` to context path ` / `: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - ----- - -deploying a WAR file::: - It is not necessary to expand the web application into a directory. - It is fine to deploy it as a WAR file: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - ----- - -deploying more than one web application::: - You can also deploy more than one web application: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - - ----- - -===== Configuring the Web Application - -As the `org.eclipse.jetty.ant.AntWebAppContext` class is an extension of -the -link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[`org.eclipse.jetty.webapp.WebAppContext`] -class, you can configure it by adding attributes of the same name -(without the `set` or `add` prefix) as the setter methods. - -Here's an example that specifies the location of the `web.xml` file (equivalent to method link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setDescriptor%28java.lang.String%29[`AntWebAppContext.setDescriptor()`]) and the web application's temporary directory (equivalent to method link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setTempDirectory%28java.io.File%29[`AntWebAppContext.setTempDirectory()`]): - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - ----- - -Other extra configuration options for the AntWebAppContext include: - -extra classes and Jars::: - If your web application's classes and Jars do not reside inside `WEB-INF` of the resource base directory, you can use the and elements to tell Ant where to find them. Here's an example: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - ----- -context attributes::: - Jetty allows you to set up ServletContext attributes on your web application. - You configure them in a context XML file that is applied to your WebAppContext instance prior to starting it. - For convenience, the Ant plugin permits you to configure these directly in the build file. - Here's an example: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - - - - ----- -`jetty-env.xml` file::: - If you are using features such as link:#configuring_jndi[JNDI] with your web application, you may need to configure a link:#using_jndi[`WEB-INF/jetty-env.xml`] file to define resources. If the structure of your web application project is such that the source of `jetty-env.xml` file resides somewhere other than `WEB-INF`, you can use the `jettyEnvXml` attribute to tell Ant where to find it: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - - ----- -context XML file::: - You may prefer or even require to do some advanced configuration of your web application outside of the Ant build file. - In this case, you can use a standard context XML configuration file which the Ant plugin applies to your web application before it is deployed. - Be aware that the settings from the context XML file _override_ those of the attributes and nested elements you defined in the build file. -+ -[source, xml, subs="{sub-order}"] ----- -project name="Jetty-Ant integration test" basedir="."> - - - - - - - - - - - - - - - - - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/architecture/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/architecture/chapter.adoc deleted file mode 100644 index 0c65bb6a02ec..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/architecture/chapter.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[architecture]] -== Architecture - -General items related to the architecture of jetty and how it deals with certain design decisions. - -include::jetty-classloading.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/architecture/jetty-classloading.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/architecture/jetty-classloading.adoc deleted file mode 100644 index 7cdf6d09b7e8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/architecture/jetty-classloading.adoc +++ /dev/null @@ -1,198 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-classloading]] -=== Jetty Classloading - -Class loading in a web container is slightly more complex than a normal Java application. -The normal configuration is that each web context (web application or WAR file) has its own classloader, which has the system classloader as its parent. -Such a classloader hierarchy is normal in Java, however the servlet specification complicates the hierarchy because it requires the following: - -* Classes contained within `WEB-INF/lib` or `WEB-INF/classes` have priority over classes on the parent classloader. -This is the opposite of the normal behavior of a Java 2 classloader. -* System classes such as `java.lang.String` are excluded from the webapp priority, and you may not replace them with classes in `WEB-INF/lib` or `WEB-INF/` classes. -Unfortunately the specification does not clearly state what classes are _System_ classes, and it is unclear if all `javax` classes should be treated as System classes. -* Server implementation classes like link:{JDURL}/org/eclipse/jetty/server/Server.html[Server] should be hidden from the web application and should not be available in any classloader. -Unfortunately the specification does not state what classes are _Server_ classes, and it is unclear if common libraries like the Xerces parser should be treated as Implementation classes. - -[[configuring-webapp-classloading]] -==== Configuring Webapp Classloading - -Jetty provides configuration options to control the three webapp class loading issues identified above. - -You can configure webapp classloading by several methods on the link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[WebAppContext]. -You can call these methods directly if you are working with the Jetty API, or you can inject methods from a context XML file if you are using the Context Provider (xref:using-context-provider[]). -You CANNOT set these methods from a `jetty-web.xml` file, as it executes after the classloader configuration is set. -As a note, `jetty-web.xml` uses the webapp classpath and not the classpath of the server. - -[[controlling-webapp-classloader-priority]] -===== Controlling Webapp Classloader Priority - -The method link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#isParentLoaderPriority()[org.eclipse.jett .webapp.WebAppContext.setParentLoaderPriority(boolean)] allows control over the priority given to webapp classes over system classes. -If you set it to false (the default), Jetty uses standard webapp classloading priority. -However, if in this mode some classes that are dependencies of other classes are loaded from the parent classloader (due to settings of system classes below), ambiguities might arise as both the webapp and system classloader versions can end up being loaded. - -If set to true, Jetty uses normal JavaSE classloading priority, and gives priority to the parent/system classloader. -This avoids the issues of multiple versions of a class within a webapp, but the version the parent/system loader provides must be the right version for all webapps you configure in this way. - -[[configuring-webapp-caching]] -===== Configuring Webapp Classloader Caching - -Introduced in Jetty 9.3.6, the link:{JDURL}/org/eclipse/jetty/webapp/CachingWebAppClassLoader.html[CachingWebAppClassLoader] can be used to cache `getResource(String)` results. -For webapps that search for classes and resources regularly, this can increase speed and performance. -This is an optional feature and it should be noted that it can conflict with several other libraries such as JSP, JSTL, JSF and CDI. -As such, this feature must be manually enabled for each webapp you want to use it in. - -Below is an example of implementing this feature using Jetty IoC XML format: - -[source, xml, options="header"] ----- - - -... - - - - - - - -... - ----- - -[[classloading-setting-system-classes]] -===== Setting System Classes - -You can call the methods -link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setSystemClasses%28java.lang.String%5B%5D%29[WebAppContext.setSystemClasses(String[\])] -or -link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#getSystemClasspathPattern()[WebAppContext.getSystemClasspathPattern().add(String)] -to allow fine control over which classes are considered system classes. - -* A web application can see a System class. -* A WEB-INF class cannot replace a System class. - -The default system classes are: - -.Default System Classes -[width="100%",cols="8%,92%",options="header",] -|======================================================================= -|System Classes | Note -|java. |Java SE classes (per servlet spec v2.5 / SRV.9.7.2). -|javax. |Java SE classes (per servlet spec v2.5 / SRV.9.7.2). -|org.xml. |Needed by javax.xml. -|org.w3c. |Needed by javax.xml. -|org.eclipse.jetty.continuation. |Webapp can see and not change continuation classes. -|org.eclipse.jetty.jndi. |Webapp can see and not change naming classes. -|org.eclipse.jetty.jaas. |Webapp can see and not change JAAS classes. -|org.eclipse.jetty.websocket. |WebSocket is a Jetty extension. -|org.eclipse.jetty.servlet.DefaultServlet |Webapp can see and not change default servlet. -|======================================================================= - -Absolute classname can be passed, names ending with `.` are treated as packages names, and names starting with `-` are treated as negative matches and must be listed before any enclosing packages. - -[[setting-server-classes]] -===== Setting Server Classes - -You can call the methods link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setServerClasses%28java.lang.String%5B%5D%29[org.eclipse.jetty.webapp.WebAppContext.setServerClasses(String Array)] or -link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#addServerClass(java.lang.String)[org.eclipse.jetty.webapp.WebAppContext.addServerClass(String)] to allow fine control over which classes are considered Server classes. - -* A web application cannot see a Server class. -* A WEB-INF class can replace a Server class. - -The default server classes are: - -.Default Server Classes -[width="100%",cols="8%,92%",options="header",] -|======================================================================= -|Server Classes -|-org.eclipse.jetty.continuation. |Don't hide continuation classes. -|-org.eclipse.jetty.jndi. |Don't hide naming classes. -|-org.eclipse.jetty.jaas. |Don't hide jaas classes. -|-org.eclipse.jetty.servlets. |Don't hide utility servlet classes if provided. -|-org.eclipse.jetty.servlet.DefaultServlet |Don't hide default servlet. -|-org.eclipse.jetty.servlet.listener. |Don't hide utility listeners -|-org.eclipse.jetty.websocket. |Don't hide websocket extension. -| org.eclipse.jetty. |Do hide all other Jetty classes. -|======================================================================= - -[[adding-extra-classpaths]] -==== Adding Extra Classpaths to Jetty - -You can add extra classpaths to Jetty in several ways. - -[[classpaths-using-start-jar]] -===== Using `start.jar` - -If you are using `start.jar` via the Jetty distribution, at startup the Jetty runtime automatically loads option Jars from the top level `$jetty.home/lib` directory. The default settings include: - -* Adding Jars under `$jetty.home/lib/ext` to the system classpath. -You can place additional Jars here. -* Adding the directory `$jetty.home/resources` to the classpath (may contain classes or other resources). -* Adding a single path defined by the command line parameter __path__. - -[[using-extra-classpath-method]] -===== Using the extraClasspath() method - -You can add an additional classpath to a context classloader by calling link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setExtraClasspath(java.lang.String)[org.eclipse.jetty.webapp.WebAppContext.setExtraClasspath(String)] with a comma-separated list of paths. -You can do so directly to the API via a context XML file such as the following: - -[source, xml, subs="{sub-order}"] ----- - - ... - ../my/classes,../my/jars/special.jar,../my/jars/other.jar - ... ----- - -[[using-custom-webappclassloader]] -==== Using a Custom WebAppClassLoader - -If none of the alternatives already described meet your needs, you can always provide a custom classloader for your webapp. -We recommend, but do not require, that your custom loader subclasses link:{JDURL}/org/eclipse/jetty/webapp/WebAppClassLoader.html[WebAppClassLoader]. - -If you do not subclass WebAppClassLoader, we recommend that you implement the link:{JDURL}/org/eclipse/jetty/util/ClassVisibilityChecker.html[ClassVisibilityChecker] interface. -Without this interface, session persistence will be slower. - -You configure the classloader for the webapp like so: - -[source, java, subs="{sub-order}"] ----- -MyCleverClassLoader myCleverClassLoader = new MyCleverClassLoader(); - ... - WebAppContext webapp = new WebAppContext(); - ... - webapp.setClassLoader(myCleverClassLoader); - ----- - -You can also accomplish this in a context xml file. - -[[starting-jetty-custom-classloader]] -==== Starting Jetty with a Custom ClassLoader - -If you start a Jetty server using a custom class loader–consider the Jetty classes not being available to the system class loader, only your custom class loader–you may run into class loading issues when the `WebAppClassLoader` kicks in. -By default the `WebAppClassLoader` uses the system class loader as its parent, hence the problem. This is easy to fix, like so: - -[source, java, subs="{sub-order}"] ----- -context.setClassLoader(new WebAppClassLoader(this.getClass().getClassLoader(), context)); ----- - -or - -[source, java, subs="{sub-order}"] ----- -context.setClassLoader(new WebAppClassLoader(new MyCustomClassLoader(), context)); ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/connectors/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/connectors/chapter.adoc deleted file mode 100644 index 09aae5827d5e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/connectors/chapter.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-connectors]] -== Configuring Jetty Connectors - -This chapter discusses various options for configuring Jetty connectors. - -include::configuring-connectors.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/connectors/configuring-connectors.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/connectors/configuring-connectors.adoc deleted file mode 100644 index e154227d2c79..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/connectors/configuring-connectors.adoc +++ /dev/null @@ -1,540 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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. - -Typically connectors require very little configuration aside from setting the listening port, and enabling `X-Forwarded-For` customization when applicable. -Additional settings, including construction your own constructor Jetty XML files, are for expert configuration only. - -==== Enabling Connectors - -Out of the box, Jetty provides several link:#startup-modules[modules] for enabling different types of connectors, from HTTP to HTTPS, HTTP/2, and others. -If you startup Jetty with the `--list-modules=connector` command, you can see a list of all available connector modules: - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --list-modules=connector - -Available Modules: -================== -tags: [connector] - -Modules for tag 'connector': ----------------------------- - - Module: acceptratelimit - : Enable a server wide accept rate limit - Tags: connector - Depend: server - XML: etc/jetty-acceptratelimit.xml - - Module: connectionlimit - : Enable a server wide connection limit - Tags: connector - Depend: server - XML: etc/jetty-connectionlimit.xml - - Module: http - : Enables a HTTP connector on the server. - : By default HTTP/1 is support, but HTTP2C can - : be added to the connector with the http2c module. - Tags: connector, http - Depend: server - XML: etc/jetty-http.xml - - Module: http-forwarded - : Adds a forwarded request customizer to the HTTP Connector - : to process forwarded-for style headers from a proxy. - Tags: connector - Depend: http - XML: etc/jetty-http-forwarded.xml - - Module: http2 - : Enables HTTP2 protocol support on the TLS(SSL) Connector, - : using the ALPN extension to select which protocol to use. - Tags: connector, http2, http, ssl - Depend: ssl, alpn - LIB: lib/http2/*.jar - XML: etc/jetty-http2.xml - - Module: http2c - : Enables the HTTP2C protocol on the HTTP Connector - : The connector will accept both HTTP/1 and HTTP/2 connections. - Tags: connector, http2, http - Depend: http - LIB: lib/http2/*.jar - XML: etc/jetty-http2c.xml - - Module: https - : Adds HTTPS protocol support to the TLS(SSL) Connector - Tags: connector, https, http, ssl - Depend: ssl - Optional: http-forwarded, http2 - XML: etc/jetty-https.xml - - Module: proxy-protocol-ssl - : Enables the Proxy Protocol on the TLS(SSL) Connector. - : http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt - : This allows a Proxy operating in TCP mode to transport - : details of the proxied connection to the server. - : Both V1 and V2 versions of the protocol are supported. - Tags: connector, ssl - Depend: ssl - XML: etc/jetty-proxy-protocol-ssl.xml - - Module: ssl - : Enables a TLS(SSL) Connector on the server. - : This may be used for HTTPS and/or HTTP2 by enabling - : the associated support modules. - Tags: connector, ssl - Depend: server - XML: etc/jetty-ssl.xml - XML: etc/jetty-ssl-context.xml - - Module: unixsocket - : Enables a Unix Domain Socket Connector that can receive - : requests from a local proxy and/or SSL offloader (eg haproxy) in either - : HTTP or TCP mode. Unix Domain Sockets are more efficient than - : localhost TCP/IP connections as they reduce data copies, avoid - : needless fragmentation and have better dispatch behaviours. - : When enabled with corresponding support modules, the connector can - : accept HTTP, HTTPS or HTTP2C traffic. - Tags: connector - Depend: server - LIB: lib/jetty-unixsocket-${jetty.version}.jar - LIB: lib/jnr/*.jar - XML: etc/jetty-unixsocket.xml - - Module: unixsocket-forwarded - : Adds a forwarded request customizer to the HTTP configuration used - : by the Unix Domain Socket connector, for use when behind a proxy operating - : in HTTP mode that adds forwarded-for style HTTP headers. Typically this - : is an alternate to the Proxy Protocol used mostly for TCP mode. - Tags: connector - Depend: unixsocket-http - XML: etc/jetty-unixsocket-forwarded.xml - - Module: unixsocket-http - : Adds a HTTP protocol support to the Unix Domain Socket connector. - : It should be used when a proxy is forwarding either HTTP or decrypted - : HTTPS traffic to the connector and may be used with the - : unix-socket-http2c modules to upgrade to HTTP/2. - Tags: connector, http - Depend: unixsocket - XML: etc/jetty-unixsocket-http.xml - - Module: unixsocket-http2c - : Adds a HTTP2C connetion factory to the Unix Domain Socket Connector - : It can be used when either the proxy forwards direct - : HTTP/2C (unecrypted) or decrypted HTTP/2 traffic. - Tags: connector, http2 - Depend: unixsocket-http - LIB: lib/http2/*.jar - XML: etc/jetty-unixsocket-http2c.xml - - Module: unixsocket-proxy-protocol - : Enables the proxy protocol on the Unix Domain Socket Connector - : http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt - : This allows information about the proxied connection to be - : efficiently forwarded as the connection is accepted. - : Both V1 and V2 versions of the protocol are supported and any - : SSL properties may be interpreted by the unixsocket-secure - : module to indicate secure HTTPS traffic. Typically this - : is an alternate to the forwarded module. - Tags: connector - Depend: unixsocket - XML: etc/jetty-unixsocket-proxy-protocol.xml - - Module: unixsocket-secure - : Enable a secure request customizer on the HTTP Configuration - : used by the Unix Domain Socket Connector. - : This looks for a secure scheme transported either by the - : unixsocket-forwarded, unixsocket-proxy-protocol or in a - : HTTP2 request. - Tags: connector - Depend: unixsocket-http - XML: etc/jetty-unixsocket-secure.xml -... -.... - -To enable a connector, simply activate the associated module. -Below is an example of activating both the `http` and `https` modules in a fresh link:#startup-base-and-home[Jetty base] using the link:#start-vs-startd[start.d directory]: - -[source, screen, subs="{sub-order}"] -.... -[mybase] java -jar $JETTY_HOME/start.jar --create-startd -MKDIR : ${jetty.base}/start.d -INFO : Base directory was modified - -[mybase] java -jar $JETTY_HOME/start.jar --add-to-start=http,https -INFO : server transitively enabled, ini template available with --add-to-start=server -INFO : http initialized in ${jetty.base}/start.d/http.ini -INFO : https initialized in ${jetty.base}/start.d/https.ini -INFO : ssl transitively enabled, ini template available with --add-to-start=ssl -MKDIR : ${jetty.base}/etc -COPY : ${jetty.home}/modules/ssl/keystore to ${jetty.base}/etc/keystore -INFO : Base directory was modified -[mybase] tree -. -├── etc -│   └── keystore -└── start.d - ├── http.ini - └── https.ini -.... - -When the `http` and `https` modules were activated, so too were any modules they were dependent on, in this case `server` and `ssl`, as well as any dependencies for those modules, such as the `etc` and `ketystore` directories for `ssl`. - -At this point the server has been configured with connectors for both HTTP and HTTPS and can be started: - -[source, screen, subs="{sub-order}"] -.... -[mybase] java -jar $JETTY_HOME/start.jar -2017-08-31 10:19:58.855:INFO::main: Logging initialized @372ms to org.eclipse.jetty.util.log.StdErrLog -2017-08-31 10:19:59.076:INFO:oejs.Server:main: jetty-{VERSION} -2017-08-31 10:19:59.125:INFO:oejs.AbstractConnector:main: Started ServerConnector@421e98e0{HTTP/1.1,[http/1.1]}{0.0.0.0:8080} -2017-08-31 10:19:59.150:INFO:oejus.SslContextFactory:main: x509=X509@5315b42e(jetty,h=[jetty.eclipse.org],w=[]) for SslContextFactory@2ef9b8bc(file:///var/my-jetty-base/etc/keystore,file:///var/my-jetty-base/etc/keystore) -2017-08-31 10:19:59.151:INFO:oejus.SslContextFactory:main: x509=X509@5d624da6(mykey,h=[],w=[]) for SslContextFactory@2ef9b8bc(file:///var/my-jetty-base/etc/keystore,file:///var/my-jetty-base/etc/keystore) -2017-08-31 10:19:59.273:INFO:oejs.AbstractConnector:main: Started ServerConnector@2b98378d{SSL,[ssl, http/1.1]}{0.0.0.0:8443} -2017-08-31 10:19:59.274:INFO:oejs.Server:main: Started @791ms -.... - -When modules are enabled, they are loaded with several default options. -These can be changed by editing the associated module ini file in the `start.d` directory (or the associated lines in `server.ini` if your implementation does not use `start.d`). -For example, if we examine the `http.ini` file in our `start.d` directory created above, we will see the following settings: - -[source, screen, subs="{sub-order}"] -.... -# --------------------------------------- -# Module: http -# Enables a HTTP connector on the server. -# By default HTTP/1 is support, but HTTP2C can -# be added to the connector with the http2c module. -# --------------------------------------- ---module=http - -### HTTP Connector Configuration - -## Connector host/address to bind to -# jetty.http.host=0.0.0.0 - -## Connector port to listen on -# jetty.http.port=8080 - -## Connector idle timeout in milliseconds -# jetty.http.idleTimeout=30000 - -## Number of acceptors (-1 picks default based on number of cores) -# jetty.http.acceptors=-1 - -## Number of selectors (-1 picks default based on number of cores) -# jetty.http.selectors=-1 - -## ServerSocketChannel backlog (0 picks platform default) -# jetty.http.acceptQueueSize=0 - -## Thread priority delta to give to acceptor threads -# jetty.http.acceptorPriorityDelta=0 - -## HTTP Compliance: RFC7230, RFC2616, LEGACY -# jetty.http.compliance=RFC7230 -.... - -To make a change to these settings, uncomment the line (by removing the #) and change the property to the desired value. -For example, if you wanted to change the HTTP port to 5231, you would edit the line as follows: - -[source, screen, subs="{sub-order}"] -.... -... -## Connector port to listen on -jetty.http.port=5231 -... -.... - -Now when the server is started, HTTP connections will enter on port 5231: - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar -2017-08-31 10:31:32.955:INFO::main: Logging initialized @366ms to org.eclipse.jetty.util.log.StdErrLog -2017-08-31 10:31:33.109:INFO:oejs.Server:main: jetty-{VERSION} -2017-08-31 10:31:33.146:INFO:oejs.AbstractConnector:main: Started ServerConnector@2ef9b8bc{HTTP/1.1,[http/1.1]}{0.0.0.0:5231} -... -2017-08-31 10:31:33.263:INFO:oejs.Server:main: Started @675ms -.... - -Every module has their own set of configuration options, and reviewing them all is recommended. -For additional information on the module system, please refer to our documentation on link:#startup-modules[Startup Modules]. - -____ -[NOTE] -Editing these module files is the recommended way to edit the configuration of your server. -Making changes to the associated Jetty XML file for connectors is *not* recommended, and is for advanced users only. -If you do wish to edit Jetty XML, please see our section on managing link:#[Jetty Home and Jetty Base] to ensure your Jetty Home remains a standard of truth for your implementation. -____ - -==== Limiting Connections - -Jetty also provides the means by which to limit connections to the server and/or contexts. -This is provided by two different modules in the distribution. - -`connectionlimit`:: -Applies a limit to the number of connections. -If this limit is exceeded, new connections are suspended for the time specified (in milliseconds). -`acceptratelimit`:: -Limits the rate at which new connections are accepted. -If this limit is exceeded, new connections are suspended for the time specified (in milliseconds). - -As with the modules listed above, these can be enabled by adding `--add-to-start=` to the command line. - -==== Advanced Configuration - -Jetty primarily uses a single connector type called link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[ServerConnector]. - -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 a single 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:{GITBROWSEURL}/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:{GITBROWSEURL}/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:{GITBROWSEURL}/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:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-http-forwarded.xml[`jetty-http-forwarded.xml`]:: - Adds a link:{JDURL}/org/eclipse/jetty/server/ForwardedRequestCustomizer.html[`ForwardedRequestCustomizer`]to the HTTP Connector to process forwarded-for style headers from a proxy. -link:{GITBROWSEURL}/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. -link:{GITBROWSEURL}/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. - -==== 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. -Many 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:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-http.xml[`jetty-http.xml`]) you can do this by: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - ----- - -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 can 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, subs="{sub-order}"] ----- - - - - - 8080 - ----- - -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, subs="{sub-order}"] ----- - - - - - - ----- - -The network settings available for configuration 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. -|======================================================================= - -[[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:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty.xml[`jetty.xml`], which is a `Ref` element then used in link:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-http.xml[`jetty-http.xml`], link:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-https.xml[`jetty-https.xml`] and in link:{GITBROWSEURL}/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, subs="{sub-order}"] ----- - - https - - 32768 - 8192 - 8192 - ----- - -This example HttpConfiguration may be used by reference to the ID "`httpConfig`": - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - ----- - -This same `httpConfig` is referenced by the link:{JDURL}/org/eclipse/jetty/server/handler/SecuredRedirectHandler.html[`SecuredRedirectHandler`] when redirecting secure requests. -Please note that if your `httpConfig` does not include a `secureScheme` or `securePort` or there is no `HttpConfiguration` present these types of secured requests will be returned a `403` error. - -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, subs="{sub-order}"] ----- - - - - - - ----- - -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.Server.html[`SslContextFactory.Server`] 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:{GITBROWSEURL}/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 original 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 de facto 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, subs="{sub-order}"] ----- - - 32768 - 8192 - 8192 - - - - - ----- - -===== Proxy Protocol - -The http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt[Proxy Protocol] is the _de facto_ 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 an end point that has been customized with the data obtained about the original 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 shown below: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - - - - - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/chapter.adoc deleted file mode 100644 index 230e6b838872..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/chapter.adoc +++ /dev/null @@ -1,22 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-contexts]] -== Configuring Contexts - -This chapter discusses various options for configuring Jetty contexts. - -include::setting-context-path.adoc[] -include::temporary-directories.adoc[] -include::custom-error-pages.adoc[] -include::setting-form-size.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/custom-error-pages.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/custom-error-pages.adoc deleted file mode 100644 index cdb9d405752d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/custom-error-pages.adoc +++ /dev/null @@ -1,168 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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, subs="{sub-order}"] ----- - - 404 - /jspsnoop/ERROR/404 - - ----- - -Exception example: - -[source, xml, subs="{sub-order}"] ----- - - java.io.IOException - /jspsnoop/IOException - - ----- - -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 request with an error. -javax.servlet.error.servlet_name:: - The Servlet name of the servlet that the 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.base}/webapps/` (see `DeployerManager` for more details) and an example of more flexible error page mapping is below: - -[source, xml, subs="{sub-order}"] ----- - - - - - /test - - /webapps/test - - - - - - 404 - /jspsnoop/ERROR/404 - - - - - - - - - java.io.IOException - - - /jspsnoop/IOException - - - - - - - 500 - 599 - /dump/errorCodeRangeMapping - - - - ----- - -==== 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, subs="{sub-order}"] ----- -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, subs="{sub-order}"] ----- - - ... - - - - ... - ----- - -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: - -[source, xml, subs="{sub-order}"] ----- - - ... - - - - - - ... - ----- - -==== Server level 404 error - -It is possible to 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, and use the `index.html` redirect to whatever place with a header directive. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/setting-context-path.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/setting-context-path.adoc deleted file mode 100644 index 2271dc7835ad..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/setting-context-path.adoc +++ /dev/null @@ -1,55 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[setting-context-path]] -=== Setting a Context Path - -The context path is the prefix of a URL path that is used to select the context(s) to which an incoming request is passed. Typically a URL in a Java servlet server is of the format `http://hostname.com/contextPath/servletPath/pathInfo`, where each of the path elements can be zero or more / separated elements. -If there is no context path, the context is referred to as the _root_ context. -The root context must be configured as `/` but is reported as the empty string by the servlet API `getContextPath()` method. - -How you set the context path depends on how you deploy the web application (or `ContextHandler`). - -[[using-embedded-deployment]] -==== Using Embedded Deployment - -If you run Jetty from code as an embedded server (see link:#advanced-embedding[Embedding]), setting the context path is a matter of calling the `setContextPath` method on the `ContextHandler` instance (or `WebAppContext` instance). - -[[usng-the-context-provider]] -==== By naming convention - -If a web application is deployed using the WebAppProvider of the DeploymentManager without an XML IoC file, then the name of the WAR file is used to set the context path: - -* If the WAR file is named myapp.war, then the context will be deployed with a context path of `/myapp` -* If the WAR file is named ROOT.WAR (or any case insensitive variation), then the context will be deployed with a context path of `/` -* If the WAR file is named ROOT-foobar.war ( or any case insensitive variation), then the context will be deployed with a context path of `/` and a virtual host of "foobar" - -[[using-the-webapp-provider]] -==== By Deployer configuration - -If a web application is deployed using the `WebAppProvider` of the `DeploymentManager` with an XML IoC file to configure the context, then the `setContextPath` method can be called within that file. -For example: - -[source, xml, subs="{sub-order}"] ----- - - /test - ... - ----- - -[[embedding-web-inf-jetty-web.xml-file]] -==== Embedding a WEB-INF/jetty-web.xml File - -You can also set the context path for webapps by embedding a `WEB-INF/jetty-web.xml` file in the WAR, which uses the same XML IoC format as the deployer example above. -However this is not the preferred method as it requires the web application to be modified. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/setting-form-size.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/setting-form-size.adoc deleted file mode 100644 index c220e7dcf22d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/setting-form-size.adoc +++ /dev/null @@ -1,77 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[setting-form-size]] -=== Setting Max Form Size - -When a client issues a POST request with `Content-Type: application/x-www-form-urlencoded` there are 2 configurable limits imposed to help protect the server against denial of service attacks by malicious clients sending huge amounts of data. - -There is a maximum form size limit, and a maximum form keys limit. - -The default maximum form size Jetty permits is 200000 bytes. -The default maximum form keys Jetty permits is 1000 keys. - -You can change these defaults for a particular webapp, or all webapps within the same JVM. - -==== For a Single Webapp - -The methods to invoke are: - -* `ContextHandler.setMaxFormContentSize(int maxSize);` -* `ContextHandler.setMaxFormKeys(int max);` - -This can be done either in a context XML deployment descriptor external to the webapp, or in a `jetty-web.xml` file in the webapp's `WEB-INF` directory. - -In either case the syntax of the XML file is the same: - -[source,xml,subs="{sub-order}"] ----- - - - - - 400000 - - - - 400 - ----- - -==== For All Apps in the JVM - -Use the system properties: - -* `org.eclipse.jetty.server.Request.maxFormContentSize` - the maximum size of Form Content allowed -* `org.eclipse.jetty.server.Request.maxFormKeys` - the maximum number of Form Keys allowed - -This can be set on the command line or in the `$JETTY_BASE\start.ini` or any `$JETTY_BASE\start.d\*.ini` link:#startup-modules[module ini file.] -Using `$JETTY_BASE\start.d\server.ini` as an example: - -[source,console,subs="{sub-order}"] ----- -# --------------------------------------- -# Module: server -# Enables the core Jetty server on the classpath. -# --------------------------------------- ---module=server - -### Common HTTP configuration -## Scheme to use to build URIs for secure redirects -# jetty.httpConfig.secureScheme=https - -... - --Dorg.eclipse.jetty.server.Request.maxFormContentSize=400000 --Dorg.eclipse.jetty.server.Request.maxFormKeys=400 ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/temporary-directories.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/temporary-directories.adoc deleted file mode 100644 index 4fae1fd07da7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contexts/temporary-directories.adoc +++ /dev/null @@ -1,205 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[ref-temporary-directories]] -=== Temporary Directories - -Jetty itself has no temporary directories, but you can assign a directory for each web application, into which the WAR is unpacked, JSPs compiled on-the-fly, etc. -If you do not assign a specific temporary directory, Jetty will create one as needed when your web application starts. -Whether you set the location of the temporary directory - or you let Jetty create one for you - you also have a choice to either keep or delete the temporary directory when the web application stops. - -==== The Default Temp Directory - -By default, Jetty will create a temporary directory for each web application. The name of the directory will be of the form: - -.... -"jetty-"+host+"-"+port+"-"+resourceBase+"-_"+context+"-"+virtualhost+"-"+randomdigits+".dir" -.... - -For example: - -.... -jetty-0.0.0.0-8080-test.war-_test-any-8900275691885214790.dir -.... - -Where `0.0.0.0` is the host address, `8080` is the port, `test.war` is the resourceBase, `test` is the context path (with / converted to _), `any` is the virtual host, and `randomdigits` are a string of digits guaranteed to be unique. - -Once the temp directory is created, it is retrievable as the value (as a File) of the context attribute `javax.servlet.context.tempdir.` - -===== The location of the temp directory - -By default, Jetty will create this directory inside the directory named by the `java.io.tmpdir` System property. -You can instruct Jetty to use a different parent directory by setting the context attribute `org.eclipse.jetty.webapp.basetempdir` to the name of the desired parent directory. -The directory named by this attribute _must_ exist and be __writeable__. - -As usual with Jetty, you can either set this attribute in a context xml file, or you can do it in code. - -Here's an example of setting it in an xml file: - -[source, xml, subs="{sub-order}"] ----- - - - /test - foo.war - - - org.eclipse.jetty.webapp.basetempdir - /home/my/foo - - ----- - -The equivalent in code is: - -[source, java, subs="{sub-order}"] ----- -WebAppContext context = new WebAppContext(); -context.setContextPath("/test"); -context.setWar("foo.war"); -context.setAttribute("org.eclipse.jetty.webapp.basetempdir", "/tmp/foo"); ----- - -==== Setting a Specific Temp Directory - -There are several ways to use a particular directory as the temporary directory: - -===== Call WebAppContext.setTempDirectory(String dir) -As before this can be accomplished with an XML file or directly in code. -Here is an example of setting the temp directory in XML: - -[source, xml, subs="{sub-order}"] ----- - - - /test - foo.war - - /some/dir/foo - ----- - -And here is an example of doing it with java code: - -[source, java, subs="{sub-order}"] ----- -WebAppContext context = new WebAppContext(); -context.setContextPath("/test"); -context.setWar("foo.war"); -context.setTempDirectory(new File("/some/dir/foo")); ----- - -===== Setting the javax.servlet.context.tempdir Context Attribute -You should set this context attribute with the name of directory you want to use as the temp directory. -Again, you can do this in XML: - -[source, xml, subs="{sub-order}"] ----- - - - /test - foo.war - - - javax.servlet.context.tempdir - /some/dir/foo - - - ----- - -Or in java: - -[source, java, subs="{sub-order}"] ----- -WebAppContext context = new WebAppContext(); -context.setContextPath("/test"); -context.setWar("foo.war"); -context.setAttribute("javax.servlet.context.tempdir", "/some/dir/foo"); ----- - -Once a temporary directory has been created by either of these methods, a file instance for it is set as the value of the `javax.servlet.context.tempdir` attribute of the web application. - -____ -[NOTE] -Be wary of setting an explicit temp directory if you are likely to change the jars in WEB-INF/lib between redeployments. -There is a JVM bug concerning link:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4774421[caching of jar contents.] -____ - -===== Setting the Temp Directory on the Command Line -You can set the location of the temp directory on the command line when Jetty starts up in two ways. -First is the most straightforward, simply add it to your command line when starting Jetty. - -[source, screen, subs="{sub-order}"] ----- -[my-base]$ java -jar /path/to/jetty-home/start.jar -Djava.io.tmpdir=/path/to/desired/directory ----- - -Alternately, this can be defined in a link:#startup-modules[module.] -The `jvm` module packaged with Jetty is set up to add additional JVM options. -After enabling the module (using the `--add-to-start=jvm` command), edit the `jvm.ini` file and add the location to the temporary directory. -You will also need verify the line including the `--exec` command is not commented out, as this is required for Jetty to start a new, forked JVM. -Below is an example of the standard `jvm.ini` file altered to include a reference to a temp directory. - -[source, screen, subs="{sub-order}"] -.... -# --------------------------------------- -# Module: jvm -# A noop module that creates an ini template useful for -# setting JVM arguments (eg -Xmx ) -# --------------------------------------- ---module=jvm - -## JVM Configuration -## If JVM args are include in an ini file then --exec is needed -## to start a new JVM from start.jar with the extra args. -## -## If you wish to avoid an extra JVM running, place JVM args -## on the normal command line and do not use --exec ---exec -# -Xmx2000m -# -Xmn512m -# -XX:+UseConcMarkSweepGC -# -XX:ParallelCMSThreads=2 -# -XX:+CMSClassUnloadingEnabled -# -XX:+UseCMSCompactAtFullCollection -# -XX:CMSInitiatingOccupancyFraction=80 -# -internal:gc -# -XX:+PrintGCDateStamps -# -XX:+PrintGCTimeStamps -# -XX:+PrintGCDetails -# -XX:+PrintTenuringDistribution -# -XX:+PrintCommandLineFlags -# -XX:+DisableExplicitGC --Djava.io.tmpdir=/path/to/desired/directory -.... - -==== The "work" Directory - -It is possible to create a directory named `work` in the `$\{jetty.base}` directory. -If such a directory is found, it is assumed you want to use it as the parent directory for all of the temporary directories of the webapps in `$\{jetty.base}`. -Moreover, as has historically been the case, these temp directories inside the work directory are not cleaned up when Jetty exits (or more correctly speaking, the `temp` directory corresponding to a context is not cleaned up when that context stops). - -When a `work` directory is used, the algorithm for generating the name of the context-specific temp directories omits the random digit string. -This ensures the name of the directory remains consistent across context restarts. - -==== Persisting the temp directory - -Sometimes it is useful to keep the contents of the temporary directory between restarts of the web application. -By default, Jetty will *not* persist the temp directory. -To configure Jetty to keep it, use link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[WebAppContext.setPersistTempDirectory(true)]. - -____ -[NOTE] -Be aware that if you call `setPersistTempDirectory(true)`, but let Jetty create a new temp directory each time (i.e. you do NOT set an explicit temp directory), then you will accumulate temp directories in your chosen temp directory location. -____ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/bugs.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/bugs.adoc deleted file mode 100644 index 0328bde4437d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/bugs.adoc +++ /dev/null @@ -1,21 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[bugs]] -=== Issues, Features, and Bugs - -As with any constantly evolving software project, there will be issues, features, and bugs. -We want to know whats bugging you! - -File bugs as Issues in our Github repository http://github.com/jetty/jetty.project[Issues at Github] - diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/chapter.adoc deleted file mode 100644 index 534338c0e1bc..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/chapter.adoc +++ /dev/null @@ -1,28 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[advanced-contributing]] -== Contributing to Jetty - -There are many ways to contribute to Jetty, from hardened developers looking to sharpen their skills to neophytes interested in working with an open source project for the first time. -Here we show ways to interact with the Jetty community, give feedback to the developers and contribute patches to both core Jetty code and even this document. - -include::community.adoc[] -include::documentation.adoc[] -include::source-build.adoc[] -include::coding-standards.adoc[] -include::bugs.adoc[] -include::patches.adoc[] -include::security.adoc[] -include::releasing-jetty.adoc[] -include::release-testing.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/coding-standards.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/coding-standards.adoc deleted file mode 100644 index df69e8c04942..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/coding-standards.adoc +++ /dev/null @@ -1,84 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[coding-standards]] -=== Coding Standards - -Jetty uses number of conventions for its source code. - -==== Code Formatting - -Jetty uses the code formatting the following project specifies. - -http://git.eclipse.org/c/jetty/org.eclipse.jetty.admin.git/tree/jetty-eclipse-java-format.xml[Eclipse Java Formatting] - -==== Code Templates - -Jetty specifies the following code templates for use by the project developers. - -http://git.eclipse.org/c/jetty/org.eclipse.jetty.admin.git/tree/jetty-eclipse-codetemplates.xml[Eclipse Code Templates] - -==== Code Conventions - -The following is an example of the Java formatting and naming styles to apply to Jetty: - -[source, java, subs="{sub-order}"] ----- - -import some.exact.ClassName; // GOOD -import some.wildcard.package.*; // BAD! - -package org.always.have.a.package; - -/* --------------------------------------------------------- */ -/** Always have some javadoc - */ -class MyClassName -{ - // indent by 4 spaces. - // use spaced to indent - // The code must format OK with default tabsize of 8. - - private static final int ALL_CAPS_FOR_PUBLIC_CONSTANTS=1; - - // Field prefixed with __ for static of _ for normal fields. - // This convention is no longer mandatory, but any given - // class should either consistently use this style or not. - private static String __staticField; - private Object _privateField; - - - // use getters and setters rather than public fields. - public void setPrivateField(Object privateField) - { - _privateField=privateField; - } - - public Object getPrivateField() - { - return _privateField; - } - - public void doSomething() - throws SomeException - { - Object local_variable = _privateField; - if (local_variable==null) - { - // do Something - } - } -} - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/community.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/community.adoc deleted file mode 100644 index e5a504e6ef6e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/community.adoc +++ /dev/null @@ -1,38 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[community]] -=== Community - -Developers and users alike are welcome to engage the Jetty community. -We all have day jobs here so don't just ask questions and get frustrated if no one answers right away. -Stick around to hear an answer, one is likely coming at some point! - -[[community-mailing-lists]] -==== Mailing Lists - -We have a number of options for people that wish to subscribe to our mailing lists. - -* Jetty Developers List -** Join - https://dev.eclipse.org/mailman/listinfo/jetty-dev -** Archives - https://dev.eclipse.org/mhonarc/lists/jetty-dev/ -* Jetty Users List -** Join - https://dev.eclipse.org/mailman/listinfo/jetty-users -** Archives - https://dev.eclipse.org/mhonarc/lists/jetty-users/ -* Jetty Announcements List -** Join - https://dev.eclipse.org/mailman/listinfo/jetty-announce -** Archives - https://dev.eclipse.org/mhonarc/lists/jetty-announce/ -* Jetty Commit List -** Join - https://dev.eclipse.org/mailman/listinfo/jetty-commit -** Archives - https://dev.eclipse.org/mhonarc/lists/jetty-commit/ - diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/documentation.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/documentation.adoc deleted file mode 100644 index d27142bbe651..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/documentation.adoc +++ /dev/null @@ -1,234 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[contributing-documentation]] -=== Documentation - -This document is produced using a combination of maven, git, and asciidoc. -We welcome anyone and everyone to contribute to the content of this book. -Below is the information on how to obtain the source of this book and to build it as well as information on how to contribute back to it. - -Note: All contributions to this documentation are under the EPLv1 and the copyright is assigned to Mort Bay. - -==== Tools - -You will need: - -git:: - This documentation is part of the Jetty project so all contributions must be through the normal Jetty contribution process. -+ -You can go one of two ways for using git, if you are familiar with SCM's and the command line interface feel free to install and use git from there. -Otherwise we would recommend you use the github client itself as it will help with some of the workflow involved with working with git. -All contributions much be signed and can be pulled into Jetty through the normal pull request process. - -maven 3:: - We build the documentation with maven 3 which can be found at http://maven.apache.org[Apache Maven]. - -==== Render Chain - -The Jetty documentation is all written in asciidoc which is used as the origin format. -The maven build uses the asciidoctor-maven-plugin to process all of the .adoc files into a single docbook file which is then used to produce the final output. -We use this intermediary step in order to primarily produce chunked html which we then deploy to the Eclipse Jetty website. -However we can also use this docbook output to produce pdf files, epub books or even Eclipse Help files should we so desire. - -==== Getting Started (cli) - -First you need to obtain the source of the documentation project. - -Clone the repository: - -[source, screen, subs="{sub-order}"] -.... -$ git clone https://github.com/jetty/jetty.project.git -.... - -You will now have a local directory with all of jetty, including the jetty-documentation. -Now we move on to building it. - -[source, screen, subs="{sub-order}"] -.... -$ cd jetty.project/jetty-documentation -$ mvn install -.... - -While maven is running you may see a lot of files being downloaded. -If you are not familiar with maven, then what you are seeing is maven setting up the execution environment for generating the documentation. -This build will first produce docbook xml and then through the docbkx-maven-plugin generate the chunked html output. -The downloads are all of the java dependencies that are required to make this build work. -After a while the downloading will stop and you should see the execution of the asciidoctor-maven-plugin followed by the docbkx-maven-plugin. - -[source, screen, subs="{sub-order}"] -.... -[INFO] --- asciidoctor-maven-plugin:1.5.3:process-asciidoc (output-html) @ jetty-documentation --- -[INFO] Rendered /Users/jesse/src/projects/jetty/jetty-docs/src/main/asciidoc/index.adoc -[INFO] - -[INFO] Processing input file: index.xml -[INFO] Applying customization parameters -[INFO] Chunking output. -[INFO] See /Users/jesse/src/projects/jetty/jetty-docs/target/docbkx/html/index for generated file(s) -.... - -The build is finished once you see a message akin to this: - -[source, screen, subs="{sub-order}"] -.... -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 7.014s -[INFO] Finished at: Tue Oct 25 14:15:37 CDT 2011 -[INFO] Final Memory: 14M/229M -[INFO] ------------------------------------------------------------------------ -.... - -You may now open your web browser and browse to the first page of the html output to see what you have produced! -Generally you can do this with File -> Open File -> which will open a file system browsing screen, navigate to your jetty-documentation directory and then further into target/docbkx/html/index/index.html which is the first page of the produced documentation. - -____ -[TIP] -If the build is broken, feel free to notify us. -____ - -==== Making Changes - -Now that you have built the documentation, you want to edit it and make some changes. -We'll now have to take a bit of as step back and look at how git and github works. -In the above example you have cloned directly from our canonical documentation repository. -Obviously we can not allow anyone immediate access to this repository so you must make a fork of it for your own and then issue back pull requests to build up documentation karma. -In English that means that you would go to the url of the documentation in github: - -.... -https://github.com/jetty/jetty.project -.... - -When you are on this page you will see a little button called 'Fork' which you can click and you will be taken back to your main page on github where you have a new repository. -When you checkout this repository you are free to commit to your heart's delight all the changes you so direly wish to see in the Jetty documentation. -You can clone it to your local machine and build it the same way as above. -So let's start small with a little example. -Find some paragraph in the documentation that you think needs changed. Locate that in the local checkout and make the change. -Now follow the process to push that change back into Jetty proper. -Do make sure the change works and the build isn't broken though so make sure you run maven and check the output. -Then commit the change. - -[source, screen, subs="{sub-order}"] -.... -$ git commit -s -m "Tweaked the introduction to fix a horrid misspelled word." src/main/asciidoc/quickstart/introduction/topic.xml -.... - -____ -[NOTE] -In order for us to accept your commit into the Jetty repository you must have an Eclipse CLA on file and sign your commit. -Please check out the link:#contributing-cla[patches] section for more information. -____ - -This will commit the change in your local repository. -You can then push the change up to your repository on github. - -[source, screen, subs="{sub-order}"] -.... -$ git push -.... - -Now you'll see some output showing that your change has been propagated to your repository on github. -In fact if you navigate to that repository at the top of the files list you should see your comment there. -Success, your change is now positioned for notifying us about it! -If you click on the commit message itself you'll be taken to a screen that shows what files were changed in that commit. In the upper right corner is a button for 'Pull Request'. -When you select this and follow the workflow we will then be notified of your contribution and will be able to apply it to our git repository upon review. - -Thats it! You have successfully contributed to the documentation efforts of the Jetty project. -After enough of these sorts of contributions and building up good community karma, you may be asked to join us as a committer on the documentation. - -==== Conventions - -Below is list of conventions that should be followed when developing documentation within this framework. -These are not set in stone and should be updated as we learn more. - -ventilated prose:: - Each sentence should be on its own line with a hard return at the end of the line. - Asciidoc rendering does not treat this style as separate lines and will produce paragraphs correctly. - The primary benefit is that you can easily see changes between scm versions of files, and it makes it trivial to quickly look through a pull request. - Additional benefits are the ability to comment out a sentence mid paragraph or move sentences around within a paragraph. - Enabling Soft Line Wrap in your favorite editor can make this a bit easier to stomach. - -id's:: - Critically important for being able to generate url's that can be used in a persistent fashion. - Without sane id's the chapters and sections will have generated id which are rooted in some obscure location based - voodoo. - A url using these 'e12c8673' type links will not be durable across generations of the documentation. - These id's need to be used on chapters and sections two deep, and anywhere that you intend to cross link deeper. -+ -The id values go into a global namespace so they must be unique across the entire document or the last example will win and any cross links will go there. -Below is an example of an id. - -.... -[[this-id-an-id]] -.... - -link vs xref:: - The `link:` item should be generally used for linking around the document when you want to choose the text that will be rendered in the link itself. - However if you are linking to a section and want to use the title itself as the link text, use the `xref:` tag without the hashmark in front of the link id. - -version differences:: - In general differences in functionality within a release should go into nested sections and use titles like 'Prior to: ##' or 'In version: ##'. - -license blocks:: - Each adoc file should contain the license block that exists in the index.adoc file and a copy has been added to the bottom of this page as well for reference. - -.... -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -.... - -Some admonition examples: - -______________________________________________ -[NOTE] -A note about the previous case to be aware of. -______________________________________________ - -________________________________________ -[IMPORTANT] -Important notes are marked with an icon. -________________________________________ - -________________________________ -[TIP] -Tips that make your life easier. -________________________________ - -_______________________________________________________ -[CAUTION] -Places where you have to be careful what you are doing. -_______________________________________________________ - -__________________________________________________________________________________________________________________ -[WARNING] -Where extreme care has to be taken. Data corruption or other nasty -things may occur if these warnings are ignored. -__________________________________________________________________________________________________________________ - -==== Oddities - -* If an included file ends with a list entry, it needs to have two empty lines at the end of the file in order for the section rendering to work correctly. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/patches.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/patches.adoc deleted file mode 100644 index 96f1400bd8c7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/patches.adoc +++ /dev/null @@ -1,104 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[contributing-patches]] -=== Contributing Patches - -We love seeing people contribute patches to the Jetty project and the process is relatively simple. -The requirements to commit are modest but very important to the Eclipse Foundation and the intellectual property of the open source project. -The following is the general process by which we operate. - -* You must have a signed Eclipse Contributor Agreement. -* This agreement must be under the _same_ email address as the Git pull request originates from. -* The commit must be signed. -* When the pull request is made, a git-hook will validate the email address. -** If the result is a green checkbox then the Jetty committers can review the pull request. -** If the result is a red X then there is absolutely nothing the Jetty committers can do to accept the commit at this point. -* This may not be the final form a commit will take, there may be some back and forth and you may be asked to re-issue a pull request. - - -Not everything is specifically relevant since we are at GitHub but the crux of things are detailed there. -The ECA is *critically* important to the process. - -[[contributing-eca]] -==== Sign an Eclipse Contributor Agreement (ECA) - -The Eclipse Foundation has a strong Intellectual Property policy which tracks contributions in detail to ensure that: - -1. Did the contributor author 100% of the content? -2. Does the contributor have the rights to contribute this content to Eclipse? -3. Is the contribution under the project’s license(s) (e.g. EPL) - -A contributor needs to e-sign a Eclipse Contributor Agreement (for more explanation see the http://www.eclipse.org/legal/ecafaq.php[Eclipse ECA FAQ] ) regardless of how their contribution patch is provided. -You can familiarize yourself with the Eclipse wiki page at http://wiki.eclipse.org/Development_Resources/Contributing_via_Git[Contributing via Git]. -In order to have a pull request accepted by any Eclipse project you *must* complete this agreement. -____ -[TIP] -Log into the https://www.eclipse.org[Eclipse home page] (you will need to create an account with the Eclipse Foundation if you have not already done so), click on "Eclipse ECA", and complete the form. -Be sure to use the _same email address_ when you create any Git commit records. -____ - -[[contributing-git-config]] -==== Configuring Git - -GitHub has copious amounts of quality documentation on how to interact with the system and you will minimally need to configure the user.email property. -Check out the following link:https://help.github.com/articles/setting-your-email-in-git[guide on GitHub] for more information. - -[[contributing-making-the-commit]] -==== Making the Commit - -When making the commit for the pull request it is _vital_ that you "sign-off" on the commit using `git commit -s` option. -Without this sign-off, your patch cannot be applied to the Jetty repository because it will be rejected. - -You can check out the link:https://help.github.com/articles/signing-tags-using-gpg[guide at Github] for more information. -____ -[TIP] -One way to think of this is that when you sign the ECA you are indicating that you are free to contribute to eclipse, but that doesn't mean everything you ever do can be contributed. -Using the commit signing mechanism indicates that your commit is under the auspices of your agreement. -____ - -If a pull request is for a particular issue in our repository then the format of the commit message is important. -The message should follow the form "Issue #123 ". -When the Jetty project runs releases we have an automated process that scans for commits with this format for inclusion in our VERSION.txt file. - -[source, screen] ----- -> git commit -s -m "Issue #123 resolving the issue by adding widget" ----- - -[[contributing-the-pull-request]] -==== The Pull Request - -Pull requests are very much a GitHub process so best link:https://help.github.com/articles/creating-a-pull-request[explained by Github]. - -[[contributing-our-policies]] -==== Our Policies - -We wholeheartedly welcome contributions to Jetty and will do our best to process them in a timely fashion. -While not every contribution will be accepted, our commitment is to work with interested parties on the things they care about. -With that in mind, we can only handle pull requests with actively engaged parties. -We reserve the right to abandon pull requests whose authors do no respond in a timely fashion. - -We will generally adhere to the following time frames for contributions: - -* Invalid Pull Requests - 1 week -** These pull requests do not follow the contribution requirements for some reason, be it missing contributor agreement or the wrong email. -** We will try and follow up with the pull request author to resolve the issue but much of this is out of our hands and are between committer and the Eclipse Foundation. -** If we do not hear from the contributor after a week we will close the pull request. - -* Valid Pull Requests - 2 weeks -** These pull requests have a green check mark after the commit title. -** If the pull request can be immediately applied we will do so. -** There may need to be some conversation on the issue in which case a committer will follow up with the author in the pull request. -** If the original contributor does not respond within 2 weeks we may close the commit. -** If we see value in the commit yet the author has not responded after 2 weeks we may make some variation of the commit ourselves. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/release-testing.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/release-testing.adoc deleted file mode 100644 index d644b8d15ae4..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/release-testing.adoc +++ /dev/null @@ -1,225 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[release-testing]] -=== Testing a Jetty Release - -To test a Jetty release, complete the following steps for each release you want to test: - -1. Download the staged release: -+ -[source, screen, subs="{sub-order}"] -.... - - wget https://oss.sonatype.org/content/repositories/jetty-[reponumber]/org/eclipse/jetty/jetty-home/[jetty-version]/jetty-home-9.[jetty-minor-version].tar.gz - - -.... -2. Extract to a directory of your choice. -3. Start jetty: -+ -[source, screen, subs="{sub-order}"] -.... - - cd [installdir] ; java -jar start.jar - - -.... -4. If there are no exceptions, proceed. Otherwise, investigate. -5. Open http://localhost:8080/ in a browser. In the examples section click "Test Jetty Webapp". You should see the `test.war` webapp. -6. Go through ALL the tests and verify that everything works as expected. -7. In the examples section click "JAAS Test" and verify that everything works as expected. -8. In the examples section click "JNDI Test" and verify that everything works as expected. -9. In the examples section click "Servlet 3.1 Test" and verify that everything works as expected. -10. Verify that hot deployment works. -+ -[source, screen, subs="{sub-order}"] -.... - - cd [installdir] ; - touch [pathToJettyDistribution]/webapps.demo/test.xml - - -.... -11. Verify that `test.war` gets redeployed in `STDOUT`. -12. Verify that the spdy example webapp and spdy-proxy do work -+ -[source, screen, subs="{sub-order}"] -.... - - cd jetty_src/jetty-spdy/spdy-example-webapp - mvn jetty:run-forked - - -.... -13. Browse to https://localhost:8443 and verify that all looks ok -14. Stop the server with CTRL+C and restart it in proxy mode: -+ -[source, screen, subs="{sub-order}"] -.... - - mvn -Pproxy jetty:run-forked - - -.... -15. Browse to http://localhost:8080 and https://localhost:8443 and verify that all looks ok - -[[testing-cometd]] -==== Testing CometD - -1. Clone CometD. -+ -[source, screen, subs="{sub-order}"] -.... - - clone git://github.com/cometd/cometd.git - git clone git://github.com/cometd/cometd.git - - -.... -2. Edit `pom.xml` and update `jetty-version.` -+ -.... - - - UTF-8 - 7.6.2.v20120308 - ${jetty-version} - 1.6.4 - 3.1.0.RELEASE - - - - Jetty Staging - https://oss.sonatype.org/content/repositories/jetty-988/ - - - - -.... -3. Build Cometd: -+ -[source, screen, subs="{sub-order}"] -.... - - mvn clean install - - -.... -4. Be patient. -5. Run the loadtest as it is described here: http://cometd.org/documentation/2.x/howtos/loadtesting. -Keep the default values, but make sure that you raise the clients setting to 1000. -Run the loadtest until ''JIT compilation time'' is close to a value of zero (about 10k calls). -6. Make sure that the performance results are reasonably fast. -On a MacBook Pro i7 2.6ghz dualcore produces the following: -+ -[source, screen, subs="{sub-order}"] -.... - - ======================================== -Statistics Started at Fri Mar 09 13:44:35 CET 2012 -Operative System: Mac OS X 10.7.3 amd64 -JVM : Oracle Corporation Java HotSpot(TM) 64-Bit Server VM runtime 23.0-b16 1.7.0_04-ea-b14 -Processors: 4 -System Memory: 99.583336% used of 30.0 GiB -Used Heap Size: 36.490677 MiB -Max Heap Size: 1920.0 MiB -Young Generation Heap Size: 896.0 MiB -- - - - - - - - - - - - - - - - - - - - -Testing 1000 clients in 100 rooms, 10 rooms/client -Sending 1000 batches of 10x50 bytes messages every 10000 ?s -[GC [PSYoungGen: 786432K->8736K(917504K)] 823650K->45954K(1966080K), 0.0309940 secs] [Times: user=0.09 sys=0.00, real=0.03 secs] -[GC [PSYoungGen: 795168K->11424K(917504K)] 832386K->48642K(1966080K), 0.0513360 secs] [Times: user=0.13 sys=0.00, real=0.05 secs] -[GC [PSYoungGen: 797856K->14560K(917504K)] 835074K->51778K(1966080K), 0.0432940 secs] [Times: user=0.12 sys=0.00, real=0.05 secs] -[GC [PSYoungGen: 800992K->15680K(917504K)] 838210K->52898K(1966080K), 0.0491200 secs] [Times: user=0.14 sys=0.00, real=0.05 secs] -[GC [PSYoungGen: 802112K->17568K(917504K)] 839330K->54786K(1966080K), 0.0484950 secs] [Times: user=0.14 sys=0.00, real=0.05 secs] -[GC [PSYoungGen: 804000K->17600K(917504K)] 841218K->54818K(1966080K), 0.0456460 secs] [Times: user=0.14 sys=0.01, real=0.05 secs] -[GC [PSYoungGen: 804032K->19488K(917504K)] 841250K->56706K(1966080K), 0.0542000 secs] [Times: user=0.15 sys=0.00, real=0.05 secs] -[GC [PSYoungGen: 805920K->20224K(917504K)] 843138K->57442K(1966080K), 0.0486350 secs] [Times: user=0.16 sys=0.00, real=0.05 secs] -[GC [PSYoungGen: 806656K->20192K(917504K)] 843874K->57410K(1966080K), 0.0566690 secs] [Times: user=0.15 sys=0.00, real=0.06 secs] -[GC [PSYoungGen: 806624K->21152K(917504K)] 843842K->58370K(1966080K), 0.0536740 secs] [Times: user=0.16 sys=0.00, real=0.06 secs] -[GC [PSYoungGen: 807584K->21088K(917504K)] 844802K->58306K(1966080K), 0.0576060 secs] [Times: user=0.18 sys=0.00, real=0.06 secs] -[GC [PSYoungGen: 807520K->22080K(917504K)] 844738K->59298K(1966080K), 0.0663300 secs] [Times: user=0.19 sys=0.01, real=0.06 secs] -- - - - - - - - - - - - - - - - - - - - -Statistics Ended at Fri Mar 09 13:45:21 CET 2012 -Elapsed time: 45826 ms - Time in JIT compilation: 52 ms - Time in Young Generation GC: 606 ms (12 collections) - Time in Old Generation GC: 0 ms (0 collections) -Garbage Generated in Young Generation: 9036.513 MiB -Garbage Generated in Survivor Generation: 21.65625 MiB -Garbage Generated in Old Generation: 0.0 MiB -Average CPU Load: 156.54865/400 ----------------------------------------- - -Outgoing: Elapsed = 45820 ms | Rate = 218 messages/s - 21 requests/s - ~0.083 Mib/s -Waiting for messages to arrive 996960/999045 -All messages arrived 999045/999045 -Messages - Success/Expected = 999045/999045 -Incoming - Elapsed = 45945 ms | Rate = 21743 messages/s - 9496 responses/s(43.68%) - ~8.295 Mib/s -Messages - Wall Latency Distribution Curve (X axis: Frequency, Y axis: Latency): - @ _ 24 ms (8765, 0.88%) - @ _ 45 ms (58952, 5.90%) - @ _ 67 ms (87065, 8.71%) - @ _ 88 ms (113786, 11.39%) - @ _ 109 ms (167426, 16.76%) - @ _ 131 ms (176163, 17.63%) ^50% - @ _ 152 ms (123182, 12.33%) - @ _ 174 ms (90918, 9.10%) - @ _ 195 ms (67209, 6.73%) ^85% - @ _ 216 ms (46989, 4.70%) - @ _ 238 ms (24975, 2.50%) ^95% - @ _ 259 ms (16509, 1.65%) - @ _ 281 ms (8454, 0.85%) ^99% -@ _ 302 ms (4324, 0.43%) -@ _ 323 ms (2955, 0.30%) -@ _ 345 ms (957, 0.10%) ^99.9% -@ _ 366 ms (204, 0.02%) -@ _ 388 ms (144, 0.01%) -@ _ 409 ms (25, 0.00%) -@ _ 430 ms (43, 0.00%) -Messages - Wall Latency 50th%/99th% = 117/275 ms -Messages - Wall Latency Min/Ave/Max = 2/123/430 ms -Messages - Network Latency Min/Ave/Max = 1/114/417 ms -Thread Pool - Concurrent Threads max = 239 | Queue Size max = 1002 | Queue Latency avg/max = 12/101 ms - - -.... -7. Deploy `cometd.war` to the `webapps` directory of the jetty-home tested above. -+ -[source, screen, subs="{sub-order}"] -.... - - cp cometd-demo/target/cometd-demo-[version].war [pathToJetty]/jetty-home-[jetty-version]/webapps/ - - -.... -8. Start jetty and make sure there are no exceptions. -+ -[source, screen, subs="{sub-order}"] -.... - - cd [pathToJetty] && java -jar start.jar - - -.... -9. Go through all pages of the demo and test them: -+ -.... - - http://localhost:8080/cometd-demo-2.4.1-SNAPSHOT/ - - -.... - -If all tests are green, you are done! diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/releasing-jetty.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/releasing-jetty.adoc deleted file mode 100644 index 378b8f1ee4f6..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/releasing-jetty.adoc +++ /dev/null @@ -1,252 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[releasing-jetty]] -=== Releasing Jetty - -There are a number of steps to releasing jetty. -It is not just limited to running a couple of maven commands and then moving onto bigger and better things. -There are a number of process related issues once the fun maven bits have been completed. - -[[releasing-process]] -==== Building and Staging a Releasable Version - -This release script is for jetty-9 (to release jetty-7 or jetty-8 see older documentation). - -1. Pick your version identification strings. -+ -These follow a strict format and will be used when prompted during step link:#prepare-release-step[listitem_title] below. -+ -.... -Release Version : 9.0.0.v20130322 (v[year][month][day]) -Next Development Version : 9.0.1-SNAPSHOT -Tag Name : jetty-9.9.0.v20130322 -.... - -2. We use the 'release-9' branch to avoid problems with other developers actively working on the master branch. -+ -[source, screen, subs="{sub-order}"] -.... -// Get all of the remotes -$ git pull origin -// Create a local tracking branch (if you haven't already) -$ git branch --track release-9 refs/remotes/origin/release-9 -// Check out your local tracking branch. -$ git checkout release-9 -// Merge from master into the branch (this becomes your point in time -// from master that you will be releasing from) -$ git merge --no-ff master -.... - -3. Update the VERSION.txt with changes from the git logs, this populates the resolves issues since the last release. -+ -[source, screen, subs="{sub-order}"] -.... -$ mvn -N -Pupdate-version -.... - -4. Edit the VERSION.txt file to set the 'Release Version' at the top alongside the Date of this release. -+ -[source, screen, subs="{sub-order}"] -.... -$ vi VERSION.txt -.... - -5. Make sure everything is commit'd and pushed to github.com/eclipse/jetty.project -+ -[source, screen, subs="{sub-order}"] -.... -$ git commit -m "Updating VERSION.txt top section" VERSION.txt -$ git push origin release-9 -.... - -6. Prepare the Release -+ -____ -[NOTE] -This step updates the elements in the pom.xml files, does a test build with these new versions, and then commits the pom.xml changes to your local git repo. -The `eclipse-release` profile is required on the prepare in order to bring in the jetty aggregates as that profile defines a module which is ignored otherwise. -____ - -+ -[source, screen, subs="{sub-order}"] -.... -$ mvn release:prepare -DreleaseVersion=9.0.0.v20130322 \ - -DdevelopmentVersion=9.0.1-SNAPSHOT \ - -Dtag=jetty-9.0.0.v20130322 \ - -Peclipse-release -.... -7. Perform the Release -+ -____ -[NOTE] -This step performs the release and deploys it to a oss.sonatype.org staging repository. -____ - -+ -[source, screen, subs="{sub-order}"] -.... -$ mvn release:perform -.... -8. Set up files for next development versions. -+ -Edit `VERSION.txt` for 'Next Development Version' at the top. -Do not date this line. -+ -Make sure everything is commit'd and pushed to github.com/eclipse/jetty.project -+ -[source, screen, subs="{sub-order}"] -.... -$ vi VERSION.txt -$ git commit -m "Updating VERSION.txt top section" VERSION.txt -$ git push origin release-9 -.... - -9. Close the staging repository on oss.sonatype.org - -10. Announce stage to the mailing list for testing. - -11. Once the staged repository has been approved by the rest of the committers. -+ -* Release the staging repository to maven central on oss.sonatype.org -* Merge back the changes in release-9 to master -+ -[source, screen, subs="{sub-order}"] -.... -$ git checkout master -$ git merge --no-ff release-9 -$ git push origin master -.... - -[[releasing-aggregates]] -==== Building and Deploying Aggregate Javadoc and Xref - -Define the jetty.eclipse.website server entry in your .m2/settings.xml file. -You'll need to have access to the dev.eclipse.org machine to perform these actions. -If you don't know if you have access to this then you probably don't and will need to ask a project leader for help. - -To build and deploy the aggregate javadoc and jxr bits: - -[source, screen, subs="{sub-order}"] -.... -$ cd target/checkout -$ mvn -Paggregate-site javadoc:aggregate jxr:jxr -$ mvn -N site:deploy -.... - -This will generate the aggregate docs and deploy them to the `/home/www/jetty//jetty-project` directory on download.eclipse.org. - -[[releasing-distributions]] -==== Deploying Distribution Files - -Since we also provide alternative locations to download jetty distributions we need to copy these into place. -There are a couple of scripts that will take care of this although they need to be localized to your particular execution environment and you need to have authorization to put stuff where it needs to go. -These scripts are located at: - -* http://git.eclipse.org/c/jetty/org.eclipse.jetty.admin.git/tree/release-scripts. - -To localize the scripts to your environment: - -* ensure you have "curl" installed -* edit the scripts and replace all ssh login lines with your own login id - -Once these are setup you can deploy a release to eclipse with the following incantation: - -[source, screen, subs="{sub-order}"] -.... -$ ./promote-to-eclipse.sh 9.0.0.v20130322 -.... - -Each of these scripts will download all of the relevant files from maven central and then copy them into the correct location on eclipse infrastructure. -On the eclipse side of it they will also adjust the xref and javadoc documentation links if they remain broken as well as regenerate all of the html files on the eclipse download site. - -[[releasing-stable-links]] -==== Updating Stable Links - -Since we are not allowed to have symbolic links on the download site we have to log into the machine manually and remove the previous stable directory and update it with a new release. -Maintaining the conventions we use on the site will allow all 'stable' links to be stable and not needed to update to the latest major Jetty build version: - -[source, screen, subs="{sub-order}"] -.... -$ ssh @build.eclipse.org -$ cd ~downloads/jetty/ -$ rm -Rf stable-9 -$ cp -r stable-9 -$ ./index.sh -.... - -This needs to be done for all Eclipse Jetty releases (regardless of version). In addition we have to work to reduce the footprint of jetty on the primary eclipse download resources so we want to move older releases to the eclipse archive site. - -[source, screen, subs="{sub-order}"] -.... -$ cd ~/downloads/jetty -$ mv /home/data/httpd/archive.eclipse.org/jetty/ -$ ./index.sh -.... - -Periodically we need to do the same for the osgi P2 repositories to keep the size of our downloads directory at a reasonable size. - -==== Building an OSGi P2 Repository - -Most of the jetty jars are also osgi bundles, plus we release some specific bundles that link:#framework-jetty-osgi[integrate jetty closely with osgi]. -To do this, we use a Hudson job on the eclipse infrastructure. You will need to have permission to access https://ci.eclipse.org/shared/view/Jetty-RT/ - -There are Hudson jobs that build osgi p2 repos for each of the major releases of jetty:7 (jetty-rt-bundles-7), 8 (jetty-rt-bundles-8) and 9 (jetty-rt-bundles-9). -You will need to start a manual build of the job that matches the version of jetty that you are releasing. -You will be prompted to supply some parameters to the build: - -pack_and_sign:: - By default, this is ticked. Leave it ticked. -jetty_release-version:: - Enter the version number of the release, eg 9.2.6.v20141205 -force_context_qualifier:: - Leave this blank. -set_pom_version:: - Enter the major.minor.point release number, eg 9.2.6 -delete_tycho_meta:: - This is ticked by default. Leave it ticked -BRANCH_NAME:: - This is not the branch of the jetty release. Rather it refers to the branch structure of the project that drives the jetty p2 release. - It will already be set correctly for the selected job, so don't change it unless you have an extremely good reason. - -Once you have supplied the necessary parameters, the build job will commence and the bundles and update site zips will generated and automatically placed in the `/home/data/httpd/downlaod.eclipse.org/jetty/updates/jetty-bundles-[MAJOR.VERSION].x`, where [MAJOR.VERSION] matches the major version number of the jetty release you are doing. -These files will then be visible from http://download.eclipse.org/jetty/updates/jetty-bundles-[MAJOR.VERSION].x, where [MAJOR.VERSION] corresponds to the major version of the jetty release you are doing. - -[[releasing-documentation]] -==== Release Documentation - -There are two git repositories you need to be aware of for releasing jetty-documentation.The jetty-documentation is located in our github repository and the jetty-website is located at eclipse. - -jetty-documentation:: -https://github.com/jetty-project/jetty-documentation -jetty-website:: -http://github.com/jetty/jetty.website - -Do the following steps to publish documentation for the release: - -1. Checkout the jetty-documentation repository. -2. Edit the of the jetty-documentation pom.xml and change it _locally_ to be the release number, eg 9.2.6.v20141205 -3. Build the documentation with mvn clean install -4. Checkout the jetty-website -5. Inside the documentation/ directory, make a directory named the same as the release number, eg 9.2.6.v20141205/ -6. Copy the built `documentation` from jetty-documentation/target/docbkx/html/jetty into the new directory -7. Edit the `index.html` file in the `documentation` directory and add the newly released documentation url. -Make sure you follow the other examples and include the `rel="nofollow"` attribute on the link so that search engines do not crawl newly created documentation, otherwise we are subject to duplicate content penalties in SEO. -8. Commit the changes to the jetty-website project - -____ -[NOTE] -There is a separate Jenkins build job that publishes documentation to https://jetty.org/docs/ triggered by a push of changed files to the jetty-documentation project. -If you commit your change to the number from step 2, then these builds will use the same release version number. -It is preferable if you _don't_ commit that version number change, or better yet, ensure that it is set to the next -SNAPSHOT version number for your jetty major release number. -____ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/source-build.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/source-build.adoc deleted file mode 100644 index cfaa3fcf8304..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/contributing/source-build.adoc +++ /dev/null @@ -1,93 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[contributing-source-build]] -=== Source Control and Building - -If you want to contribute to the development of jetty, you will need to work with a handful of technologies. - -[[contributing-source]] -==== Source Control - -Jetty uses several development trunks for its artifacts. -They are mirrored on github through http://github.com/eclipse, or you can look through them via the Eclipse setup at the URLs below. - -===== Primary Interest SCM URLs - -These are the URLs to the GIT repositories for the Jetty code. -They are for people who are working on the Jetty project, as well as for people who are interested in examining or modifying the Jetty code for their own projects. - -Jetty Project Repository:: - https://github.com/jetty/jetty.project - -===== Build and Project Infrastructure SCM URLs - -These are the URLs for Jetty-related code and metadata. -These are not needed to use Jetty; these are primarily of use for people who are working with Jetty-the-project (as opposed to using Jetty-the-server in their own projects). - -Administrative pom.xml file:: - https://github.com/eclipse/jetty.parent -Build related artifacts that release separately, common assembly descriptors, remote resources, etc.:: - https://github.com/eclipse/jetty.toolchain -Files associated with the development of Jetty -- code styles, formatting, iplogs, etc.:: - http://git.eclipse.org/c/jetty/org.eclipse.jetty.admin.git - -==== Build - -Jetty requires the use of Java 8 and the latest releases are always recommended to build. - -Jetty uses http://maven.apache.org/[Apache Maven 3] for managing its build and primary project metadata. - -Building Jetty should simply be a matter of changing into the relevant directory and executing the following commands: - -[source, screen, subs="{sub-order}"] -.... - -$ git clone https://github.com/jetty/jetty.project.git -$ cd jetty.project -$ mvn install - - -.... - -All relevant dependencies will be downloaded into your local repository automatically. - -____ -[NOTE] -Jetty has a great many test cases that run through the course of its build. -Periodically we find some test cases to be more time dependent than they should be and this results in intermittent test failures. -You can help track these down by opening a bug report. -____ - -==== Import into Eclipse - -Jetty is a Maven project. To develop Jetty in Eclipse, follow these directions: - -===== Install m2e plugin - -1. From the Eclipse menu at the top of the screen, select _Help > Eclipse Marketplace._ -2. Search for __m2e__. -3. Install the _Maven Integration for Eclipse_ - -===== Clone the git repository - -Using either the egit plugin or git on the commandline (as in the build section above), obtain the jetty source. - -===== Import the Maven Projects - -1. From the Eclipse menu, select _File > Import_ -2. From the Maven folder, select _Existing Maven Projects._ -3. Click __Next__. -4. In the Import Maven projects pane, click _Browse_ and select the top folder of the jetty source tree. -5. Click _Next/Finish_ to import all of jetty into Eclipse. -6. Wait for Eclipse and m2e to compilie and set up the project. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/chapter.adoc deleted file mode 100644 index cfe9b923ca70..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/chapter.adoc +++ /dev/null @@ -1,25 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[advanced-debugging]] -== Debugging - -=== Options - -Given how flexible Jetty is in how it can be configured and deployed into development and production, there exists a wealth of different options for debugging your application in you favorite environment. -In this section we will gather up some of these different options available and explain how you can use them. -If you would like to contribute to this section simply fork the repository and contribute the information, or open a github issue with the information and we'll bring it over. - -include::enable-remote-debugging.adoc[] -include::debugging-with-intellij.adoc[] -include::debugging-with-eclipse.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/debugging-with-eclipse.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/debugging-with-eclipse.adoc deleted file mode 100644 index 366b484f566a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/debugging-with-eclipse.adoc +++ /dev/null @@ -1,54 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[debugging-with-eclipse]] -=== Debugging With Eclipse - -There are a number of options available to debug your application in Eclipse. - -If not done already prepare your application for remote debugging as described here: xref:enable-remote-debugging[] - -==== Linking with Eclipse - -Next we need to link the Eclipse project with the deployed webapp. - -1. Within Eclipse, right-click on the project containing the webapp deployed into jetty and select *Debug -> Debug Configurations* and create a new configuration of **Remote Java Application**. -Make sure the port you choose is the same as the one you added in xref:enable-remote-debugging[]. -+ -image:debug-eclipse-1.png[image,width=576] - -2. Next in your webapp you can set a breakpoint within a servlet which when it is tripped will halt the remote jvm's processing thread to await for debugging commands from your Eclipse instance. -+ -image:debug-eclipse-2.png[image,width=576] - -3. Accessing that servlet within your browser, pointed at your remote debug configurated jetty-home, should transition your Eclipse instance to the standard Debug view. -+ -image:debug-eclipse-3.png[image,width=576] - -[[eclipse-within-eclipse]] -==== Within Eclipse - -Since Jetty can be incredibly simple to embed, many people choose to create a small `main` method which they can launch directly within Eclipse in order to more easily debug their entire application. -The best place to get started on this approach is to look through xref:embedding-jetty[] and the xref:embedded-examples[] sections. - -Once you have a main method defined in order to launch your application, right-click on the source file and select**Debug As -> Java Application**. -In your *Console* tab within Eclipse you should see your application startup and once it has completed startup you should be able to configure breakpoints and hit the Jetty instance as normal via your web browser. - -____ -[TIP] -You can easily configure logging through a `jetty-logging.properties` -file. If this file is on your classpath then Jetty will use it for -configuring logging, we use this approach extensively throughout Jetty -development and it makes life ever so much easier. You can see this in -action in the xref:configuring-jetty-stderrlog[] section. -____ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/debugging-with-intellij.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/debugging-with-intellij.adoc deleted file mode 100644 index 325042a9179f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/debugging-with-intellij.adoc +++ /dev/null @@ -1,64 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[debugging-with-intellij]] -=== Debugging With IntelliJ - -There are a number of options available to debug your application in IntelliJ. - -If not done already prepare your application for remote debugging as described here: xref:enable-remote-debugging[] - -==== Linking with IntelliJ - -Next we need to link the IntelliJ project with the deployed webapp. - -1. Within IntelliJ, open the project containing the webapp deployed into jetty that you want to debug. Select**Run -> Edit Configurations**. -Add a new configuration by clicking the "+" icon. Choose **Remote**. -Make sure the port you choose is the same as the one you added in xref:enable-remote-debugging[]. -+ -image:intellij_new_remote_config.png[image,width=800] - -2. Next in your webapp you can set a breakpoint within a servlet which when it is tripped will halt the remote jvm's processing thread to await for debugging commands from your IntelliJ instance. -To set a breakpoint, simply open the servlet or any other class you want to debug and click left to the line you want to set the breakpoint at (where the red dot is on the next screenshot). -The red dot and red background on the line mark the breakpoint. -+ -image:intellij_set_breakpoint.png[image,width=800] - -3. Accessing that servlet within your browser, pointed at your remote debug configured jetty-home, should transition your IntelliJ instance to the standard debugger view. -+ -image:intellij_debug_view.png[image,width=800] - -[[intellij-within-intellij]] -==== Within IntelliJ - -Since Jetty can be incredibly simple to embed, many people choose to create a small `main` method which they can launch directly within IntelliJ in order to more easily debug their entire application. -The best place to get started on this approach is to look through xref:embedding-jetty[] and the xref:embedded-examples[] sections. - -Once you have a main method defined in order to launch your application, open the source file and right-click the main method. -Select *Debug* or simply hit CTRL+SHIFT+D. -In your *Console* tab within IntelliJ you should see your application startup and once it has completed startup you should be able to configure breakpoints and hit the Jetty instance as normal via your web browser. -The same thing works for unit tests. -Instead of the main method run debug on the test method you want to debug. - -image:intellij_select_debug.png[image,width=800] - -Debugging in IntelliJ is extremely powerful. -For example it's possible to have conditional breakpoints that only trigger a break if the configured conditions are met. -Have a look at the various tutorials in the internet or the http://www.jetbrains.com/idea/webhelp/getting-help.html[IntelliJ documentation] for further details. - -____ -[TIP] -You can easily configure logging through a `jetty-logging.properties` file. -If this file is on your classpath then Jetty will use it for configuring logging, we use this approach extensively throughout Jetty development and it makes life ever so much easier. -You can see this in action in the xref:configuring-jetty-stderrlog[] section. -____ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/enable-remote-debugging.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/enable-remote-debugging.adoc deleted file mode 100644 index 1fbb55472c7b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/debugging/enable-remote-debugging.adoc +++ /dev/null @@ -1,95 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[enable-remote-debugging]] -=== Enable remote debugging - -[[remote-debugging]] -==== Remote Debugging - -If you have a web application deployed into Jetty you can interact with it remotely from a debugging perspective easily. -The basics are that you must start up the remote JVM with additional parameters and then start up a remote debugging session in Eclipse for the webapp in question. -This is easily accomplished. - -____ -[NOTE] -This example assumes you are deploying your web application into a jetty-base. -____ - -===== Starting Jetty - -Assuming you have your webapp deployed into jetty, there are two different ways to approach this: - -Via command line:: - Add the required parameters on the commandline like so. -+ -[source, screen, subs="{sub-order}"] -.... - -$ java -Xdebug -agentlib:jdwp=transport=dt_socket,address=9999,server=y,suspend=n -jar start.jar - - -.... - -Via `start.ini`:: - This approach is best used if you want to debug a particular jetty-base and not have to remember the commandline incantations. -+ -1. Edit the `start.ini` and uncomment the --exec line, this is required if you are adding jvm options to the start.ini file as jetty-start must generate the classpath required and fork a new jvm. -2. Add the parameters mentioned above in the Command Line option so your start.ini looks like this: -+ -[source, plain, subs="{sub-order}"] ----- -#=========================================================== -# Configure JVM arguments. -# If JVM args are include in an ini file then --exec is needed -# to start a new JVM from start.jar with the extra args. -# If you wish to avoid an extra JVM running, place JVM args -# on the normal command line and do not use --exec -#----------------------------------------------------------- ---exec --Xdebug --agentlib:jdwp=transport=dt_socket,address=9999,server=y,suspend=n -# -Xmx2000m -# -Xmn512m -# -XX:+UseConcMarkSweepGC -# -XX:ParallelCMSThreads=2 -# -XX:+CMSClassUnloadingEnabled -# -XX:+UseCMSCompactAtFullCollection -# -XX:CMSInitiatingOccupancyFraction=80 -# -verbose:gc -# -XX:+PrintGCDateStamps -# -XX:+PrintGCTimeStamps -# -XX:+PrintGCDetails -# -XX:+PrintTenuringDistribution -# -XX:+PrintCommandLineFlags -# -XX:+DisableExplicitGC - - ----- -+ -Uncomment any other jvm environmental options you so desire for your debugging session. - -3. Regardless of the option chosen, you should see the following lines at the top of your jetty startup. -+ -[source, plain, subs="{sub-order}"] ----- -Listening for transport dt_socket at address: 9999 - ----- - -===== Linking with your IDE - -Refer to the documentation for your ide: - -* xref:debugging-with-intellij[] -* xref:debugging-with-eclipse[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/chapter.adoc deleted file mode 100644 index 0ec821b99ec8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/chapter.adoc +++ /dev/null @@ -1,26 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-deployment]] -== Deploying to Jetty - -This chapter discusses various ways to deploy applications with Jetty. -Topics range from deployment bindings to deploying third party products. -It also includes information about the Deployment Manager and WebApp Provider. - -include::configuring-specific-webapp-deployment.adoc[] -include::deployment-processing-webapps.adoc[] -include::static-content-deployment.adoc[] -include::deployment-architecture.adoc[] -include::quickstart-webapp.adoc[] -//include::overlay-deployer.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/configuring-specific-webapp-deployment.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/configuring-specific-webapp-deployment.adoc deleted file mode 100644 index 17670bf24e9e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/configuring-specific-webapp-deployment.adoc +++ /dev/null @@ -1,161 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-specific-webapp-deployment]] -=== Configuring a Specific Web Application Deployment - -Using the Automatic Web Application Deployment model is quick and easy, but sometimes you might need to tune certain deployment properties (for example, you want to deploy with a context path that is not based on the file name, or you want to define a special database connection pool just for this web application). -You can use a xref:deployable-descriptor-file[] to accomplish such tuning. - -[[deployable-descriptor-file]] -==== Jetty Deployable Descriptor XML File - -Jetty supports deploying Web Applications via XML files which will build an instance of a link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html[ContextHandler] that Jetty can then deploy. - -[[using-basic-descriptor-files]] -==== Using Basic Descriptor Files - -In a default Jetty installation, Jetty scans its `$JETTY_HOME/webapps` directory for context deployment descriptor files. -To deploy a web application using such a file, simply place the file in that directory. - -The deployment descriptor file itself is an xml file that configures a link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`] class. -For a basic installation only two properties need configured: - -war:: - The filesystem path to the web application file (or directory) -contextPath:: - The context path to use for the web application - -For example, here is a descriptor file that deploys the file `/opt/myapp/myapp.war` to the context path `/wiki`: - -[source, xml, subs="{sub-order}"] ----- - - - - - /wiki - /opt/myapp/myapp.war - ----- - -Both `SystemProperty` and `Property` elements can be used in the descriptor file. -For example, if the system property is set to `myapp.home=/opt/myapp`, the previous example can be rewritten as: - -[source, xml, subs="{sub-order}"] ----- - - - - - /wiki - /myapp.war - ----- - -If the home path for an application needs altered, only the system property needs changed. -This is useful if the version of an app is frequently changed. - -____ -[NOTE] -To ensure your `web.xml` files are validated, you will need to set the `validateXml` attribute to true as described link:#jetty-xml-dtd[here.] -____ - -[[configuring-advanced-descriptor-files]] -==== Configuring Advanced Descriptor Files - -Official documentation for the for the link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`] class lists all the properties that can be set. -Here are some examples that configure advanced options in the descriptor file. - -This first example tells Jetty not to expand the WAR file when deploying it. -This can help make it clear that users should not make changes to the temporary unpacked WAR because such changes do not persist, and therefore do not apply the next time the web application deploys. - -[source, xml, subs="{sub-order}"] ----- - - - - - /wiki - /myapp.war - false - ----- - -The next example retrieves the JavaEE Servlet context and sets an initialization parameter on it. -The `setAttribute` method can also be used to set a Servlet context attribute. -However, since the `web.xml` for the web application is processed after the deployment descriptor, the `web.xml` values overwrite identically named attributes from the deployment descriptor. - -[source, xml, subs="{sub-order}"] ----- - - - - - /wiki - /myapp.war - - - myapp.config - /config/app-config.xml - - - ----- - -The following example sets a special `web.xml` override descriptor. -This descriptor is processed after the web application's `web.xml`, so it may override identically named attributes. -This feature is useful when adding parameters or additional Servlet mappings without breaking open a packed WAR file. - -[source, xml, subs="{sub-order}"] ----- - - - - - /wiki - /myapp.war - /opt/myapp/overlay-web.xml - ----- - -The next example configures not only the web application context, but also a database connection pool (see xref:jndi-datasource-examples[]) that the application can then use. -If the `web.xml` does not include a reference to this data source, an override descriptor mechanism (as shown in the previous example) can be used to include it. - -[source, xml, subs="{sub-order}"] ----- - - - - - /wiki - /myapp.war - - - - jdbc/DSTest - - - org.some.Driver - jdbc.url - jdbc.user - jdbc.pass - - - - ----- - -There are many other settings that can be changed in a link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`]. -The link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[javadoc] for `WebAppContext` is a good source of information. -Also see the documentation on link:#troubleshooting-zip-exceptions[avoiding zip file exceptions] for a description of `WebAppContext` settings that determine such things as whether or not the war is automatically unpacked during deployment, or whether certain sections of a webapp are copied to a temporary location. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/deployment-architecture.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/deployment-architecture.adoc deleted file mode 100644 index 94b241ed2fa3..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/deployment-architecture.adoc +++ /dev/null @@ -1,166 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[deployment-architecture]] -=== Deployment Architecture - -Jetty is built around an extensible Deployment Manager architecture complete with formal LifeCycle for Web Applications going through it. - -For Jetty to serve content (static or dynamic), a link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html[ContextHandler] needs to be configured and added to Jetty in the appropriate location. -A pluggable `DeploymentManager` exists to make this process easier. -The Jetty distribution contains example `DeploymentManager` configurations to deploy WAR files found in a directory to Jetty, and to deploy Jetty context xml files into Jetty as well. - -The `DeploymentManager` is the heart of the typical webapp deployment mechanism; it operates as a combination of an Application LifeCycle Graph, Application Providers that find and provide Applications into the Application LifeCycle Graph, and a set of bindings in the graph that control the deployment process. - -image:Jetty_DeployManager_DeploymentManager_Roles.png[image,width=195] - -[[udm-application-providers]] -==== Application Providers - -Before Jetty deploys an application, an link:{JDURL}/org/eclipse/jetty/deploy/AppProvider.html[`AppProvider`] identifies the App and then provides it to the `DeploymentManager`. -The main `AppProvider` with the Jetty distribution is the link:{JDURL}/org/eclipse/jetty/deploy/providers/WebAppProvider.html[`WebAppProvider`.] - -[[udm-application-lifecycle-graph]] -==== Application LifeCycle Graph - -The core feature of the `DeploymentManager` is the link:{JDURL}/org/eclipse/jetty/deploy/AppLifeCycle.html[Application LifeCycle Graph]. - -image:Jetty_DeployManager_AppLifeCycle-1.png[image,width=340] - -The nodes and edges of this graph are pre-defined in Jetty along the most common actions and states found. -These nodes and edges are not hardcoded; they can be adjusted and added to depending on need (for example, any complex requirements for added workflow, approvals, staging, distribution, coordinated deploys for a cluster or cloud, etc.). - -New applications enter this graph at the Undeployed node, and the link:{JDURL}/org/eclipse/jetty/deploy/DeploymentManager.html#requestAppGoal(org.eclipse.jetty.deploy.App[`java.lang.String DeploymentManager.requestAppGoal(App,String)`] method pushes them through the graph. - -[[udm-lifecycle-bindings]] -==== LifeCycle Bindings - -A set of default link:{JDURL}/org/eclipse/jetty/deploy/AppLifeCycle.Binding.html[`AppLifeCycle.Bindings`] defines standard behavior, and handles deploying, starting, stopping, and undeploying applications. -If desired, custom `AppLifeCycle.Bindings` can be written and assigned anywhere on the Application LifeCycle graph. - -Examples of new `AppLifeCycle.Binding` implementations that can be developed include: - -* Validating the incoming application. -* Preventing the deployment of known forbidden applications. -* Submitting the installation to an application auditing service in a corporate environment. -* Distributing the application to other nodes in the cluster or cloud. -* Emailing owner/admin of change of state of the application. - -There are four default bindings: - -* link:{JDURL}/org/eclipse/jetty/deploy/bindings/StandardDeployer.html[`StandardDeployer`] — Deploys the ContextHandler into Jetty in the appropriate place. -* link:{JDURL}/org/eclipse/jetty/deploy/bindings/StandardStarter.html[`StandardStarter`] — Sets the ContextHandler to started and start accepting incoming requests. -* link:{JDURL}/org/eclipse/jetty/deploy/bindings/StandardStopper.html[`StandardStopper`] — Stops the ContextHandler and stops accepting incoming requests. -* link:{JDURL}/org/eclipse/jetty/deploy/bindings/StandardUndeployer.html[`StandardUndeployer`] — Removes the ContextHandler from Jetty. - -image:Jetty_DeployManager_DefaultAppLifeCycleBindings.png[image,width=851] - -A fifth, non-standard binding, called link:{JDURL}/org/eclipse/jetty/deploy/bindings/DebugBinding.html[DebugBinding], is also available for debugging reasons; it logs the various transitions through the Application LifeCycle. - -===== Using GlobalWebappConfigBinding - -In addition to the LifeCycle bindings discussed above, there is also the `GlobalWebappConfigBinding` which, when added to the `DeploymentManager` will apply an additional configuration XML file to each webapp that it deploys. -This can useful when setting server or system classes, or when defining link:#override-web-xml[override descriptors.] -This configuration XML file will be _in addition to_ any context XML file that exists for the webapp; it will be applied _after_ any context XML files but _before_ the webapp is started. -The format for the XML file is the same as any context XML file and can be used to same parameters for a webapp. - -To use this binding, you can either modify the existing `jetty-deploy.xml` which comes with the Jetty distribution (be sure to link:#startup-base-and-home[copy it to your $JETTY_BASE/etc directory first]), or by link:#custom-modules[creating a new module] file which calls to an additional XML file. - -[source, xml, subs="{sub-order}"] ----- - - - - /etc/global-webapp-config.xml - - - ----- - -[[default-web-app-provider]] -==== Understanding the Default WebAppProvider - -The link:{JDURL}/org/eclipse/jetty/deploy/providers/WebAppProvider.html[WebAppProvider] is used for the deployment of Web Applications packaged as WAR files, expanded as a directory, or declared in a xref:deployable-descriptor-file[]. -It supports hot (re)deployment. - -The basic operation of the `WebAppProvider` is to periodically scan a directory for deployables. -In the standard Jetty Distribution, this is configured in the `${jetty.home}/etc/jetty-deploy.xml` file. - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - /webapps - /etc/webdefault.xml - 1 - true - - - - - - - ----- - -The above configuration will create a `DeploymentManager` tracked as a Server LifeCycle Bean, with the following configuration. - -contexts:: - A passed in reference to the HandlerContainer into which the discovered webapps are deployed. - This is normally a reference that points to the `id="Contexts"` found in the `${jetty.home}/etc/jetty.xml` file, which itself is an instance of `ContextHandlerCollection`. - -monitoredDirName:: - The file path or URL to the directory to scan for web applications. - - Scanning follows these rules: - - 1. A base directory must exist. - 2. Hidden Files (starting with `"."`) are ignored. - 3. Directories with names ending in `".d"` are ignored. - 4. Common CVS directories `"CVS"` and `"CVSROOT"` are ignored. - 5. Any `*.war` files are considered link:#automatic-webapp-deployment[automatic deployables]. - 6. Any `*.xml` files are considered link:#deployable-descriptor-file[context descriptor deployables]. - 7. In the special case where both a WAR file and XML file exists for same base name, the XML file is assumed to configure and reference the WAR file (see xref:configuring-specific-webapp-deployment[]). - Since jetty-9.2.7, if either the WAR file or its corresponding XML file changes, the webapp will be redeployed. - 8. A directory is considered to be deployable. - 9. In the special case where both a Directory and WAR file of the same name exists, the WAR file is assumed to be an automatic deployable. - 10. In the special case where both a Directory and XML file of the same name exists, the XML file is assumed to configure and reference the Directory. - 11. All other directories are subject to automatic deployment. - 12. If automatic deployment is used, and the special filename `root.war/ROOT.war` or directory name `root/ROOT` will result in a deployment to the `"/"` context path. - -defaultsDescriptor:: - Specifies the default Servlet web descriptor to use for all Web Applications. - The intent of this descriptor is to include common configuration for the Web Application before the Web Application's own `/WEB-INF/web.xml` is applied. - The `${jetty.home}/etc/webdefault.xml` that comes with the Jetty distribution controls the configuration of the JSP and Default servlets, along with MIME-types and other basic metadata. - -scanInterval:: - The period in seconds between sweeps of the `monitoredDirName` for changes: new contexts to deploy, changed contexts to redeploy, or removed contexts to undeploy. - -extractWars:: - If parameter is true, any packed WAR or zip files are first extracted to a temporary directory before being deployed. - This is advisable if there are uncompiled JSPs in the web apps. - -parentLoaderPriority:: - Parameter is a boolean that selects whether the standard Java link:#jetty-classloading[parent first delegation] is used or the link:#jetty-classloading[servlet specification webapp classloading priority]. - The latter is the default. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/deployment-processing-webapps.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/deployment-processing-webapps.adoc deleted file mode 100644 index d9b24efd246b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/deployment-processing-webapps.adoc +++ /dev/null @@ -1,297 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-webapps]] -=== Deployment Processing of WebAppContexts - -Web applications require a certain amount of processing before they can go into service: they may need to be unpacked, a special classloader created for their jar files, `web.xml` and `web-fragment.xml` descriptors processed, and classes scanned for annotations amongst other things. -As web applications have become more complex, Jetty has added ways to assist with customization by either broadening or lessening the amount of processing that is done at deployment time. -This section will examine this processing and it can be tailored to fit individual needs. - -If instead you're looking for information on how to configure a specific `WebAppContext` - such as its context path, whether it should be unpacked or not - then you can find that in the section entitled link:#configuring-specific-webapp-deployment[Configuring a Specific WebApp Deployment]. - -[[webapp-configurations]] -==== Configuration Classes - -As a webapp is being deployed, a series of link:{JDURL}/org/eclipse/jetty/webapp/Configuration.html[org.eclipse.jetty.webapp.Configuration] classes are applied to it, each one performing a specific function. -The ordering of these Configurations is significant as subsequent Configurations tend to build on information extracted or setup in foregoing Configurations. -These are the default list, in order, of Configurations that are applied to each link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[org.eclipse.jetty.webapp.WebAppContex]t: - -.Default Configuration classes -[cols=",",] -|======================================================================= -|link:{JDURL}/org/eclipse/jetty/webapp/WebInfConfiguration.html[org.eclipse.jetty.webapp.WebInfConfiguration] -|Extracts war, orders jars and defines classpath - -|link:{JDURL}/org/eclipse/jetty/webapp/WebXmlConfiguration.html[org.eclipse.jetty.webapp.WebXmlConfiguration] -|Processes a WEB-INF/web.xml file - -|link:{JDURL}/org/eclipse/jetty/webapp/MetaInfConfiguration.html[org.eclipse.jetty.webapp.MetaInfConfiguration] -|Looks in container and webapp jars for META-INF/resources and -META-INF/web-fragment.xml - -|link:{JDURL}/org/eclipse/jetty/webapp/FragmentConfiguration.html[org.eclipse.jetty.webapp.FragmentConfiguration] -|Processes all discovered META-INF/web-fragment.xml files - -|link:{JDURL}/org/eclipse/jetty/webapp/JettyWebXmlConfiguration.html[org.eclipse.jetty.webapp.JettyWebXmlConfiguration] -|Processes a WEB-INF/jetty-web.xml file -|======================================================================= - -===== Anatomy of a Configuration Class - -A Configuration class is called 5 times in different phases of the link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext's`] lifecycle: - -preConfigure:: - As the `WebAppContext` is starting up this phase is executed. - The `Configuration` should discover any of the resources it will need during the subsequent phases. -configure:: - This phase is where the work of the class is done, usually using the resources discovered during the `preConfigure` phase. -postConfigure:: - This phase allows the `Configuration` to clear down any resources that may have been created during the previous 2 phases that are not needed for the lifetime of the `WebAppContext`. -deconfigure:: - This phase occurs whenever a `WebAppContext` is being stopped and allows the Configuration to undo any resources/metadata that it created. - A `WebAppContext` should be able to be cleanly start/stopped multiple times without resources being held. -destroy:: - This phase is called when a `WebAppContext` is actually removed from service. - For example, the war file associated with it is deleted from the $JETTY_HOME/webapps directory. - -Each phase is called on each `Configuration` class in the order in which the `Configuration` class is listed. -Using the default `Configuration` classes as an example, `preConfigure()` will be called on `WebInfConfiguration`, `WebXmlConfiguration`, `MetaInfConfiguration`, `FragmentConfiguration` and then `JettyWebXmlConfiguration`. -The cycle begins again for the `configure()` phase and again for the `postConfigure()` phases. -The cycle is repeated _in reverse order_ for the `deconfigure()` and eventually the `destroy()` phases. - -===== Extending Container Support by Creating Extra Configurations - -As shown, there is a default set of Configurations that support basic deployment of a webapp. -JavaEE features such as JNDI and advanced servlet spec features such as annotations have not been mentioned. -Jetty's philosophy is to allow the user to tailor the container exactly to their needs. -If these features are not needed, then Jetty does not pay the price for them - an important consideration because features such as annotations require extensive and time-consuming scanning of `WEB-INF/lib` jars. -As modern webapps may have scores of these jars, it can be a source of significant deployment delay. -We will see in the section link:#webapp-context-attributes[Other Configuration] another helpful webapp facility that Jetty provides for cutting down the time spent analyzing jars. - -Jetty makes use of the flexibility of Configurations to make JNDI and annotation support pluggable. - -Firstly, lets look at how Configurations help enable JNDI. - -[[jndi-configuration-classes]] -====== Example: JNDI Configurations - -JNDI lookups within web applications require the container to hookup resources defined in the container's environment to that of the web application. -To achieve that, we use 2 extra Configurations: - -.JNDI Configuration classes -[cols=",",] -|======================================================================= -|link:{JDURL}/org/eclipse/jetty/plus/webapp/EnvConfiguration.html[org.eclipse.jetty.plus.webapp.EnvConfiguration] -|Creates `java:comp/env` for the webapp, applies a `WEB-INF/jetty-env.xml` file - -|link:{JDURL}/org/eclipse/jetty/plus/webapp/PlusConfiguration.html[org.eclipse.jetty.plus.webapp.PlusConfiguration] -|Processes JNDI related aspects of `WEB-INF/web.xml` and hooks up naming entries -|======================================================================= - -These configurations must be added in _exactly_ the order shown above and should be inserted _immediately before_ the link:{JDURL}/org/eclipse/jetty/webapp/JettyWebXmlConfiguration.html[org.eclipse.jetty.webapp.JettyWebXmlConfiguration] class in the list of configurations. -To fully support JNDI additional configuration is required, full details of which can be found link:#jndi[here]. - -====== Example: Annotation Configurations - -We need just one extra Configuration class to help provide servlet annotation scanning: - -.Annotation Configuration classes -[cols=",",] -|======================================================================= -|link:{JDURL}/org/eclipse/jetty/annotations.AnnotationConfiguration.html[org.eclipse.jetty.annotations.AnnotationConfiguration] -|Scan container and web app jars looking for @WebServlet, @WebFilter, -@WebListener etc -|======================================================================= - -The above configuration class must be _inserted immediately before_ the link:{JDURL}/org/eclipse/jetty/webapp/JettyWebXmlConfiguration.html[org.eclipse.jetty.webapp.JettyWebXmlConfiguration] class in the list of configurations. -To fully support annotations additional configuration is require, details of which can be found link:#webapp-context-attributes[below.] - -===== How to Set the List of Configurations - -You have a number of options for how to make Jetty use a different list of Configurations. - -====== Setting the list directly on the WebAppContext - -If you have only one webapp that you wish to affect, this may be the easiest option. -You will, however, either need to have a context xml file that represents your web app, or you need to call the equivalent in code. -Let's see an example of how we would add in the Configurations for both JNDI _and_ annotations: - -[source, xml, subs="{sub-order}"] ----- - - - - - - /webapps/my-cool-webapp - - - - org.eclipse.jetty.webapp.WebInfConfiguration - org.eclipse.jetty.webapp.WebXmlConfiguration - org.eclipse.jetty.webapp.MetaInfConfiguration - org.eclipse.jetty.webapp.FragmentConfiguration - org.eclipse.jetty.plus.webapp.EnvConfiguration - org.eclipse.jetty.plus.webapp.PlusConfiguration - org.eclipse.jetty.annotations.AnnotationConfiguration - org.eclipse.jetty.webapp.JettyWebXmlConfiguration - - - - ----- - -Of course, you can also use this method to reduce the Configurations applied to a specific `WebAppContext`. - -====== Setting the list for all webapps via the Deployer - -If you use the link:#deployment-architecture[deployer], you can set up the list of Configuration classes on the link:#default-web-app-provider[WebAppProvider]. -They will then be applied to each `WebAppContext` deployed by the deployer: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - - - - /webapps - - - org.eclipse.jetty.webapp.WebInfConfiguration - org.eclipse.jetty.webapp.WebXmlConfiguration - org.eclipse.jetty.webapp.MetaInfConfiguration - org.eclipse.jetty.webapp.FragmentConfiguration - org.eclipse.jetty.plus.webapp.EnvConfiguration - org.eclipse.jetty.plus.webapp.PlusConfiguration - org.eclipse.jetty.annotations.AnnotationConfiguration - org.eclipse.jetty.webapp.JettyWebXmlConfiguration - - - - - - - - - ----- - -====== Adding or inserting to an existing list - -Instead of having to enumerate the list in its entirety, you can simply nominate classes that you want to add, and indicate whereabouts in the list you want them inserted. -Let's look at an example of using this method to add in Configuration support for JNDI - as usual you can either do this in an xml file, or via equivalent code. -This example uses an xml file, in fact it is the `$JETTY_HOME/etc/jetty-plus.xml` file from the Jetty distribution: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - org.eclipse.jetty.webapp.FragmentConfiguration - - - org.eclipse.jetty.plus.webapp.EnvConfiguration - org.eclipse.jetty.plus.webapp.PlusConfiguration - - - - - - ----- - -The link:{JDURL}/org/eclipse/jetty/webapp/Configuration.html[org.eclipse.jetty.webapp.Configuration.ClassList] class provides these methods for insertion: - -addAfter:: - Inserts the supplied list of `Configuration` class names after the given Configuration class name. -addBefore:: - Inserts the supplied list of `Configuration` class names before the given Configuration class name. - -[[webapp-context-attributes]] -==== Other Configuration - -[[container-include-jar-pattern]] -===== org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern - -This is a link:#context_attributes[context attribute] that can be set on link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[an org.eclipse.jetty.webapp.WebAppContext] to control which parts of the _container's_ classpath should be processed for things like annotations, `META-INF/resources`, `META-INF/web-fragment.xml` and `tlds` inside `META-INF`. - -Normally, nothing from the container classpath will be included for processing. -However, sometimes you will need to include some. -For example, you may have some libraries that are shared amongst your webapps and thus you have put them into a `$JETTY_HOME/lib` directory. -The libraries contain annotations and therefore must be scanned. - -The value of this attribute is a regexp that defines which _jars_ and _class directories_ from the container's classpath should be examined. - -Here's an example from a context xml file (although as always, you could have accomplished the same in code), which would match any jar whose name starts with "foo-" or "bar-", or a directory named "classes": - -[source, xml, subs="{sub-order}"] ----- - - - - - - - org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern - .*/foo-[^/]*\.jar$|.*/bar-[^/]*\.jar$|.*/classes/.* - - - ----- - -Note that the order of the patterns defines the ordering of the scanning of the jars or class directories. - -[[web-inf-include-jar-pattern]] -===== org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern - -Similarly to the previous link:#context_attributes[context attribute], this attribute controls which jars are processed for things like annotations, `META-INF/resources`, `META-INF/web-fragment.xml` and `tlds` in `META-INF`. -However, this attribute controls which jars from the _webapp's_ classpath (usually `WEB-INF/lib`) are processed. -This can be particularly useful when you have dozens of jars in `WEB-INF/lib`, but you know that only a few need to be scanned. - -Here's an example in a xml file of a pattern that matches any jar that starts with `spring-`: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern - .*/spring-[^/]*\.jar$ - - - ----- - -Note that the order of the patterns defines the ordering of the scanning of jar files. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/quickstart-webapp.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/quickstart-webapp.adoc deleted file mode 100644 index 5eccb6b64e39..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/quickstart-webapp.adoc +++ /dev/null @@ -1,177 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[quickstart-webapp]] -=== Quickstart Webapps - -The auto discovery features of the Servlet specification can make deployments slow and uncertain. -Auto discovery of Web Application configuration can be useful during the development of a webapp as it allows new features and frameworks to be enabled simply by dropping in a jar file. -However, for deployment, the need to scan the contents of many jars can have a significant impact of the start time of a webapp. - -With the release of Jetty 9.2, a quickstart module was included which allows a webapp to be pre-scanned and preconfigured. -This means that all the scanning is done prior to deployment and all configuration is encoded into an effective `web.xml`, called `WEB-INF/quickstart-web.xml`, which can be inspected to understand what will be deployed before deploying. -Not only does the `quickstart-web.xml` contain all the discovered Servlets, Filters and Constraints, but it also encodes as context parameters all discovered: - -* ServletContainerInitializers -* HandlesTypes classes -* Taglib Descriptors - -With the quickstart mechanism, Jetty is able to entirely bypass all scanning and discovery modes and start a webapp in a predictable and fast way. -Tests have shown that webapps that took many seconds to scan and deploy can now be deployed in a few hundred milliseconds. - -==== Setting up Quickstart - -===== Prerequisites - -====== Jetty Distribution - -In a standard Jetty distribution the quickstart module can be configured with the following command: - -[source, screen, subs="{sub-order}"] ----- -$ java -jar $JETTY_HOME/start.jar --add-to-start=quickstart ----- - -====== Embedded - -In a Maven project you add a dependency on the artifact `jetty-quickstart`. - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty - jetty-quickstart - {VERSION} - ----- - - - -===== Configuration - -Webapps need to be instances of link:{JDURL}/org/eclipse/jetty/quickstart/QuickStartWebApp.html[`org.eclipse.jetty.quickstart.QuickStartWebApp`] rather than the normal `org.eclipse.jetty.webapp.WebAppContext`. - -`org.eclipse.jetty.quickstart.QuickStartWebApp` instances offer the same setters as the familiar `org.eclipse.jetty.webapp.WebAppContext`, with the addition of: - -autoPreconfigure:: - (true/false). - If true, the first time the webapp is run, the WEB-INF/quickstart-web.xml is generated BEFORE the webapp is deployed. - Subsequent runs use the previously generated quickstart file. -originAttribute:: - The name of an attribute to insert into the generated elements in quickstart-web.xml that gives the origin of the element. - By default it is `origin`. -generateOrigin:: - (true/false). - By default it is `false`. - If true, the origin attribute will be inserted into each element in quickstart-web.xml. - Note that origin attributes will also be generated if debug log level is enabled. - -____ -[NOTE] -If you are using Spring-Boot you must set `generateOrigin` to true. -____ - -The origin is either a descriptor eg web.xml,web-fragment.xml,override-web.xml file, or an annotation eg @WebServlet. -For xml validation each attribute must be unique, and therefore an integer counter is appended to each value. -Some examples of elements with origin attribute information are: - -[source, xml, subs="{sub-order}"] ----- - - - - ----- - -====== In XML -If a web application already has a context xml file, eg `webapps/myapp.xml` file, simply change the class in the `Configure` element. -Otherwise, create a context xml file with the following information (in addition to the usual setting of contextPath, war etc): - -[source, xml, subs="{sub-order}"] ----- - - - - true - ----- - -====== In Code - -Create an instance of link:{JDURL}/org/eclipse/jetty/quickstart/QuickStartWebApp.html[`org.eclipse.jetty.quickstart.QuickStartWebApp`] rather than the normal `org.eclipse.jetty.webapp.WebAppContext`. You then use the QuickStartWebApp instance in exactly the same way that you would a WebAppContext. - -Here's a snippet: - -[source, java] ----- - QuickStartWebApp webapp = new QuickStartWebApp(); - webapp.setAutoPreconfigure(true); ----- - - -====== Pre-generating the quickstart-web.xml file - -Rather than use the `autoPreconfigure` feature of the QuickStartWebApp - which lazily generates the `quickstart-web.xml` file - you can eagerly pre-generate it for an existing war by invoking as a main class link:{JDURL}/org/eclipse/jetty/quickstart/PreconfigureQuickStartWar.html[`org.eclipse.jetty.quickstart.PreconfigureQuickStartWar`]. -Note that you will need to provide all necessary jetty jars on the command line classpath. -This will unpack the war if necessary, and create the `quickstart-web.xml` before the first deployment: - - -[source, screen, subs="{sub-order}"] ----- -$ java -cp [jetty classpath] org.eclipse.jetty.quickstart.PreconfigureQuickStartWar myapp.war ----- - -Run the class with no arguments to see other runtime options. - -Alternatively, you could use the link:#get-up-and-running[Jetty Maven Plugin] goal link:#jetty-effective-web-xml[`jetty:effective-web-xml`]: this will generate quickstart information, but print it to stderr. -The goal provides a configuration option to save the output to a file, which you can then copy into your webapp's WEB-INF dir. -Note that as the Jetty Maven Plugin is a general tool for running webapps, it may have more jars on its classpath than are needed by your application, and thus may generate extra quickstart information: we recommend that you use this goal only as a quick guide to the type of information that quickstart generates. - -// ==== Preconfiguring the web application -// -// If the `QuickStateWebApp` method `setAutoPreconfigure(true)` is called (see example in myapp.xml above), then the first time the webapp is deployed a `WEB-INF/quickstart-web.xml` file will be generated that contains the effective `web.xml` for all the discovered configuration. -// On subsequent deployments, all the discovery steps are skipped and the `quickstart-web.xml` is used directly to configure the web application. -// -// It is also possible to preconfigure a war file manually by running the class link:{JDURL}/org/eclipse/jetty/quickstart/PreconfigureQuickStartWar.html[org.eclipse.jetty.quickstart.PreconfigureQuickStartWar] with the jetty-all-uber (aggregate) jar: -// -// -// This will create the `quickstart-web.xml` file before the first deployment. - -==== Avoiding TLD Scans with precompiled JSPs - -Of course precompiling JSPs is an excellent way to improve the start time of a web application. -As of Jetty 9.2 the Apache Jasper JSP implementation has been used and has been augmented to allow the TLD scan to be skipped. -This can be done by adding a `context-param` to the `web.xml` file (this is done automatically by the Jetty Maven JSPC plugin): - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty.jsp.precompiled - true - ----- - -==== Bypassing start.jar - -The Jetty `start.jar` mechanism is a very powerful and flexible mechanism for constructing a `classpath` and executing a configuration encoded in Jetty XML format. -However, this mechanism does take some time to build the `classpath`. -The start.jar mechanism can be bypassed by using the `–dry-run` option to generate and reuse a complete command line to start Jetty at a later time: - -[source, screen, subs="{sub-order}"] ----- -$ RUN=$(java -jar $JETTY_HOME/start.jar --dry-run) -$ eval $RUN ----- - -Note that `--dry-run` may create a properties file in the temp directory and include it on the generated command line. -If so, then a copy of the temporary properties file should be taken and the command line updated with it's new persistent location. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/static-content-deployment.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/static-content-deployment.adoc deleted file mode 100644 index 736f136de0dd..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/deploying/static-content-deployment.adoc +++ /dev/null @@ -1,36 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[static-content-deployment]] -=== Configuring Static Content Deployment - -To serve purely static content, the Jetty Deployment Descriptor XML concepts and the internal `ResourceHandler` can be used. -Create a file called `scratch.xml` in the `${jetty.base}/webapps` directory and paste the following file contents in it. - -[source, xml, subs="{sub-order}"] ----- - - - - /scratch - - -   /home/scratch - true - - - ----- - -This is a very basic setup for serving static files. -For advanced static file serving, use the link:{JDURL}/org/eclipse/jetty/servlet/DefaultServlet.html[DefaultServlet]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/chapter.adoc deleted file mode 100644 index 908afffeca55..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/chapter.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[advanced-embedding]] -== Embedding - -include::jetty-helloworld.adoc[] -include::embedding-jetty.adoc[] -include::embedded-examples.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/embedded-examples.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/embedded-examples.adoc deleted file mode 100644 index 900b11edc808..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/embedded-examples.adoc +++ /dev/null @@ -1,81 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[embedded-examples]] -=== Embedded Examples - -Jetty has a rich history of being embedded into a wide variety of applications. -In this section we will walk you through a number of our simple examples under our embedded-jetty-examples project in our git repository. - -____ -[IMPORTANT] -These files are pulled directly from our git repository when this document is generated. -If the line numbers do not line up feel free to fix this documentation in github and give us a pull request, or at least open an issue to notify us of the discrepancy. -____ - -include::examples/embedded-file-server.adoc[] -include::examples/embedded-split-file-server.adoc[] -include::examples/embedded-many-connectors.adoc[] -include::examples/embedded-secured-hello-handler.adoc[] -include::examples/embedded-minimal-servlet.adoc[] -include::examples/embedded-one-webapp.adoc[] - -[[embedded-webapp-jsp]] -==== Web Application with JSP - -This example is very similar to the one in the previous section, although it enables the embedded webapp to use JSPs. -As of jetty-9.2, we use the JSP engine from Apache, which relies on a Servlet Specification 3.1 style `ServletContainerInitializer` to initialize itself. -To get this to work with Jetty, you need to enable annotations processing, as shown in this example code: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneWebAppWithJsp.java[] - ----- - -===== Run it! - -After you have started things up you should be able to navigate to http://localhost:8080/jsp/ and click on any of the links to jsps. - -===== Maven Coordinates - -To use this example in your project, you will need the following Maven dependencies declared, in addition to those from the previous section: - -[source, xml, subs="{sub-order}"] ----- - - - org.eclipse.jetty - jetty-annotations - ${project.version} - - - org.eclipse.jetty - apache-jsp - ${project.version} - - - org.eclipse.jetty - apache-jstl - ${project.version} - ----- - -[[adding-embedded-examples]] -==== Adding Examples - -If you would like to add an example to this list, fork the documentation project from github (see the blue bar at the bottom of this page) and add the new page. -Feel free to add the example contents directly as a `[source.java]` and we will take it from there. - -If you feel and example is missing, feel free to open a bug to ask for it. -No guarantees, but the more helpful and demonstrative it is the better. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/embedding-jetty.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/embedding-jetty.adoc deleted file mode 100644 index 322f7c037cc7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/embedding-jetty.adoc +++ /dev/null @@ -1,242 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[embedding-jetty]] -=== Embedding Jetty - -Jetty has a slogan, "__Don't deploy your application in Jetty, deploy Jetty in your application!__" -What this means is that as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a software component that can be instantiated and used in a Java program just like any POJO. -Put another way, running Jetty in embedded mode means putting an HTTP module into your application, rather than putting your application into an HTTP server. - -This tutorial takes you step-by-step from the simplest Jetty server instantiation to running multiple web applications with standards-based deployment descriptors. -The source for most of these examples is part of the standard Jetty project. - -==== Overview - -To embed a Jetty server the following steps are typical and are illustrated by the examples in this tutorial: - -1. Create a link:{JDURL}/org/eclipse/jetty/server/Server.html[Server] instance. -2. Add/Configure link:{JDURL}/org/eclipse/jetty/server/Connector.html[Connectors]. -3. Add/Configure link:{JDURL}/org/eclipse/jetty/server/Handler.html[Handlers] and/or link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html[Contexts] and/or http://docs.oracle.com/javaee/6/api/javax/servlet/Servlet.html[Servlets]. -4. Start the Server. -5. Wait on the server or do something else with your thread. - -==== Creating the Server - -The following code from SimplestServer.java instantiates and runs the simplest possible Jetty server: - -[source, java] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SimplestServer.java[] ----- - -This runs an HTTP server on port 8080. It is not a very useful server as it has no handlers, and thus returns a 404 error for every request. - -==== Using Handlers - -To produce a response to a request, Jetty requires that you set a link:{JDURL}/org/eclipse/jetty/server/Handler.html[Handler] on the server. -A handler may: - -* Examine/modify the HTTP request. -* Generate the complete HTTP response. -* Call another Handler (see link:{JDURL}/org/eclipse/jetty/server/handler/HandlerWrapper.html[`HandlerWrapper`]). -* Select one or many Handlers to call (see link:{JDURL}/org/eclipse/jetty/server/handler/HandlerCollection.html[`HandlerCollection`]). - -===== HelloWorld Handler - -The following code based on HelloHandler.java shows a simple hello world handler: - -[source, java] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java[] ----- - -The parameters passed to the handle method are: - -* `target` – the target of the request, which is either a URI or a name from a named dispatcher. -* `baseRequest` – the Jetty mutable request object, which is always unwrapped. -* `request` – the immutable request object, which may have been wrapped by a filter or servlet. -* `response` – the response, which may have been wrapped by a filter or servlet. - -The handler sets the response status, content-type, and marks the request as handled before it generates the body of the response using a writer. - -===== Running HelloWorldHandler - -To allow a Handler to handle HTTP requests, you must add it to a Server instance. -The following code from OneHandler.java shows how a Jetty server can use the HelloWorld handler: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneHandler.java[] ----- - -One or more handlers do all request handling in Jetty. -Some handlers select other specific handlers (for example, a `ContextHandlerCollection` uses the context path to select a `ContextHandler`); others use application logic to generate a response (for example, the `ServletHandler` passes the request to an application Servlet), while others do tasks unrelated to generating the response (for example, `RequestLogHandler` or `StatisticsHandler`). - -Later sections describe how you can combine handlers like aspects. -You can see some of the handlers available in Jetty in the link:{JDURL}/org/eclipse/jetty/server/handler/package-summary.html[org.eclipse.jetty.server.handler] package. - -===== Handler Collections and Wrappers - -Complex request handling is typically built from multiple Handlers that you can combine in various ways. -Jetty has several implementations of the link:{JDURL}/org/eclipse/jetty/server/HandlerContainer.html[`HandlerContainer`] interface: - -link:{JDURL}/org/eclipse/jetty/server/handler/HandlerCollection.html[`HandlerCollection`]:: - Holds a collection of other handlers and calls each handler in order. - This is useful for combining statistics and logging handlers with the handler that generates the response. -link:{JDURL}/org/eclipse/jetty/server/handler/HandlerList.html[`HandlerList`]:: - A Handler Collection that calls each handler in turn until either an exception is thrown, the response is committed or the `request.isHandled()` returns true. - You can use it to combine handlers that conditionally handle a request, such as calling multiple contexts until one matches a virtual host. -link:{JDURL}/org/eclipse/jetty/server/handler/HandlerWrapper.html[`HandlerWrapper`]:: - A Handler base class that you can use to daisy chain handlers together in the style of aspect-oriented programming. - For example, a standard web application is implemented by a chain of a context, session, security and servlet handlers. -link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandlerCollection.html[`ContextHandlerCollection`]:: - A specialized `HandlerCollection` that uses the longest prefix of the request URI (the `contextPath`) to select a contained `ContextHandler` to handle the request. - -===== Scoped Handlers - -Much of the standard Servlet container in Jetty is implemented with `HandlerWrappers` that daisy chain handlers together: `ContextHandler` to `SessionHandler` to `SecurityHandler` to `ServletHandler`. -However, because of the nature of the servlet specification, this chaining cannot be a pure nesting of handlers as the outer handlers sometimes need information that the inner handlers process. -For example, when a `ContextHandler` calls some application listeners to inform them of a request entering the context, it must already know which servlet the `ServletHandler` will dispatch the request to so that the `servletPath` method returns the correct value. - -The `HandlerWrapper` is specialized to the link:{JDURL}/org/eclipse/jetty/server/handler/ScopedHandler.html[`ScopedHandler`] abstract class, which supports a daisy chain of scopes. -For example if a `ServletHandler` is nested within a `ContextHandler`, the order and nesting of execution of methods is: - -.... -Server.handle(...) - ContextHandler.doScope(...) - ServletHandler.doScope(...) - ContextHandler.doHandle(...) - ServletHandler.doHandle(...) - SomeServlet.service(...) -.... - -Thus when the `ContextHandler` handles the request, it does so within the scope the `ServletHandler` has established. - -===== Resource Handler - -The link:{JDURL}/org/eclipse/jetty/embedded/FileServer.html[FileServer example] shows how you can use a `ResourceHandler` to serve static content from the current working directory: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServer.java[] ----- - -Notice that a `HandlerList` is used with the `ResourceHandler` and a `DefaultHandler`, so that the `DefaultHandler` generates a good 404 response for any requests that do not match a static resource. - -==== Embedding Connectors - -In the previous examples, the Server instance is passed a port number and it internally creates a default instance of a Connector that listens for requests on that port. -However, often when embedding Jetty it is desirable to explicitly instantiate and configure one or more Connectors for a Server instance. - -===== One Connector - -The following example, link:{JDURL}/org/eclipse/jetty/embedded/OneConnector.html[OneConnector.java], -instantiates, configures, and adds a single HTTP connector instance to the server: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneConnector.java[] ----- - -In this example the connector handles the HTTP protocol, as that is the default for the link:{JDURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`] class. - -===== Many Connectors - -When configuring multiple connectors (for example, HTTP and HTTPS), it may be desirable to share configuration of common parameters for HTTP. -To achieve this you need to explicitly configure the `ServerConnector` class with `ConnectionFactory` instances, and provide them with common HTTP configuration. - -The link:{JDURL}/org/eclipse/jetty/embedded/ManyConnectors.html[ManyConnectors example], configures a server with two `ServerConnector` instances: the http connector has a link:{JDURL}/org/eclipse/jetty/server/HttpConnectionFactory.html[`HTTPConnectionFactory`] instance; the https connector has a `SslConnectionFactory` chained to a `HttpConnectionFactory`. -Both `HttpConnectionFactory` are configured based on the same link:{JDURL}/org/eclipse/jetty/server/HttpConfiguration.html[`HttpConfiguration`] instance, however the HTTPS factory uses a wrapped configuration so that a link:{JDURL}/org/eclipse/jetty/server/SecureRequestCustomizer.html[`SecureRequestCustomizer`] can be added. - -==== Embedding Servlets - -http://en.wikipedia.org/wiki/Java_Servlet[Servlets] are the standard way to provide application logic that handles HTTP requests. -Servlets are similar to a Jetty Handler except that the request object is not mutable and thus cannot be modified. -Servlets are handled in Jetty by a link:{JDURL}/org/eclipse/jetty/embedded/MinimalServlets.html[`ServletHandler`]. -It uses standard path mappings to match a Servlet to a request; sets the requests `servletPath` and `pathInfo`; passes the request to the servlet, possibly via Filters to produce a response. - -The link:{JDURL}/org/eclipse/jetty/embedded/MinimalServlets.html[MinimalServlets example] creates a `ServletHandler` instance and configures a single HelloServlet: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java[] ----- - -==== Embedding Contexts - -A link:{JDURL}/org/eclipse/jetty/embedded/OneContext.html[`ContextHandler`] is a `ScopedHandler` that responds only to requests that have a URI prefix that matches the configured context path. -Requests that match the context path have their path methods updated accordingly and the contexts scope is available, which optionally may include: - -* A `Classloader` that is set as the Thread context `classloader` while request handling is in scope. -* A set of attributes that is available via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[`ServletContext`] API. -* A set of init parameters that is available via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[`ServletContext`] API. -* A base Resource which is used as the document root for static resource requests via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[`ServletContext`] API. -* A set of virtual host names. - -The following link:{JDURL}/org/eclipse/jetty/embedded/OneContext.html[OneContext example] shows a context being established that wraps the link:{JDURL}/org/eclipse/jetty/embedded/HelloHandler.html[HelloHandler]: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneContext.java[] ----- - -When many contexts are present, you can embed a `ContextHandlerCollection` to efficiently examine a request URI to then select the matching `ContextHandler`(s) for the request. -The link:{JDURL}/org/eclipse/jetty/embedded/ManyContexts.html[ManyContexts example] shows how many such contexts you can configure: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyContexts.java[] ----- - -==== Embedding ServletContexts - -A link:{JDURL}/org/eclipse/jetty/servlet/ServletContextHandler.html[`ServletContextHandler`] is a specialization of `ContextHandler` with support for standard sessions and Servlets. -The following link:{JDURL}/org/eclipse/jetty/embedded/OneServletContext.html[OneServletContext example] instantiates a link:{JDURL}/org/eclipse/jetty/servlet/DefaultServlet.html[`DefaultServlet`] to server static content from /tmp/ and a `DumpServlet` that creates a session and dumps basic details about the request: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneServletContext.java[] ----- - -==== Embedding Web Applications - -A link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`] is an extension of a `ServletContextHandler` that uses the http://en.wikipedia.org/wiki/WAR_%28Sun_file_format%29[standard layout] and web.xml to configure the servlets, filters and other features from a web.xml and/or annotations. -The following link:{JDURL}/org/eclipse/jetty/embedded/OneWebApp.html[OneWebApp example] configures the Jetty test webapp. -Web applications can use resources the container provides, and in this case a `LoginService` is needed and also configured: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneWebApp.java[] ----- - -==== Like Jetty XML - -The typical way to configure an instance of the Jetty server is via `jetty.xml` and associated configuration files. -However the Jetty XML configuration format is just a simple rendering of what you can do in code; it is very simple to write embedded code that does precisely what the jetty.xml configuration does. -The link:{GITBROWSEURL}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java[LikeJettyXml example] following renders in code the behavior obtained from the configuration files: - -* link:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty.xml[jetty.xml] -* link:{GITBROWSEURL}/jetty-jmx/src/main/config/etc/jetty-jmx.xml[jetty-jmx.xml] -* link:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-http.xml[jetty-http.xml] -* link:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-https.xml[jetty-https.xml] -* link:{GITBROWSEURL}/jetty-deploy/src/main/config/etc/jetty-deploy.xml[jetty-deploy.xml] -* link:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-stats.xml[jetty-stats.xml] -* link:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-requestlog.xml[jetty-requestlog.xml] -* link:{GITBROWSEURL}/jetty-server/src/main/config/etc/jetty-lowresources.xml[jetty-lowresources.xml] -* link:{GITBROWSEURL}/tests/test-webapps/test-jetty-webapp/src/main/config/demo-base/etc/test-realm.xml[test-realm.xml] - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java[] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-file-server.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-file-server.adoc deleted file mode 100644 index 46bd50a7b3c3..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-file-server.adoc +++ /dev/null @@ -1,44 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[embedded-file-server]] -==== Simple File Server - -This example shows how to create a simple file server in Jetty. -It is perfectly suitable for test cases where you need an actual web server to obtain a file from, it could easily be configured to serve files from a directory under `src/test/resources`. -Note that this does not have any logic for caching of files, either within the server or setting the appropriate headers on the response. -It is simply a few lines that illustrate how easy it is to serve out some files. - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/FileServer.java[] - ----- - -===== Run it! - -After you have started things up you should be able to navigate to http://localhost:8080/index.html (assuming one is in the resource base directory) and you are good to go. - -===== Maven Coordinates - -To use this example in your project you will need the following Maven dependencies declared. - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty - jetty-server - ${project.version} - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-many-connectors.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-many-connectors.adoc deleted file mode 100644 index 87ab53d7fa51..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-many-connectors.adoc +++ /dev/null @@ -1,51 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[embedded-many-connectors]] -==== Multiple Connectors - -This example shows how to configure Jetty to use multiple connectors, specifically so it can process both http and https requests. -Since the meat of this example is the server and connector configuration it only uses a simple HelloHandler but this example should be easily merged with other examples like those deploying servlets or webapps. - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/ManyConnectors.java[] - ----- - -===== Walkthrough - -Start things up! -By using the `server.join()` the server thread will join with the current thread. -See link:http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()[`Thread.join()`] for more details. - -===== Maven Coordinates - -To use this example in your project you will need the following Maven dependencies declared. - -[source, xml, subs="{sub-order}"] ----- - - - org.eclipse.jetty - jetty-server - ${project.version} - - - org.eclipse.jetty - jetty-security - ${project.version} - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-minimal-servlet.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-minimal-servlet.adoc deleted file mode 100644 index 43aa4c5000da..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-minimal-servlet.adoc +++ /dev/null @@ -1,51 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[embedded-minimal-servlet]] -==== Minimal Servlet - -This example shows the bare minimum required for deploying a servlet into Jetty. -Note that this is strictly a servlet, not a servlet in the context of a web application, that example comes later. -This is purely just a servlet deployed and mounted on a context and able to process requests. -This example is excellent for situations where you have a simple servlet that you need to unit test, just mount it on a context and issue requests using your favorite http client library (like our Jetty client found in xref:client-http[]). - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java[] - ----- - -===== Walkthrough - -Start things up! By using the `server.join()` the server thread will join with the current thread. -See link:http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()[`Thread.join()`] for more details. - -It is really simple to create useful servlets for testing behaviors. Sometimes you need a http server to run a unit test against that will return test content and wiring up a servlet like this makes it trivial. - -After you have started things up you should be able to navigate to http://localhost:8080/ and you are good to go. - -===== Maven Coordinates - -To use this example in your project you will need the following Maven dependencies declared. - -[source, xml, subs="{sub-order}"] ----- - - - org.eclipse.jetty - jetty-servlet - ${project.version} - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-one-webapp.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-one-webapp.adoc deleted file mode 100644 index 2f399a7933b0..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-one-webapp.adoc +++ /dev/null @@ -1,45 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[embedded-one-webapp]] -==== Web Application - -This example shows how to deploy a simple webapp with an embedded instance of Jetty. -This is useful when you want to manage the lifecycle of a server programmatically, either within a production application or as a simple way to deploying and debugging a full scale application deployment. -In many ways it is easier then traditional deployment since you control the classpath yourself, making this easy to wire up in a test case in Maven and issue requests using your favorite http client library (like our Jetty client found in xref:client-http[]). - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneWebApp.java[] - ----- - -===== Run it! - -After you have started things up you should be able to navigate to http://localhost:8080/ and you are good to go. - -===== Maven Coordinates - -To use this example in your project you will need the following Maven dependencies declared. - -[source, xml, subs="{sub-order}"] ----- - - - org.eclipse.jetty - jetty-webapp - ${project.version} - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-secured-hello-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-secured-hello-handler.adoc deleted file mode 100644 index 0991f1c40c86..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-secured-hello-handler.adoc +++ /dev/null @@ -1,54 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[embedded-secured-hello-handler]] -==== Secured Hello Handler - -This example shows how to wrap one handler with another one that handles security. -We have a simple Hello Handler that just return a greeting but add on the restriction that to get this greeting you must authenticate. -Another thing to remember is that this example uses the `ConstraintSecurityHandler` which is what supports the security mappings inside of the servlet api, it could be easier to show just the `SecurityHandler` usage, but the constraint provides more configuration power. -If you don't need that you can drop the Constraint bits and use just the `SecurityHandler`. - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java[] - ----- - -===== Run it! - -After you have started things up you should be able to navigate to http://localhost:8080/index.html (assuming one is in the resource base directory) and you are good to go. - -===== The Realm Properties File - -[source,properties] ----- -include::{SRCDIR}/examples/embedded/src/test/resources/realm.properties[] - ----- - -===== Maven Coordinates - -To use this example in your project you will need the following Maven dependencies declared. - -[source, xml, subs="{sub-order}"] ----- - - - org.eclipse.jetty - jetty-server - ${project.version} - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-split-file-server.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-split-file-server.adoc deleted file mode 100644 index 91996509bb41..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/examples/embedded-split-file-server.adoc +++ /dev/null @@ -1,51 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[embedded-split-file-server]] -==== Split File Server - -This example builds on the link:#emebedded-file-server[Simple File Server] to show how chaining multiple `ResourceHandlers` together can let you aggregate multiple directories to serve content on a single path and how you can link these together with `ContextHandlers`. - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SplitFileServer.java[] - - ----- - -===== Run it! - -After you have started things up you should be able to navigate to http://localhost:8090/index.html (assuming one is in the resource base directory) and you are good to go. -Any requests for files will be looked for in the first resource handler, then the second, and so on and so forth. - -===== Maven Coordinates - -To use this example as is in your project you will need the following maven dependencies declared. -We would recommend not using the toolchain dependency in your actual application. - -[source, xml, subs="{sub-order}"] ----- - - - org.eclipse.jetty - jetty-server - ${project.version} - - - org.eclipse.jetty.toolchain - jetty-test-helper - 2.2 - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/jetty-helloworld.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/jetty-helloworld.adoc deleted file mode 100644 index 8e8e0085d582..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/embedding/jetty-helloworld.adoc +++ /dev/null @@ -1,89 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-helloworld]] -=== Jetty Embedded HelloWorld - -This section provides a tutorial that shows how you can quickly develop embedded code against the Jetty API. - -[[downloading-jars]] -==== Downloading the Jars - -Jetty is decomposed into many jars and dependencies to achieve a minimal footprint by selecting the minimal set of jars. -Typically it is best to use something like link:#jetty-maven-helloworld[Maven] to manage jars, however this tutorial uses an aggregate Jar that contains all of the required Jetty classes in one Jar. -You can manually download the aggregate link:https://repo1.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/{VERSION}/jetty-all-{VERSION}-uber.jar[`jetty-all.jar`] using `curl` or a browser. - -____ -[NOTE] -The central Maven repository has started to aggressively reject/deny access to the repository from the `wget` command line tool (due to abusive use of the tool by some groups). -The administrators of the central maven repository have stated that the recommended command line download tool is now curl. -____ - -____ -[IMPORTANT] -The `jetty-all` jar referenced in this section is for example purposes only and should not be used outside of this context. -Please consider using link:#jetty-maven-helloworld[Maven] to manage your project dependencies. -____ - -Use curl as follows: - -[source, screen, subs="{sub-order}"] -.... -> mkdir Demo -> cd Demo -> curl -o jetty-all-uber.jar https://repo1.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/{VERSION}/jetty-all-{VERSION}-uber.jar -.... - -[[writing-helloworld-example]] -==== Writing a HelloWorld Example - -The link:#embedding[Embedding Jetty] section contains many examples of writing against the Jetty API. -This tutorial uses a simple HelloWorld handler with a main method to run the server. -You can either link:{GITBROWSEURL}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloWorld.java[download] or create in an editor the file `HelloWorld.java` with the following content: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/HelloWorld.java[] ----- - -[[compiling-helloworld-example]] -==== Compiling the HelloWord example - -The following command compiles the HelloWorld class: - -[source, screen, subs="{sub-order}"] -.... -> mkdir classes -> javac -d classes -cp jetty-all-uber.jar HelloWorld.java -.... - -[[running-handler-and-server]] -==== Running the Handler and Server - -The following command runs the HelloWorld example: - -[source, screen, subs="{sub-order}"] -.... -> java -cp classes:jetty-all-uber.jar org.eclipse.jetty.demos.HelloWorld -.... - -You can now point your browser at http://localhost:8080/[http://localhost:8080] to see your hello world page. - -[[next-steps]] -==== Next Steps - -To learn more about Jetty, take these next steps: - -* Follow the examples in link:#embedding-jetty[Embedding Jetty] to better understand the jetty APIs. -* Explore the complete link:{JDURL}/[Jetty javadoc] -* Consider using link:#maven-and-jetty[Jetty and Maven] to manage your Jars and dependencies. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/balancer-servlet.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/balancer-servlet.adoc deleted file mode 100644 index 8018048ad556..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/balancer-servlet.adoc +++ /dev/null @@ -1,34 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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..proxyTo:: -One of more of these are required and will be the locations that are used to proxy traffic to. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/cgi-servlet.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/cgi-servlet.adoc deleted file mode 100644 index ae15fbd05e4c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/cgi-servlet.adoc +++ /dev/null @@ -1,39 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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. - -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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/chapter.adoc deleted file mode 100644 index 70296e7fa9bc..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/chapter.adoc +++ /dev/null @@ -1,42 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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::header-filter.adoc[] -include::gzip-filter.adoc[] -include::cross-origin-filter.adoc[] -include::resource-handler.adoc[] -include::debug-handler.adoc[] -include::statistics-handler.adoc[] -include::inetaccess-handler.adoc[] -include::moved-context-handler.adoc[] -include::shutdown-handler.adoc[] -include::default-handler.adoc[] -include::error-handler.adoc[] -include::rewrite-handler.adoc[] - diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/cross-origin-filter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/cross-origin-filter.adoc deleted file mode 100644 index 6fe6a365cbf8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/cross-origin-filter.adoc +++ /dev/null @@ -1,91 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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 https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-servlets/. -It is also available as part of the Jetty distribution in the `$JETTY_HOME/lib` directory. - -[[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, subs="{sub-order}"] ----- - - - - cross-origin - org.eclipse.jetty.servlets.CrossOriginFilter - - - cross-origin - /cometd/* - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/debug-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/debug-handler.adoc deleted file mode 100644 index 5415f021eff1..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/debug-handler.adoc +++ /dev/null @@ -1,63 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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 - -The debug handler can be added to Jetty by activating the `debug` module. - -==== Embedded usage - -[source, java, subs="{sub-order}"] ----- -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(); ----- - -==== 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} ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/default-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/default-handler.adoc deleted file mode 100644 index d9693b3c4dd9..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/default-handler.adoc +++ /dev/null @@ -1,47 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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, subs="{sub-order}"] ----- - 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(); ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/default-servlet.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/default-servlet.adoc deleted file mode 100644 index f29a365e9114..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/default-servlet.adoc +++ /dev/null @@ -1,83 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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 the `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. -welcomeServlets:: -If `true`, attempt to dispatch to welcome files that are servlets, but only after no matching static -resources could be found. If `false`, then a welcome file must exist on disk. If `exact`, then exact -servlet matches are supported without an existing file. Default is `false`. This must be `false` if you want directory listings, -but have index.jsp in your welcome file list. -precompressed:: -If set to a comma separated list of encoding types (that may be listed in a requests Accept-Encoding header) to file extension mappings to look for and serve. -For example: `br=.br,gzip=.gz,bzip2=.bz`. -If set to a boolean `true`, then a default set of compressed formats will be used, otherwise no precompressed formats supported. -gzip:: -Deprecated. Use `precompressed` instead. 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. -resourceCache:: -If set, this is a context attribute name, which the servlet will use to look for a shared ResourceCache instance. -relativeResourceBase:: -Set with a pathname relative to the base of the servlet context root. Useful for only serving static content out of only specific subdirectories. -cacheControl:: -If set, all static content will have this value set as the cache-control header. -pathInfoOnly:: -If `true`, only the path info will be applied to the resourceBase -stylesheet:: -Set with the location of an optional stylesheet that will be used to decorate the directory listing html. -etags:: -If `true`, weak etags will be generated and handled. -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`. -encodingHeaderCacheSize:: -Max entries in a cache of ACCEPT-ENCODING headers diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/dos-filter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/dos-filter.adoc deleted file mode 100644 index 795e752a20f9..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/dos-filter.adoc +++ /dev/null @@ -1,102 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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. - -[[dos-filter-using]] -==== Using the DoS Filter - -Jetty places throttled requests in a queue, and proceed only when there is capacity available. - -===== Required JARs - -To use the DoS Filter, these JAR files must be available in WEB-INF/lib: - -* $JETTY_HOME/lib/jetty-util.jar -* $JETTY_HOME/lib/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, subs="{sub-order}"] ----- - - DoSFilter - org.eclipse.jetty.servlets.DoSFilter - - maxRequestsPerSec - 30 - - ----- - -[[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. -remotePort:: -If true, then rate is tracked by IP and 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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/error-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/error-handler.adoc deleted file mode 100644 index 5bbf22e19a7e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/error-handler.adoc +++ /dev/null @@ -1,29 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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[]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/gzip-filter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/gzip-filter.adoc deleted file mode 100644 index 25dda7ff5972..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/gzip-filter.adoc +++ /dev/null @@ -1,92 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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. -Some user-agents might be excluded from compression to avoid common browser bugs (yes, this means IE!). - -The `GzipHandler` can be added to the entire server by enabling the `gzip.mod` module. -It may also be added to individual contexts in a context xml file. - -____ -[NOTE] -Jetty 9 only compresses using GZip. -Using deflate HTTP compression is not supported and will not function. -____ - -[[gzip-filter-rules]] -==== Gzip Rules - -`GzipHandler` will gzip 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 gzip -* 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 - -Compressing the content can greatly improve the network bandwidth usage, but at the cost of memory and CPU cycles. -The link:#default-servlet[DefaultServlet] is capable of serving pre-compressed static content, which saves memory and CPU. - -The `GzipHandler` installs an output interceptor which passes through to the `DefaultServlet`. -If the content served by `DefaultServlet` is already compressed, the `GzipHandler` does nothing; if it is not compressed, the content is compressed on-the-fly. - -____ -[NOTE] -Automatic precompression by the `DefaultServlet` can be configured. -Read more about the `DefaultServlet` link:#default-servlet[here.] -____ - - -[[gzip-filter-init]] -==== Gzip Configuration - -minGzipSize:: -Content will only be compressed if content length is either unknown or greater than `minGzipSize`. -checkGzExists (Deprecated):: -False by default. -If set to true, the handler will check for pre-compressed content. -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. -Performs a `String.startsWith(String)` comparison to check if the path matches. -If it does match then there is 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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/header-filter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/header-filter.adoc deleted file mode 100644 index 0e4f8113c33b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/header-filter.adoc +++ /dev/null @@ -1,112 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[header-filter]] -=== Header Filter - -[[header-filter-metadata]] -==== Info - -* Classname: `org.eclipse.jetty.servlets.HeaderFilter` -* Maven Artifact: org.eclipse.jetty:jetty-servlets -* Javadoc: {JDURL}/org/eclipse/jetty/servlets/HeaderFilter.html - -[[header-filter-usage]] -==== Usage - -The header filter sets or adds headers to each response based on an optionally included/excluded list of path specs, mime types, and/or HTTP methods. -This filter processes its configured headers before calling `doFilter` in the filter chain. Some of the headers configured in this filter may get overwritten by other filters and/or the servlet processing the request. - -===== Required JARs - -To use the Header Filter, these JAR files must be available in WEB-INF/lib: - -* $JETTY_HOME/lib/jetty-http.jar -* $JETTY_HOME/lib/jetty-servlets.jar -* $JETTY_HOME/lib/jetty-util.jar - -===== Sample Configuration - -Place the configuration in a webapp's `web.xml` or `jetty-web.xml`. -This filter will perform the following actions on each response: - -* Set the X-Frame-Options header to DENY. -* Add a Cache-Control header containing no-cache, no-store, must-revalidate -* Set the Expires header to approximately one year in the future. -* Add a Date header with the current system time. - -____ -[NOTE] -Each action must be separated by a comma. -____ - -[source, xml, subs="{sub-order}"] ----- - - HeaderFilter - org.eclipse.jetty.servlets.HeaderFilter - - headerConfig - - set X-Frame-Options: DENY, - "add Cache-Control: no-cache, no-store, must-revalidate", - setDate Expires: 31540000000, - addDate Date: 0 - - - ----- - -[[header-filter-init]] -===== Configuring Header Filter Parameters - -The following `init` parameters control the behavior of the filter: - -includedPaths:: -Optional. Comma separated values of included path specs. - -excludedPaths:: -Optional. Comma separated values of excluded path specs. - -includedMimeTypes:: -Optional. Comma separated values of included mime types. The mime type will be guessed from the extension at the end of the request URL if the content type has not been set on the response. - -excludedMimeTypes:: -Optional. Comma separated values of excluded mime types. The mime type will be guessed from the extension at the end of the request URL if the content type has not been set on the response. - -includedHttpMethods:: -Optional. Comma separated values of included http methods. - -excludedHttpMethods:: -Optional. Comma separated values of excluded http methods. - -headerConfig:: -Comma separated values of actions to perform on headers. The syntax for each action is `action headerName: headerValue`. - -Supported header actions: - -* `set` - causes set `setHeader` to be called on the response -* `add` - causes set `addHeader` to be called on the response -* `setDate` - causes `setDateHeader` to be called on the response. -* `addDate` - causes `addDateHeader` to be called on the response. - -If `setDate` or `addDate` is used, `headerValue` should be the number of milliseconds to add to the current system time before writing the header value. - -If a property is both included and excluded by the filter configuration, then it will be considered excluded. - -Path spec rules: - -* If the spec starts with `^`, the spec is assumed to be a regex based path spec and will match with normal Java regex rules. -* If the spec starts with `/`, the spec is assumed to be a Servlet url-pattern rules path spec for either an exact match or prefix based match. -* If the spec starts with `*.`, the spec is assumed to be a Servlet url-pattern rules path spec for a suffix based match. -* All other syntaxes are unsupported. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/inetaccess-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/inetaccess-handler.adoc deleted file mode 100644 index 2e0c069de4ef..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/inetaccess-handler.adoc +++ /dev/null @@ -1,32 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[inetaccess-handler]] -=== InetAccess Handler - -[[inetaccess-handler-metadata]] -==== Info - -* Classname: `org.eclipse.jetty.server.handler.InetAccessHandler` -* Maven Artifact: org.eclipse.jetty:jetty-server -* Javadoc: {JDURL}/org/eclipse/jetty/server/handler/InetAccessHandler.html - -[[inetaccess-handler-usage]] -==== Usage - -Controls access to the wrapped handler using the real remote IP. Control is provided by and `IncludeExcludeSet` over a `InetAddressSet`. -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. - -==== Usage in Standard Distribution - -The InetAccess handler can be added to Jetty by activating the `inetaccess` module. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/ipaccess-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/ipaccess-handler.adoc deleted file mode 100644 index cfc923bef05d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/ipaccess-handler.adoc +++ /dev/null @@ -1,69 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/moved-context-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/moved-context-handler.adoc deleted file mode 100644 index c012f5f76ec9..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/moved-context-handler.adoc +++ /dev/null @@ -1,65 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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 xref:configuring-contexts[context xml] file in `{$jetty/.base}/webapps` and configure the `MovedContextHandler` to do the redirection from `/foo` to `/`. - -Below is an example. -This is a permanent redirection, which also preserves `pathinfo` and query strings on the redirect: - -[source, xml, subs="{sub-order}"] ----- - - - - - /foo - / - true - false - false - - - - 209.235.245.73 - 127.0.0.73 - acme.org - www.acme.org - server.acme.org - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/proxy-servlet.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/proxy-servlet.adoc deleted file mode 100644 index 77b86f67943c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/proxy-servlet.adoc +++ /dev/null @@ -1,73 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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 -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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/qos-filter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/qos-filter.adoc deleted file mode 100644 index bc7f41eca73d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/qos-filter.adoc +++ /dev/null @@ -1,157 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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 behavior 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/jetty-util.jar -* $JETTY_HOME/lib/jetty-servlets.jar – contains 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, subs="{sub-order}"] ----- - - QoSFilter - org.eclipse.jetty.servlets.QoSFilter - - maxRequests - 50 - - ----- - -[[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:: -The length 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 `` 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, subs="{sub-order}"] ----- - - QoSFilter - /* - ----- - -===== 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 an example: - -[source, java, subs="{sub-order}"] ----- -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; - } - } ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/resource-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/resource-handler.adoc deleted file mode 100644 index 537aaaeda7bc..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/resource-handler.adoc +++ /dev/null @@ -1,52 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[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 fully featured way of serving static content look to the xref: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, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SplitFileServer.java[] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/rewrite-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/rewrite-handler.adoc deleted file mode 100644 index a18f1a8b8fa7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/rewrite-handler.adoc +++ /dev/null @@ -1,140 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -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: - -[source, screen, subs="{sub-order}"] -.... -$ java -jar start.jar --add-to-start=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, subs="{sub-order}"] ----- -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, subs="{sub-order}"] ----- -include::{SRCDIR}/demos/demo-jetty-webapp/src/main/config/modules/demo.d/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, subs="{sub-order}"] ----- - 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:{JDURL}/org/eclipse/jetty/rewrite/handler/CookiePatternRule.html[CookiePatternRule]:: -Adds a cookie to the response. -link:{JDURL}/org/eclipse/jetty/rewrite/handler/HeaderPatternRule.html[HeaderPatternRule]:: -Adds/modifies a header in the response. -link:{JDURL}/org/eclipse/jetty/rewrite/handler/RedirectPatternRule.html[RedirectPatternRule]:: -Redirects the response. -link:{JDURL}/org/eclipse/jetty/rewrite/handler/ResponsePatternRule.html[ResponsePatternRule]:: -Sends the response code (status or error). -link:{JDURL}/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:{JDURL}/org/eclipse/jetty/rewrite/handler/RedirectRegexRule.html[RedirectRegexRule]:: -Redirect the response. -link:{JDURL}/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 and specific value, or on the presence of a header (with any value). - -link:{JDURL}/org/eclipse/jetty/rewrite/handler/ForwardedSchemeHeaderRule.html[ForwardedSchemaHeaderRule]:: -Set the scheme on the request (defaulting to HTTPS). - -===== Others - -Extra rules that defy standard classification. - -link:{JDURL}/org/eclipse/jetty/rewrite/handler/MsieSslRule.html[MsieSslRule]:: -Disables the keep alive for SSL from IE5 or IE6. -link:{JDURL}/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:{JDURL}/org/eclipse/jetty/rewrite/handler/VirtualHostRuleContainer.html[VirtualHostRuleContainer]:: -Groups rules that apply only to a specific virtual host or a set of virtual hosts diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/shutdown-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/shutdown-handler.adoc deleted file mode 100644 index fbb673faf3df..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/shutdown-handler.adoc +++ /dev/null @@ -1,62 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[shutdown-handler-usage]] -==== Usage - -A handler that shuts the server down on a valid request. -This is used to perform "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 also be added as a part of handler chain or collection. - -[source, java, subs="{sub-order}"] ----- - Server server = new Server(8080); - HandlerList handlers = new HandlerList(); - handlers.setHandlers(new Handler[] - { someOtherHandler, new ShutdownHandler(server,"secret password") }); - server.setHandler(handlers); - server.start(); ----- - -This is an example that you can use to call the shutdown handler from within java. - -[source, java, subs="{sub-order}"] ----- - 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); - } - } ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/statistics-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/statistics-handler.adoc deleted file mode 100644 index 1b5358eb4e85..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/extras/statistics-handler.adoc +++ /dev/null @@ -1,108 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -[[statistics-handler-usage]] -==== Usage - -Jetty currently has two main statistics collection mechanisms: - -* Instances of `ConnectionStatistics` can collect statistics for each connection of a connector. -* The `StatisticsHandler` class may be used to collect statistics for HTTP requests. - -The `StatisticsHandler` and `ConnectionStatistics` are not included in the default Jetty configuration, these need to be configured manually or enabled using the Jetty `stats` module on the command line. -[source, screen, subs="{sub-order}"] -.... -$ java -jar {$jetty.home}/start.jar --add-to-start=stats -.... - -In addition to these, the `SessionHandler` and `DefaultSessionCache` classes collect statistics for sessions. -These statistics are enabled by default and are accessible via JMX interface. - -_____ -[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. -_____ - -[[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. -You can enable the `StatisticsHandler` by activating the `stats` modules on the command line. - -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, subs="{sub-order}"] ----- - - - - - - - ----- - -[[connection-statistics]] -==== Connection Statistics - -Detailed statistics on connection duration and number of messages are only collated when a connection is closed. -The current and maximum number of connections are the only "live" statistics. - -The following example shows how to turn on connection statistics in the Jetty XML format. - -[source, xml, subs="{sub-order}"] ----- - - - - - - - ----- - -A special variant of `ConnectionStatistics` called `IncludeExcludeConnectionStatistics` allows you to refine which types of connection you want to collect statistics for. - -The following example shows how this can be used to record statistics only for WebSocket connections. -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - ----- - -[[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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/chapter.adoc deleted file mode 100644 index 18d455bc6c42..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/chapter.adoc +++ /dev/null @@ -1,18 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[fastcgi]] -== FastCGI Support - -include::fastcgi-intro.adoc[] -include::configuring-fastcgi.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/configuring-fastcgi.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/configuring-fastcgi.adoc deleted file mode 100644 index e30f193c1f9e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/configuring-fastcgi.adoc +++ /dev/null @@ -1,175 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 on 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`: - -[source, screen, subs="{sub-order}"] -.... -$ mkdir -p /usr/jetty/wordpress -$ cd /usr/jetty/wordpress -$ java -jar $JETTY_HOME/start.jar --add-to-start=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. -For FastCGI there is no web application that needs developed - all the work has already been done for you by Jetty. -As such you only need to deploy a Jetty context XML file that configures the web application directly. -Copy and paste the following content as `$JETTY_BASE/webapps/jetty-wordpress.xml`: - -[source, xml, subs="{sub-order}"] ----- - - - - - - /var/www/wordpress - - - / - - - index.php - - - - org.eclipse.jetty.fcgi.server.proxy.TryFilesFilter - /* - - - - - - - files - $path /index.php?p=$path - - - - - - - default - - - org.eclipse.jetty.servlet.DefaultServlet - - - - dirAllowed - false - - - - / - - - - org.eclipse.jetty.fcgi.server.proxy.FastCGIProxyServlet - *.php - - proxyTo - http://localhost:9000 - - - prefix - / - - - scriptRoot - - - - scriptPattern - (.+?\\.php) - - - - - ----- - -An explanation of the above contents: - -* Linne 6 specifies the WordPress installation directory, in this example `/var/www/wordpress` (as defined in the first step). -* Line 9 it is specified the context path at which WordPress will be served, in this example at the root context path `/`. -* Line 10 specifies 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. -* Line 12 specifies the welcome file as `index.php`, so that Jetty can perform the proper redirects in case of URIs ending with the `/` character. -* Line 15 specifies 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. -* Line 29specifies 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). -* Line 47 specifies the `FastCGIProxyServlet`, a Servlet that proxies HTTP requests arriving from clients to FastCGI requests to the FastCGI server. -* Line 52 specifies the TCP address of the FastCGI server (`php-fpm`), where HTTP requests are forwarded as FastCGI requests. -* Line 60 specifies once again the WordPress installation directory, so that the `FastCGIProxyServlet` can pass this information to the FastCGI server. -* Line 64 specifies 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 navigate to `http://localhost:8080` with your browser and enjoy WordPress: - -[source, screen, subs="{sub-order}"] -.... -$ 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 easy; in additions to the modules you have enabled above, add the `http2` module: - -[source, screen, subs="{sub-order}"] -.... -$ 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: - -[source, screen, subs="{sub-order}"] -.... -$ 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 HTTP/1.1. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/fastcgi-intro.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/fastcgi-intro.adoc deleted file mode 100644 index a32593bb8fd5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/fastcgi/fastcgi-intro.adoc +++ /dev/null @@ -1,31 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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], 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 not only 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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/cdi.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/cdi.adoc deleted file mode 100644 index 869796376960..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/cdi.adoc +++ /dev/null @@ -1,114 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[framework-cdi]] -=== CDI - -Contexts and Dependency Injection for Java EE (http://www.cdi-spec.org/[CDI]) is a standard implemented by frameworks such as http://seamframework.org/Weld[Weld] and https://openwebbeans.apache.org/[Apache OpenWebBeans]. -This is a common way to assemble and configure webapplications by a process often referred to as 'decoration'. - -Jetty integration of CDI frameworks allows CDI to be used to inject the Filters, Servlets and Listeners created within a Servlet Context. -There are two approaches to integration: - - * CDI implementation can integrate with Jetty. - This requires the CDI implementation to have Jetty specific code. - Since Jetty-9.4.20 a loosely bound mechanism has been available for CDI implementations to extends the Jetty `DecoratedObjectFactory` without hard API dependencies. - Prior to that, CDI implementations directly called jetty APIs that need to be explicitly exposed to the webapp. - - * Alternately, Jetty can integrate with CDI implementations by using standard CDI SPIs. - -==== Jetty CDI Modules - -The Jetty distribution come with several CDI modules. -These modules do not provide CDI, but instead enable one of more integration mechanisms. - -===== Jetty `cdi` Module -The `cdi` module supports either two modes of CDI integration which can be selected either by the "org.eclipse.jetty.cdi" context init parameter or the "org.eclipse.jetty.cdi" server attribute (which is initialised from the "jetty.cdi.mode" start property). -Supported modes are: - - * `CdiSpiDecorator` Jetty will call the CDI SPI within the webapp to decorate objects (default). - - * `CdiDecoratingLister` The webapp may register a decorator on the context attribute "org.eclipse.jetty.cdi.decorator". -------------------------- -cd $JETTY_BASE -java -jar $JETTY_HOME/start.jar --add-to-start=cdi -------------------------- - -===== Jetty `cdi-decorate` Module -This module depends on the `cdi` module and sets the default mode to `CdiDecoratingListener`. -This is the preferred mode for Weld integration. -------------------------- -cd $JETTY_BASE -java -jar $JETTY_HOME/start.jar --add-to-start=cdi-decorate -------------------------- - -===== Jetty `cdi-spi` Module -This module depends on the `cdi` module and sets the default mode to `CdiSpiDecorator`. -This is the preferred mode for Open Web Beans integration. -------------------------- -cd $JETTY_BASE -java -jar $JETTY_HOME/start.jar --add-to-start=cdi-spi -------------------------- - -===== Jetty `cdi2` Module -This module supports the *deprecated* technique of exposing private Jetty decorate APIs to the CDI implementation in the webapp. - -------------------------- -cd $JETTY_BASE -java -jar $JETTY_HOME/start.jar --add-to-start=cdi2 -------------------------- - -This module is equivalent to directly modifying the class path configuration with a `jetty-web.xml` like: - -[source.XML, xml] -------------------------------------------------------------- - - - - - -org.eclipse.jetty.util.Decorator - - - -org.eclipse.jetty.util.DecoratedObjectFactory - - - -org.eclipse.jetty.server.handler.ContextHandler. - - - -org.eclipse.jetty.server.handler.ContextHandler - - - -org.eclipse.jetty.servlet.ServletContextHandler - - -------------------------------------------------------------- - -____ -[TIP] -The `cdi2` module or directly modifying the web application classpath will not work for Jetty 10.0.0 and later. -It should only be used for versions prior to Jetty 9.4.20 and/or Weld 3.1.2.Final -____ - - -[[cdi-embedded]] -==== Embedded Jetty with CDI -When starting embedded Jetty programmatically from the `main` method, to use CDI it may be -necessary: - - * enable a Jetty CDI integration mode - - * and/or enable a CDI frame integration. - -However, depending on the exact configuration of the embedded server, either or both steps may not be required as `ServletContainerInitializer`s may be discovered. - -The details for embedding CDI is explained in the link:#weld-embedded[Embedded Jetty with Weld] section, which can also be adapted to other CDI frameworks. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/chapter.adoc deleted file mode 100644 index 302d9ee00e5a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/chapter.adoc +++ /dev/null @@ -1,20 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[frameworks]] -== Frameworks - -include::cdi.adoc[] -include::weld.adoc[] -include::osgi.adoc[] -include::metro.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/metro.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/metro.adoc deleted file mode 100644 index ed2d3c6bf42e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/metro.adoc +++ /dev/null @@ -1,57 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[framework-metro]] -=== Metro - -https://metro.java.net/[Metro] is the reference implementation for http://jcp.org/en/jsr/detail?id=109[web services]. -You can easily use Metro with Jetty to integrate web services with your web applications. - -[[metro-setup-distro]] -==== Metro Setup - -1. https://metro.java.net/latest/download.html[Download] the Metro distribution and unpack it to your disk. -We'll refer to the unpacked location as `$metro.home`. -2. Create the directory `$jetty.home/lib/metro` -3. Copy the jars from $metro.home/lib to `$jetty.home/lib/metro` -4. Edit the start.ini file and add an OPTION line for metro near the end. -+ -[source, plain, subs="{sub-order}"] ----- -OPTIONS=metro ----- - -That's all the setup you need to do to integrate Jetty and Metro. - -Now read the https://metro.java.net/discover/[Metro documentation] on https://metro.java.net/getting-started/[how to create web services]. -The Metro distribution you downloaded should also contain several example web applications in the $metro.home/samples directory that you can build and deploy to Jetty (simply by copying the war file produced by the build). - -Here's an example of the log output from Jetty when one of the sample Metro wars (from `$metro.home/samples/async`) is deployed to Jetty: - -[source, screen, subs="{sub-order}"] -.... -[2093] java -jar start.jar - -2013-07-26 15:47:53.480:INFO:oejs.Server:main: jetty-9.0.4.v20130625 -2013-07-26 15:47:53.549:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/user/jetty-home-{VERSION}/webapps/] at interval 1 -Jul 26, 2013 3:47:53 PM com.sun.xml.ws.transport.http.servlet.WSServletContextListener contextInitialized -INFO: WSSERVLET12: JAX-WS context listener initializing -Jul 26, 2013 3:47:56 PM com.sun.xml.ws.server.MonitorBase createRoot -INFO: Metro monitoring rootname successfully set to: com.sun.metro:pp=/,type=WSEndpoint,name=/metro-async-AddNumbersService-AddNumbersImplPort -Jul 26, 2013 3:47:56 PM com.sun.xml.ws.transport.http.servlet.WSServletDelegate -INFO: WSSERVLET14: JAX-WS servlet initializing -2013-07-26 15:47:56.800:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@75707c77{/metro-async,file:/tmp/jetty-0.0.0.0-8080-metro-async.war-_metro-async-any-/webapp/,AVAILABLE}{/metro-async.war} -2013-07-26 15:47:56.853:INFO:oejs.ServerConnector:main: Started ServerConnector@47dce809{HTTP/1.1}{0.0.0.0:8080} - - -.... diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/osgi.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/osgi.adoc deleted file mode 100644 index 9faf168ddf41..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/frameworks/osgi.adoc +++ /dev/null @@ -1,1157 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[framework-jetty-osgi]] -=== OSGI - -==== Introduction - -The Jetty OSGi infrastructure provides a Jetty container inside an OSGi container. -Traditional JavaEE webapps can be deployed, in addition to Jetty `ContextHandlers`, along with OSGi web bundles. -In addition, the infrastructure also supports the OSGi `HttpService` interface. - -==== General Setup - -All of the Jetty jars contain manifest entries appropriate to ensure that they can be deployed into an OSGi container as bundles. -You will need to install some jetty jars into your OSGi container. -You can always find the Jetty jars either in the Maven Central repository, or you can link:https://jetty.org/download.html[download] a distribution of Jetty. -Here's the absolute minimal set of Jetty jars: - -.Minimal Bundles -[cols=",",options="header",] -|=================================================== -|Jar |Bundle Symbolic Name -|jetty-util |org.eclipse.jetty.util -|jetty-http |org.eclipse.jetty.http -|jetty-io |org.eclipse.jetty.io -|jetty-security |org.eclipse.jetty.security -|jetty-server |org.eclipse.jetty.server -|jetty-servlet |org.eclipse.jetty.servlet -|jetty-webapp |org.eclipse.jetty.webapp -|jetty-deploy |org.eclipse.jetty.deploy -|jetty-xml |org.eclipse.jetty.xml -|jetty-servlet-api |org.eclipse.jetty.servlet-api -|=================================================== - -You *must also install the Apache Aries SPI Fly bundles* as many parts of Jetty - for example ALPN, websocket, annotations - use the `ServiceLoader` mechanism, which requires an OSGi Service Loader Mediator like SPI Fly: - -[[spifly]] -.SPI Fly Bundles -[cols=",,",options="header",] -|======================================================================= -|Jar |Bundle Symbolic Name |Location -|org.apache.aries.spifly:org.apache.aries.spifly.dynamic.bundle-1.2.4.jar |org.apache.aries.spifly.dynamic.bundle -|https://repo1.maven.org/maven2/org/apache/aries/spifly/org.apache.aries.spifly.dynamic.bundle/[Maven central] -|======================================================================= - -____ -[NOTE] -We strongly recommend that you also deploy the link:#osgi-annotations[annotation-related] jars also, as the Servlet Specification increasingly relies on annotations for functionality. -____ - -You will also need the **OSGi Event Management service** and the **OSGi Configuration Management service**. -If your OSGi container does not automatically make these available, you will need to add them in a way appropriate to your container. - -==== The Jetty OSGi Container - -===== The jetty-osgi-boot jar - -Now that you have the basic set of Jetty jars installed, you can install the https://repo1.maven.org/maven2/org/eclipse/jetty/osgi/jetty-osgi-boot/[jetty-osgi-boot.jar] bundle, downloadable from the maven central repo https://repo1.maven.org/maven2/org/eclipse/jetty/osgi/jetty-osgi-boot/[here.] - -This bundle will instantiate and make available the Jetty OSGi container when it is started. -If this bundle is not auto-started upon installation into your OSGi container, you should start it manually using a command appropriate for your container. - -[[customize-jetty-container]] -===== Customizing the Jetty Container - -Before going ahead with the install, you may want to customize the Jetty container. -In general this is done by a combination of System properties and the usual Jetty xml configuration files. -The way you define the System properties will depend on which OSGi container you are using, so ensure that you are familiar with how to set them for your environment. -In the following examples, we will assume that the OSGi container allows us to set System properties as simple `name=value` pairs. - -The available System properties are: - -jetty.http.port:: -If not specified, this defaults to the usual jetty port of 8080. -jetty.home:: -Either this property _or_ the *jetty.home.bundle* _must_ be specified. -This property should point to a file system location that has an `etc/` directory containing xml files to configure the Jetty container on startup. -For example: -+ -[source, plain, subs="{sub-order}"] ----- -jetty.home=/opt/custom/jetty - ----- - -+ -Where `/opt/custom/jetty` contains: -+ -[source, plain, subs="{sub-order}"] ----- - -etc/jetty.xml -etc/jetty-selector.xml -etc/jetty-deployer.xml -etc/jetty-special.xml ----- - -jetty.home.bundle:: -Either this property _or_ the *jetty.home* property must be specified. -This property should specify the symbolic name of a bundle which contains a directory called `jettyhome/`. -The `jettyhome/` directory should have a subdirectory called `etc/` that contains the xml files to be applied to Jetty on startup. -The jetty-osgi-boot.jar contains a `jettyhome/` directory with a default set of xml configuration files. -Here's how you would specify it: -+ -[source, plain, subs="{sub-order}"] ----- -jetty.home.bundle=org.eclipse.jetty.osgi.boot ----- - -+ -Here's a partial listing of that jar that shows you the names of the xml files contained within it: -+ -[source, plain, subs="{sub-order}"] ----- -META-INF/MANIFEST.MF -jettyhome/etc/jetty.xml -jettyhome/etc/jetty-deployer.xml -jettyhome/etc/jetty-http.xml ----- - -jetty.etc.config.urls:: -This specifies the paths of the xml files that are to be used. -If not specified, they default to: -+ -[source, plain, subs="{sub-order}"] ----- -etc/jetty.xml,etc/jetty-http.xml,etc/jetty-deployer.xml ----- - -+ -Note that the paths can either be relative or absolute, or a mixture. -If the path is relative, it is resolved against either *jetty.home* or **jetty.home.bundle**, whichever was specified. -You can use this ability to mix and match jetty configuration files to add functionality, such as adding in a https connector. -Here's an example of adding a HTTPS connector, using the relevant files from the jetty-home: -+ -.... -etc/jetty.xml, etc/jetty-http.xml, /opt/jetty/etc/jetty-ssl.xml, /opt/jetty/etc/jetty-https.xml, etc/jetty-deployer.xml -.... -+ - -Note that regardless of whether you set the *jetty.home* or *jetty.home.bundle* property, when Jetty executes the configuration files, it will set an appropriate value for *jetty.home* so that references in xml files to `` will work. -Be careful, however, if you are mixing and matching relative and absolute configuration file paths: the value of *jetty.home* is determined from the resolved location of the _relative_ files only. - -===== The Jetty Container as an OSGi Service - -You can now go ahead and deploy the jetty-osgi-boot.jar into your OSGi container. -A Jetty server instance will be created, the xml config files applied to it, and then published as an OSGi service. -Normally, you will not need to interact with this service instance, however you can retrieve a reference to it using the usual OSGi API: - -[source, java, subs="{sub-order}"] ----- -org.osgi.framework.BundleContext bc; -org.osgi.framework.ServiceReference ref = bc.getServiceReference("org.eclipse.jetty.server.Server"); ----- - -The Server service has a couple of properties associated with it that you can retrieve using the `org.osgi.framework.ServiceReference.getProperty(String)` method: - -managedServerName:: -The Jetty Server instance created by the jetty-osgi-boot.jar will be called "defaultJettyServer" -jetty.etc.config.urls:: -The list of xml files resolved from either *jetty.home* or **jetty.home.bundle**/jettyhome - -===== Adding More Jetty Servers - -As we have seen in the previous section, the jetty-osgi-boot code will create an `org.eclipse.jetty.server.Server` instance, apply the xml configuration files specified by *jetty.etc.config.urls* System property to it, and then register it as an OSGi Service. -The name associated with this default instance is `defaultJettyServer`. - -You can create other Server instances, register them as OSGi Services, and the jetty-osgi-boot code will notice them, and configure them so that they can deploy `ContextHandlers` and webapp bundles. -When you deploy webapps or `ContextHandlers` as bundles or Services (see sections below) you can target them to be deployed to a particular server instance via -the Server's name. - -Here's an example of how to create a new Server instance and register it with OSGi so that the jetty-osgi-boot code will find it and configure it so it can be a deployment target: - -[source, java, subs="{sub-order}"] ----- -public class Activator implements BundleActivator -{ - - public void start(BundleContext context) throws Exception - { - - Server server = new Server(); - //do any setup on Server in here - String serverName = "fooServer"; - Dictionary serverProps = new Hashtable(); - //define the unique name of the server instance - serverProps.put("managedServerName", serverName); - serverProps.put("jetty.http.port", "9999"); - //let Jetty apply some configuration files to the Server instance - serverProps.put("jetty.etc.config.urls", "file:/opt/jetty/etc/jetty.xml,file:/opt/jetty/etc/jetty-selector.xml,file:/opt/jetty/etc/jetty-deployer.xml"); - //register as an OSGi Service for Jetty to find - context.registerService(Server.class.getName(), server, serverProps); - - } -} ----- - -Now that we have created a new Server called "fooServer", we can deploy webapps and `ContextHandlers` as Bundles or Services to it (see below for more information on this). Here's an example of deploying a webapp as a Service and targeting it to the "fooServer" Server we created above: - -[source, java, subs="{sub-order}"] ----- -public class Activator implements BundleActivator -{ - - public void start(BundleContext context) throws Exception - { - - //Create a webapp context as a Service and target it at the "fooServer" Server instance - WebAppContext webapp = new WebAppContext(); - Dictionary props = new Hashtable(); - props.put("war","."); - props.put("contextPath","/acme"); - props.put("managedServerName", "fooServer"); - context.registerService(ContextHandler.class.getName(),webapp,props); - } -} ----- - -==== Deploying Bundles as Webapps - -The Jetty OSGi container listens for the installation of bundles, and will automatically attempt to deploy any that appear to be webapps. - -Any of the following criteria are sufficient for Jetty to deploy the bundle as a webapp: - -Bundle contains a WEB-INF/web.xml file:: -If the bundle contains a web descriptor, then it is automatically deployed. -This is an easy way to deploy classic JavaEE webapps. -Bundle MANIFEST contains Jetty-WarFolderPath (for releases prior tojetty-9.3) or Jetty-WarResourcePath:: -This is the location within the bundle of the webapp resources. -Typically this would be used if the bundle is not a pure webapp, but rather the webapp is a component of the bundle. -Here's an example of a bundle where the resources of the webapp are not located at the root of the bundle, but rather inside the subdirectory `web/` : -+ -`MANIFEST`: -+ -[source, plain, subs="{sub-order}"] ----- -Bundle-Name: Web -Jetty-WarResourcePath: web -Import-Package: javax.servlet;version="3.1", - javax.servlet.resources;version="3.1" -Bundle-SymbolicName: com.acme.sample.web ----- - -+ -Bundle contents: -+ -[source, plain, subs="{sub-order}"] ----- -META-INF/MANIFEST.MF -web/index.html -web/foo.html -web/WEB-INF/web.xml -com/acme/sample/web/MyStuff.class -com/acme/sample/web/MyOtherStuff.class ----- -Bundle MANIFEST contains Web-ContextPath:: -This header can be used in conjunction with either of the two preceding headers to control the context path to which the webapp is deployed, or alone to identify that the bundle's contents should be published as a webapp. -This header is part of the RFC-66 specification for using webapps with OSGi. -Here's an example based on the previous one where we use the `Web-ContextPath` header to set its deployment context path to be "/sample" : - -+ -`MANIFEST`: -+ -[source, plain, subs="{sub-order}"] ----- -Bundle-Name: Web -Jetty-WarResourcePath: web -Web-ContextPath: /sample -Import-Package: javax.servlet;version="3.1", - javax.servlet.resources;version="3.1" -Bundle-SymbolicName: com.acme.sample.web ----- - -You can also define extra headers in your bundle MANIFEST that help -customize the web app to be deployed: - -Jetty-defaultWebXmlFilePath:: -The location of a `webdefault.xml` file to apply to the webapp. -The location can be either absolute (either absolute path or file: url), or relative (in which case it is interpreted as relative to the bundle root). -Defaults to the `webdefault.xml` file built into the Jetty OSGi container. -Jetty-WebXmlFilePath:: -The location of the `web.xml` file. -The location can be either absolute (either absolute path or file: url), or relative (in which case it is interpreted as relative to the bundle root). -Defaults to `WEB-INF/web.xml` -Jetty-extraClassPath:: -A classpath of additional items to add to the webapp's classloader. -Jetty-bundleInstall:: -The path to the base folder that overrides the computed bundle installation - mostly useful for those OSGi frameworks that unpack bundles by default. -Require-TldBundle:: -A comma separated list of bundle symbolic names of bundles containing TLDs that this webapp depends upon. -managedServerName:: -The name of the Server instance to which to deploy this webapp bundle. -If not specified, defaults to the default Server instance called "defaultJettyServer". -Jetty-WarFragmentResourcePath:: -The path within a fragment hosted by the web-bundle that contains static resources for the webapp. -The path is appended to the base resource for the webapp (see Jetty-WarResourcePath). -Jetty-WarPrependFragmentResourcePath:: -The path within a fragment hosted by the web-bundle that contains static resources for the webapp. -The path is prepended to the base resource for the webapp (see Jetty-WarResourcePath). -Jetty-ContextFilePath:: -A comma separated list of paths within the webapp bundle to Jetty context files that will be applied to the webapp. -Alternatively you may include a single Jetty context file called `jetty-webapp-context.xml` in the webapp bundle's META-INF directory and it will be automatically applied to the webapp. - -===== Determining the Context Path for a Webapp Bundle - -As we have seen in the previous section, if the bundle `MANIFEST` contains the RFC-66 header **Web-ContextPath**, Jetty will use that as the context path. -If the `MANIFEST` does not contain that header, then Jetty will concoct a context path based on the last element of the bundle's location (by calling `Bundle.getLocation()`) after stripping off any file extensions. - -For example, suppose we have a bundle whose location is: - -[source, plain, subs="{sub-order}"] ----- -file://some/where/over/the/rainbow/oz.war ----- - -The corresponding synthesized context path would be: - -[source, plain, subs="{sub-order}"] ----- -/oz ----- - -===== Extra Properties Available for Webapp Bundles - -You can further customize your webapp by including a Jetty context xml file that is applied to the webapp. -This xml file must be placed in `META-INF` of the bundle, and must be called `jetty-webapp-context.xml`. - -Here's an example of a webapp bundle listing containing such a file: - -[source, plain, subs="{sub-order}"] ----- -META-INF/MANIFEST.MF -META-INF/jetty-webapp-context.xml -web/index.html -web/foo.html -web/WEB-INF/web.xml -com/acme/sample/web/MyStuff.class -com/acme/sample/web/MyOtherStuff.class ----- - -Here's an example of the contents of a `META-INF/jetty-webapp-context.xml` file: - -[source, xml, subs="{sub-order}"] ----- - - - - - - META-INF/webdefault.xml - ----- - -As you can see, it is a normal context xml file used to set up a webapp. -There are, however, some additional useful properties that can be referenced - -Server:: -This is a reference to the Jetty `org.eclipse.jetty.server.Server` instance to which the webapp being configured in the context xml file will be deployed. -bundle.root:: -This is a reference to the `org.eclipse.jetty.util.resource.Resource` that represents the location of the Bundle. -Note that this could be either a directory in the file system if the OSGi container automatically unpacks bundles, or it may be a jar:file: url if the bundle remains packed. - -==== Deploying Bundles as Jetty ContextHandlers - -In addition to deploying webapps, the Jetty OSGi container listens for the installation of bundles that are not heavyweight webapps, but rather use the flexible Jetty-specific concept of `ContextHandlers`. - -The following is the criteria used to decide if a bundle can be deployed as a `ContextHandler`: - -Bundle MANIFEST contains Jetty-ContextFilePath:: -A comma separated list of names of context files - each one of which represents a ContextHandler that should be deployed by Jetty. -The context files can be inside the bundle, external to the bundle somewhere on the file system, or external to the bundle in the *jetty.home* directory. -+ -A context file that is inside the bundle: -+ -[source, plain, subs="{sub-order}"] ----- -Jetty-ContextFilePath: ./a/b/c/d/foo.xml ----- -+ -A context file that is on the file system: -+ -[source, plain, subs="{sub-order}"] ----- -Jetty-ContextFilePath: /opt/app/contexts/foo.xml ----- -+ -A context file that is relative to jetty.home: -+ -[source, plain, subs="{sub-order}"] ----- -Jetty-ContextFilePath: contexts/foo.xml ----- -+ -A number of different context files: -+ -[source, plain, subs="{sub-order}"] ----- -Jetty-ContextFilePath: ./a/b/c/d/foo.xml,/opt/app/contexts/foo.xml,contexts/foo.xml ----- - -Other `MANIFEST` properties that can be used to configure the deployment of the `ContextHandler`: - -managedServerName:: -The name of the Server instance to which to deploy this webapp bundle. -If not specified, defaults to the default Server instance called "defaultJettyServer". - -===== Determining the Context Path for a ContextHandler Bundle - -Usually, the context path for the ContextHandler will be set by the context xml file. -However, you can override any path set in the context xml file by using the *Web-ContextPath* header in the `MANIFEST`. - -===== Extra Properties Available for Context Xml Files - -Before the Jetty OSGi container applies a context xml file found in a *Jetty-ContextFilePath* `MANIFEST` header, it sets a few useful propertiesthat can be referred to within the xml file: - -Server:: -This is a reference to the Jetty `org.eclipse.jetty.server.Server` instance to which the `ContextHandler` being configured in the context xml file will be deployed. -bundle.root:: -This is a reference to the `org.eclipse.jetty.util.resource.Resource` that represents the location of the Bundle (obtained by calling `Bundle.getLocation()`). -Note that this could be either a directory in the file system if the OSGi container automatically unpacks bundles, or it may be a jar:file: url if the bundle remains packed. - -Here's an example of a context xml file that makes use of these properties: - -[source, xml, subs="{sub-order}"] ----- -include::{SRCDIR}/jetty-osgi/test-jetty-osgi-context/src/main/context/acme.xml[] ----- - -[[services-as-webapps]] -==== Deploying Services as Webapps - -In addition to listening for bundles whose format or `MANIFEST` entries define a webapp or `ContextHandler` for to be deployed, the Jetty OSGi container also listens for the registration of OSGi services that are instances of `org.eclipse.jetty.webapp.WebAppContext`. -So you may programmatically create a `WebAppContext`, register it as a service, and have Jetty pick it up and deploy it. - -Here's an example of doing that with a simple bundle that serves static content, and an `org.osgi.framework.BundleActivator` that instantiates the `WebAppContext`: - -The bundle contents: - -[source, plain, subs="{sub-order}"] ----- -META-INF/MANIFEST.MF -index.html -com/acme/osgi/Activator.class ----- - -The `MANIFEST.MF`: - -[source, plain, subs="{sub-order}"] ----- -Bundle-Classpath: . -Bundle-Name: Jetty OSGi Test WebApp -DynamicImport-Package: org.eclipse.jetty.*;version="[9.0,10.0)" -Bundle-Activator: com.acme.osgi.Activator -Import-Package: org.eclipse.jetty.server.handler;version="[9.0,10)", - org.eclipse.jetty.webapp;version="[9.0,10)", - org.osgi.framework;version= "[1.5,2)", - org.osgi.service.cm;version="1.2.0", - org.osgi.service.packag eadmin;version="[1.2,2)", - org.osgi.service.startlevel;version="1.0.0", - org.osgi.service.url;version="1.0.0", - org.osgi.util.tracker;version= "1.3.0", - org.xml.sax,org.xml.sax.helpers -Bundle-SymbolicName: com.acme.testwebapp ----- - -The Activator code: - -[source, java, subs="{sub-order}"] ----- -public void start(BundleContext context) throws Exception -{ - WebAppContext webapp = new WebAppContext(); - Dictionary props = new Hashtable(); - props.put("Jetty-WarResourcePath","."); - props.put("contextPath","/acme"); - context.registerService(WebAppContext.class.getName(),webapp,props); -} ----- - -The above setup is sufficient for Jetty to recognize and deploy the `WebAppContext` at /acme. - -As the example shows, you can use OSGi Service properties in order to communicate extra configuration information to Jetty: - -Jetty-WarFolderPath (for releases prior to 9.3) or Jetty-WarResourcePath:: -The location within the bundle of the root of the static resources for the webapp -Web-ContextPath:: -The context path at which to deploy the webapp. -Jetty-defaultWebXmlFilePath:: -The location within the bundle of a `webdefault.xml` file to apply to the webapp. -Defaults to that of the Jetty OSGi container. -Jetty-WebXmlFilePath:: -The location within the bundle of the `web.xml` file. -Defaults to `WEB-INF/web.xml` -Jetty-extraClassPath:: -A classpath of additional items to add to the webapp's classloader. -Jetty-bundleInstall:: -The path to the base folder that overrides the computed bundle installation - mostly useful for those OSGi frameworks that unpack bundles by default. -Require-TldBundle:: -A comma separated list of bundle symbolic names of bundles containing TLDs that this webapp depends upon. -managedServerName:: -The name of the Server instance to which to deploy this webapp. -If not specified, defaults to the default Server instance called "defaultJettyServer". -Jetty-WarFragmentResourcePath:: -The path within a fragment hosted by the web-bundle that contains static resources for the webapp. -The path is appended to the base resource for the webapp (see Jetty-WarResourcePath). -Jetty-WarPrependFragmentResourcePath:: -The path within a fragment hosted by the web-bundle that contains static resources for the webapp. -The path is prepended to the base resource for the webapp (see Jetty-WarResourcePath). - -==== Deploying Services as ContextHandlers - -Similarly to WebApp`Contexts, the Jetty OSGi container can detect the registration of an OSGi Service that represents a `ContextHandler` and ensure that it is deployed. -The `ContextHandler` can either be fully configured before it is registered as an OSGi service - in which case the Jetty OSGi container will merely deploy it - or the `ContextHandler` can be partially configured, with the Jetty OSGi container completing the configuration via a context xml file and properties associated with the Service. - -Here's an example of doing that with a simple bundle that serves static content with an `org.osgi.framework.BundleActivator` that instantiates a `ContextHandler` and registers it as an OSGi Service, passing in properties that define a context xml file and context path for Jetty to apply upon deployment: - -The bundle contents: - -[source, plain, subs="{sub-order}"] ----- -META-INF/MANIFEST.MF -static/index.html -acme.xml -com/acme/osgi/Activator.class -com/acme/osgi/Activator$1.class ----- - -The `MANIFEST`: - -[source, plain, subs="{sub-order}"] ----- -Bundle-Classpath: . -Bundle-Name: Jetty OSGi Test Context -DynamicImport-Package: org.eclipse.jetty.*;version="[9.0,10.0)" -Bundle-Activator: com.acme.osgi.Activator -Import-Package: javax.servlet;version="2.6.0", - javax.servlet.resources;version="2.6.0", - org.eclipse.jetty.server.handler;version="[9.0,10)", - org.osgi.framework;version="[1.5,2)", - org.osgi.service.cm;version="1.2.0", - org.osgi.service.packageadmin;version="[1.2,2)", - org.osgi.service.startlevel;version="1.0.0.o", - org.osgi.service.url;version="1.0.0", - org.osgi.util.tracker;version="1.3.0", - org.xml.sax,org.xml.sax.helpers -Bundle-SymbolicName: com.acme.testcontext ----- - -The Activator code: - -[source, java, subs="{sub-order}"] ----- -public void start(final BundleContext context) throws Exception -{ - ContextHandler ch = new ContextHandler(); - ch.addEventListener(new ServletContextListener () { - - @Override - public void contextInitialized(ServletContextEvent sce) - { - System.err.println("Context is initialized"); - } - - @Override - public void contextDestroyed(ServletContextEvent sce) - { - System.err.println("Context is destroyed!"); - } - - }); - Dictionary props = new Hashtable(); - props.put("Web-ContextPath","/acme"); - props.put("Jetty-ContextFilePath", "acme.xml"); - context.registerService(ContextHandler.class.getName(),ch,props); -} ----- - -The contents of the `acme.xml` context file: - -[source, xml, subs="{sub-order}"] ----- -include::{SRCDIR}/jetty-osgi/test-jetty-osgi-context/src/main/context/acme.xml[] ----- - -You may also use the following OSGi Service properties: - -managedServerName:: -The name of the Server instance to which to deploy this webapp. -If not specified, defaults to the default Server instance called "defaultJettyServer". - -===== Extra Properties Available for Context Xml Files - -Before the Jetty OSGi container applies a context xml file found in a `Jetty-ContextFilePath` property, it sets a few useful properties that can be referred to within the xml file: - -Server:: -This is a reference to the Jetty `org.eclipse.jetty.server.Server` instance to which the `ContextHandler` being configured in the context xml file will be deployed. -bundle.root:: -This is a reference to the `org.eclipse.jetty.util.resource.Resource` that represents the location of the Bundle publishing the `ContextHandler` as a Service (obtained by calling `Bundle.getLocation()`). -Note that this could be either a directory in the file system if the OSGi container automatically unpacks bundles, or it may be a jar:file: url if the bundle remains packed. - -In the example above, you can see both of these properties being used in the context xml file. - -==== Support for the OSGi Service Platform Enterprise Specification - -The Jetty OSGi container implements several aspects of the Enterprise Specification v4.2 for the `WebAppContexts` and `ContextHandlers` that it deploys from either bundles or OSGi services as outlined in foregoing sections. - -===== Context Attributes - -For each `WebAppContext` or `ContextHandler`, the following context attribute is set, as required by section __128.6.1 Bundle Context__ page 427: - -osgi-bundleContext:: -The value of this attribute is the `BundleContext` representing the Bundle associated with the `WebAppContext` or `ContextHandler`. - -===== Service Attributes - -As required by the specification section _128.3.4 Publishing the Servlet Context_ page 421, each `WebAppContext` and `ContextHandler` deployed by the Jetty OSGi container is also published as an OSGi service (unless it has been already - see sections 1.6 and 1.7). -The following properties are associated with these services: - -osgi.web.symbolicname:: -The symbolic name of the Bundle associated with the `WebAppContext` or `ContextHandler` -osgi.web.version:: -The Bundle-Version header from the Bundle associated with the `WebAppContext` or `ContextHandler` -osgi.web.contextpath:: -The context path of the `WebAppContext` or `ContextHandler` - -===== OSGi Events - -As required by the specification section _128.5 Events_ pg 426, the -following OSGi Event Admin events will be posted: - -org/osgi/service/web/DEPLOYING:: -The Jetty OSGi container is about to deploy a `WebAppContext` or `ContextHandler` -org/osgi/service/web/DEPLOYED:: -The Jetty OSGi container has finished deploying a `WebAppContext` or `ContextHandler` and it is in service -org/osgi/service/web/UNDEPLOYING:: -The Jetty OSGi container is about to undeploy a `WebAppContext` or `ContextHandler` -org/osgi/service/web/UNDEPLOYED:: -The Jetty OSGi container has finished undeploying a `WebAppContext` or `ContextHandler` and it is no longer in service -org/osgi/service/web/FAILED:: -The Jetty OSGi container failed to deploy a `WebAppContext` or `ContextHandler` - -==== Using JSPs - -===== Setup - -In order to use JSPs with your webapps and bundles you will need to install the JSP and JSTL jars and their dependencies into your OSGi container. -Some you will find in the Jetty distribution, whereas others you will need to download from https://repo1.maven.org/maven2/org/eclipse/jetty/orbit/[Maven central]. -Here is the list of recommended jars (NOTE the version numbers may change in future): - -[[osgi-jsp]] - -.Jars Required for JSP -[cols=",,",options="header",] -|======================================================================= -|Jar |Bundle Symbolic Name |Location -|The link:#osgi-annotations[annotation jars] | | - -|org.mortbay.jasper:apache-el |org.mortbay.jasper.apache-el -|Distribution lib/apache-jsp - -|org.mortbay.jasper:apache-jsp |org.mortbay.jasper.apache-jsp -|Distribution lib/apache-jsp - -|org.eclipse.jetty:apache-jsp |org.eclipse.jetty.apache-jsp -|Distribution lib/apache-jsp - -|org.eclipse.jdt.core-3.8.2.v20130121.jar -|org.eclipse.jdt.core.compiler.batch |Distribution lib/apache-jsp - -|org.eclipse.jetty.osgi:jetty-osgi-boot-jsp -|org.eclipse.jetty.osgi.boot.jsp -|https://repo1.maven.org/maven2/org/eclipse/jetty/osgi/jetty-osgi-boot-jsp[Maven central] -|======================================================================= - -____ -[NOTE] -1. As of Jetty 9.2.3 the jetty-osgi-boot-jsp bundle changed to using Apache Jasper as the JSP implementation. -Prior to this the Glassfish Jasper implementation was used, which had a different set of dependencies - pay careful attention to the jars listed both at the top of this page and in this section, as deployment of other jars can cause incomplete or incorrect package resolution in the OSGi container. -2. The order of deployment is important. -Deploy these bundles in the order shown or you may experience strange failures in the compilation of jsps. -This can be hard to diagnose but is almost always caused by the `ServletContainerInitializer` in the `org.eclipse.jetty.apache-jsp` bundle for the jsp container not being invoked due to incorrect startup of the annotation jars. -____ - -For the JSTL library, we recommend the use of the implementation from Glassfish, as it has fewer dependencies: - -.Jars Required for Glassfish JSTL -[cols=",,",options="header",] -|======================================================================= -|Jar |Bundle Symbolic Name -|The link:#osgi-jsp[jsp jars]| - -|org.eclipse.jetty.orbit:javax.servlet.jsp.jstl-1.2.0.v201105211821.jar| javax.servlet.jsp.jstl - -|org.glassfish.web:javax.servlet.jsp.jstl-1.2.2.jar|org.glassfish.web.javax.servlet.jsp.jstl -|======================================================================= - -However, if you wish, you may use the JSTL implementation from Apache instead, although you will need to source some dependency jars with suitable OSGi manifests: - -.Jars Required for Apache JSTL -[cols=",,",options="header",] -|======================================================================= -|Jar |Bundle Symbolic Name |Location -|The link:#osgi-jsp[jsp jars] | | - -|org.apache.taglibs:taglibs-standard-spec:jar:1.2.1 -|org.apache.taglibs.taglibs-standard-spec |Distribution lib/apache-jstl - -|org.apache.taglibs:taglibs-standard-spec:jar:1.2.1 -|org.apache.taglibs.standard-impl |Distribution lib/apache-jstl - -|org.apache.xalan 2.7.1 | |Try -http://download.eclipse.org/tools/orbit/downloads/drops/R20140525021250/repository/plugins/org.apache.xalan_2.7.1.v201005080400.jar[Eclipse -Orbit] - -|org.apache.xml.serializer 2.7.1 | |Try -http://download.eclipse.org/tools/orbit/downloads/drops/R20140525021250/repository/plugins/org.apache.xml.serializer_2.7.1.v201005080400.jar[Eclipse -Orbit] -|======================================================================= - -===== The jetty-osgi-boot-jsp jar - -To be able to use JSPs you will need to also install the https://repo1.maven.org/maven2/org/eclipse/jetty/osgi/jetty-osgi-boot-jsp/[jetty-osgi-boot-jsp.jar] into your OSGi container. -This jar can be obtained from maven central https://repo1.maven.org/maven2/org/eclipse/jetty/osgi/jetty-osgi-boot-jsp/[here]. - -This bundle acts as a fragment extension to the jetty-osgi-boot.jar and adds in support for using JSP. - -====== Using TagLibs - -The Jetty JSP OSGi container will make available the JSTL tag library to all webapps. -If you only use this tag library, then your webapp will work without any further modification. - -However, if you make use of other taglibs, you will need to ensure that they are installed into the OSGi container, and also define some System properties and/or `MANIFEST` headers in your webapp. -This is necessary because the classloading regime used by the OSGi container is very different than that used by JSP containers, and the `MANIFEST` of a normal webapp does not contain enough information for the OSGi environment to allow a JSP container to find and resolve TLDs referenced in the webapp's .jsp files. - -Firstly, lets look at an example of a web bundle's modified `MANIFEST` file so you get an idea of what is required. -This example is a web bundle that uses the Spring servlet framework: - -[source, plain, subs="{sub-order}"] ----- -Bundle-SymbolicName: com.acme.sample -Bundle-Name: WebSample -Web-ContextPath: taglibs -Import-Bundle: org.springframework.web.servlet -Require-TldBundle: org.springframework.web.servlet -Bundle-Version: 1.0.0 -Import-Package: org.eclipse.virgo.web.dm;version="[3.0.0,4.0.0)",org.s - pringframework.context.config;version="[2.5.6,4.0.0)",org.springframe - work.stereotype;version="[2.5.6,4.0.0)",org.springframework.web.bind. - annotation;version="[2.5.6,4.0.0)",org.springframework.web.context;ve - rsion="[2.5.6,4.0.0)",org.springframework.web.servlet;version="[2.5.6 - ,4.0.0)",org.springframework.web.servlet.view;version="[2.5.6,4.0.0)" ----- - -The *Require-TldBundle* header tells the Jetty OSGi container that this bundle contains TLDs that need to be passed over to the JSP container for processing. -The *Import-Bundle* header ensures that the implementation classes for these TLDs will be available to the webapp on the OSGi classpath. - -The format of the *Require-TldBundle* header is a comma separated list of one or more symbolic names of bundles containing TLDs. - -====== Container Path Taglibs - -Some TLD jars are required to be found on the Jetty OSGi container's classpath, rather than considered part of the web bundle's classpath. -For example, this is true of JSTL and Java Server Faces. -The Jetty OSGi container takes care of JSTL for you, but you can control which other jars are considered as part of the container's classpath by using the System property **org.eclipse.jetty.osgi.tldbundles**: - -org.eclipse.jetty.osgi.tldbundles:: -System property defined on the OSGi environment that is a comma separated list of symbolic names of bundles containing taglibs that will be treated as if they are on the container's classpath for web bundles. -For example: -+ -[source, plain, subs="{sub-order}"] ----- -org.eclipse.jetty.osgi.tldbundles=com.acme.special.tags,com.foo.web,org.bar.web.framework ----- -+ -You will still need to define the *Import-Bundle* header in the `MANIFEST` file for the web bundle to ensure that the TLD bundles are on the OSGi classpath. - -Alternatively or additionally, you can define a pattern as a context attribute that will match symbolic bundle names in the OSGi environment containing TLDs that should be considered as discovered from the container's classpath. - -org.eclipse.jetty.server.webapp.containerIncludeBundlePattern:: -This pattern must be specified as a context attribute of the `WebAppContext` representing the web bundle. -Unless you are deploying your own `WebAppContext` (see link:#services-as-webapps[Deploying Services as Webapps]), you won't have a reference to the `WebAppContext` to do this. -In that case, it can be specified on the `org.eclipse.jetty.deploy.DeploymentManager`, where it will be applied to _every_ webapp deployed by the Jetty OSGi container. -The `jetty-osgi-boot.jar` contains the default `jettyhome/etc/jetty-deploy.xml` file where the `DeploymentManager` is defined. -To set the pattern, you will need to provide your own etc files - see the section on link:#customize-jetty-container[customizing the jetty container] for how to do this. Here's how the `jetty-deploy.xml` file would look if we defined a pattern that matched all bundle symbolic names ending in "tag" and "web": -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - org.eclipse.jetty.server.webapp.ContainerIncludeBundlePattern - .*\.tag$|.*\.web$ - - - - - ----- -+ -Again, you will still need to define suitable *Import-Bundle* headers in your web bundle `MANIFEST` to ensure that bundles matching the pattern are available on the OSGi class path. - -[[osgi-annotations]] -==== Using Annotations/ServletContainerInitializers - -Annotations are very much part of the Servlet 3.0 and 3.1 specifications. -In order to use them with Jetty in OSGi, you will need to deploy some extra jars into your OSGi container: - -.Jars Required for Annotations -[cols=",,",options="header",] -|======================================================================= -|Jar |Bundle Symbolic Name |Location -|The link:#spifly[spifly jars] | | -|org.ow2.asm:asm-7.0.jar |org.objectweb.asm -|https://repo1.maven.org/maven2/org/ow2/asm/asm[Maven central] - -|org.ow2.asm:asm-commons-7.0.jar |org.objectweb.asm.commons -|https://repo1.maven.org/maven2/org/ow2/asm/asm-commons[Maven central] - -|org.ow2.asm:asm-tree-7.0.jar |org.objectweb.asm.tree -|https://repo1.maven.org/maven2/org/ow2/asm/asm-tree[Maven central] - -|javax.annotation:javax.annotation-api-1.2.jar |javax.annotation-api -|https://repo1.maven.org/maven2/javax/annotation/javax.annotation-api/[Maven -central] - -|jta api version 1.1.1 (eg -org.apache.geronimo.specs:geronimo-jta_1.1_spec-1.1.1.jar)^*^ | |Maven -central - -|javax mail api version 1.4.1 (eg -org.eclipse.jetty.orbit:javax.mail.glassfish-1.4.1.v201005082020.jar)^*^ -| |Maven central - -|jetty-jndi |org.eclipse.jetty.jndi |Distribution lib/ - -|jetty-plus |org.eclipse.jetty.plus |Distribution lib/ - -|jetty-annotations |org.eclipse.jetty.annotations |Distribution lib/ -|======================================================================= - -____ -[IMPORTANT] -If you wish to use JSPs you will need to deploy these annotation-related jars. -____ - -____ -[NOTE] -You may be able to deploy later versions or other providers of these specifications, however these particular versions are known to have correct manifests and have been tested and known to work with OSGi. -____ - -Even if your webapp itself does not not use annotations, you may need to deploy these jars because your webapp depends on a Jetty module or a 3rd party library that uses a http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContainerInitializer.html[javax.servlet.ServletContainerInitializer]. -This interface requires annotation support. -It is implemented by providers of code that extend the capabilities of the container. -An example of this is the Jetty JSR356 Websocket implementation, although it is being used increasingly commonly in popular libraries like link:http://projects.spring.io/spring-framework/[Spring], link:https://jersey.java.net/[Jersey] and JSP containers. - -To find `ServletContainerInitializers` on the classpath, Jetty uses the Java http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html[`ServiceLoader`] -mechanism. -For this to function in OSGi, you will need an OSGi R5 compatible container, and have support for the http://blog.osgi.org/2013/02/javautilserviceloader-in-osgi.html[Service Loader Mediator]. -Jetty has been tested with the http://aries.apache.org/modules/spi-fly.html[Aries SpiFly] module, which is the reference implementation of the Service Loader Mediator, and is listed in the jars above. - -==== OSGi Containers - -===== Felix - -The Jetty OSGi integration has been successfully tested against http://felix.apache.org/[Felix] 5.0.0. - -You will require the following extra Felix services, available as separately downloadable jars: - -* http://felix.apache.org/documentation/subprojects/apache-felix-config-admin.html[Felix Configuration Admin Service] -* http://felix.apache.org/documentation/subprojects/apache-felix-event-admin.html[Felix Event Admin Service] - -Unfortunately, as of Felix 4.x there is a difficultly with the resolution of the `javax.transaction` package. -A link:http://mail-archives.apache.org/mod_mbox/felix-users/201211.mbox/%3CCAPr=90M+5vYjPqAvyTU+gYHr64y_FosBYELeUYcU_rFEJF3Cxw@mail.gmail.com%3E[description of the problem] and hint to solving it is described [http://mail-archives.apache.org/mod_mbox/felix-users/201211.mbox/%3CCAPr=90M+5vYjPqAvyTU+gYHr64y_FosBYELeUYcU_rFEJF3Cxw@mail.gmail.com%3E[here]]. - -The simplest solution for this is to extract the `default.properties` file from the `felix.jar`, change the declaration of the `javax.sql` and `javax.transaction` packages and set the changed lines as the value of the `org.osgi.framework.system.packages` property in the `conf/config.properties` file. - -The `default.properties` file defines the default `org.osgi.framework.system.packages` property like this: - -[source,properties] ----- -# Default packages exported by system bundle. -org.osgi.framework.system.packages=org.osgi.framework; version=1.7.0, \ - org.osgi.framework.hooks.bundle; version=1.1.0, \ - org.osgi.framework.hooks.resolver; version=1.0.0, \ - org.osgi.framework.hooks.service; version=1.1.0, \ - org.osgi.framework.hooks.weaving; version=1.0.0, \ - org.osgi.framework.launch; version=1.1.0, \ - org.osgi.framework.namespace; version=1.0.0, \ - org.osgi.framework.startlevel; version=1.0.0, \ - org.osgi.framework.wiring; version=1.1.0, \ - org.osgi.resource; version=1.0.0, \ - org.osgi.service.packageadmin; version=1.2.0, \ - org.osgi.service.startlevel; version=1.1.0, \ - org.osgi.service.url; version=1.0.0, \ - org.osgi.util.tracker; version=1.5.1 \ - ${jre-${java.specification.version}} ----- - -The last line must be substituted for one of the definitions further down in the file that is suitable for the jvm you are using. - -You will take these lines and copy them into the `conf/config.properties` file, after having replaced the line `$\{jre-$\{java.specification.version}}` with all of the lines relevant to your version of the jvm. - -For example, for a 1.7 jvm, you will find this property definition: - -[source,properties] ----- -jre-1.7=, \ - javax.accessibility;uses:="javax.swing.text";version="0.0.0.1_007_JavaSE", \ - javax.activation;version="0.0.0.1_007_JavaSE", \ - javax.activity;version="0.0.0.1_007_JavaSE", \ - javax.annotation.processing;uses:="javax.tools,javax.lang.model,javax.lang.model.element,javax.lang.model.util";version="0.0.0.1_007_JavaSE", \ - javax.annotation;version="0.0.0.1_007_JavaSE", \ - javax.crypto.interfaces;uses:="javax.crypto.spec,javax.crypto";version="0.0.0.1_007_JavaSE", \ - javax.crypto.spec;uses:="javax.crypto";version="0.0.0.1_007_JavaSE", \ - javax.crypto;uses:="javax.crypto.spec";version="0.0.0.1_007_JavaSE", \ - javax.imageio.event;uses:="javax.imageio";version="0.0.0.1_007_JavaSE", \ - javax.imageio.metadata;uses:="org.w3c.dom,javax.imageio";version="0.0.0.1_007_JavaSE", \ - javax.imageio.plugins.bmp;uses:="javax.imageio";version="0.0.0.1_007_JavaSE", \ - javax.imageio.plugins.jpeg;uses:="javax.imageio";version="0.0.0.1_007_JavaSE", \ - javax.imageio.spi;uses:="javax.imageio.stream,javax.imageio,javax.imageio.metadata";version="0.0.0.1_007_JavaSE", \ - javax.imageio.stream;uses:="javax.imageio";version="0.0.0.1_007_JavaSE", \ - javax.imageio;uses:="javax.imageio.metadata,javax.imageio.stream,javax.imageio.spi,javax.imageio.event";version="0.0.0.1_007_JavaSE", \ - javax.jws.soap;version="0.0.0.1_007_JavaSE", \ - javax.jws;version="0.0.0.1_007_JavaSE", \ - javax.lang.model.element;uses:="javax.lang.model.type,javax.lang.model";version="0.0.0.1_007_JavaSE", \ - javax.lang.model.type;uses:="javax.lang.model.element,javax.lang.model";version="0.0.0.1_007_JavaSE", \ - javax.lang.model.util;uses:="javax.lang.model,javax.lang.model.element,javax.annotation.processing,javax.lang.model.type";version="0.0.0.1_007_JavaSE", \ - javax.lang.model;version="0.0.0.1_007_JavaSE", \ - javax.management.loading;uses:="javax.management";version="0.0.0.1_007_JavaSE", \ - javax.management.modelmbean;uses:="javax.management,javax.management.loading";version="0.0.0.1_007_JavaSE", \ - javax.management.monitor;uses:="javax.management";version="0.0.0.1_007_JavaSE", \ - javax.management.openmbean;uses:="javax.management";version="0.0.0.1_007_JavaSE", \ - javax.management.relation;uses:="javax.management";version="0.0.0.1_007_JavaSE", \ - javax.management.remote.rmi;uses:="javax.management.remote,javax.security.auth,javax.management,javax.management.loading,javax.naming,javax.rmi.ssl,org.omg.CORBA,org.omg.CORBA_2_3.portable,org.omg.CORBA.portable,javax.rmi.CORBA,javax.rmi";version="0.0.0.1_007_JavaSE", \ - javax.management.remote;uses:="javax.security.auth,javax.management";version="0.0.0.1_007_JavaSE", \ - javax.management.timer;uses:="javax.management";version="0.0.0.1_007_JavaSE", \ - javax.management;uses:="javax.management.loading,javax.management.openmbean";version="0.0.0.1_007_JavaSE", \ - javax.naming.directory;uses:="javax.naming";version="0.0.0.1_007_JavaSE", \ - javax.naming.event;uses:="javax.naming,javax.naming.directory";version="0.0.0.1_007_JavaSE", \ - javax.naming.ldap;uses:="javax.naming,javax.naming.directory,javax.net.ssl,javax.naming.event";version="0.0.0.1_007_JavaSE", \ - javax.naming.spi;uses:="javax.naming,javax.naming.directory";version="0.0.0.1_007_JavaSE", \ - javax.naming;uses:="javax.naming.spi";version="0.0.0.1_007_JavaSE", \ - javax.net.ssl;uses:="javax.security.cert,javax.security.auth.x500,javax.net";version="0.0.0.1_007_JavaSE", \ - javax.net;version="0.0.0.1_007_JavaSE", \ - javax.print.attribute.standard;uses:="javax.print.attribute";version="0.0.0.1_007_JavaSE", \ - javax.print.attribute;version="0.0.0.1_007_JavaSE", \ - javax.print.event;uses:="javax.print,javax.print.attribute";version="0.0.0.1_007_JavaSE", \ - javax.print;uses:="javax.print.attribute,javax.print.event,javax.print.attribute.standard";version="0.0.0.1_007_JavaSE", \ - javax.rmi.CORBA;uses:="org.omg.CORBA,org.omg.CORBA_2_3.portable,org.omg.CORBA.portable,org.omg.SendingContext";version="0.0.0.1_007_JavaSE", \ - javax.rmi.ssl;uses:="javax.net,javax.net.ssl";version="0.0.0.1_007_JavaSE", \ - javax.rmi;uses:="org.omg.CORBA,javax.rmi.CORBA";version="0.0.0.1_007_JavaSE", \ - javax.script;version="0.0.0.1_007_JavaSE", \ - javax.security.auth.callback;version="0.0.0.1_007_JavaSE", \ - javax.security.auth.kerberos;uses:="javax.security.auth,javax.crypto";version="0.0.0.1_007_JavaSE", \ - javax.security.auth.login;uses:="javax.security.auth,javax.security.auth.callback";version="0.0.0.1_007_JavaSE", \ - javax.security.auth.spi;uses:="javax.security.auth.callback,javax.security.auth.login,javax.security.auth";version="0.0.0.1_007_JavaSE", \ - javax.security.auth.x500;uses:="javax.security.auth";version="0.0.0.1_007_JavaSE", \ - javax.security.auth;version="0.0.0.1_007_JavaSE", \ - javax.security.cert;version="0.0.0.1_007_JavaSE", \ - javax.security.sasl;uses:="javax.security.auth.callback";version="0.0.0.1_007_JavaSE", \ - javax.sound.midi.spi;uses:="javax.sound.midi";version="0.0.0.1_007_JavaSE", \ - javax.sound.midi;uses:="javax.sound.midi.spi";version="0.0.0.1_007_JavaSE", \ - javax.sound.sampled.spi;uses:="javax.sound.sampled";version="0.0.0.1_007_JavaSE", \ - javax.sound.sampled;uses:="javax.sound.sampled.spi";version="0.0.0.1_007_JavaSE", \ - javax.sql.rowset.serial;uses:="javax.sql.rowset";version="0.0.0.1_007_JavaSE", \ - javax.sql.rowset.spi;uses:="javax.sql,javax.naming,javax.sql.rowset";version="0.0.0.1_007_JavaSE", \ - javax.sql.rowset;uses:="javax.sql,javax.sql.rowset.serial,javax.sql.rowset.spi";version="0.0.0.1_007_JavaSE", \ - javax.sql;uses:="javax.transaction.xa";version="0.0.0.1_007_JavaSE", \ - javax.swing.border;uses:="javax.swing";version="0.0.0.1_007_JavaSE", \ - javax.swing.colorchooser;uses:="javax.swing,javax.swing.border,javax.swing.event,javax.swing.text";version="0.0.0.1_007_JavaSE", \ - javax.swing.event;uses:="javax.swing,javax.swing.text,javax.swing.table,javax.swing.tree,javax.swing.undo";version="0.0.0.1_007_JavaSE", \ - javax.swing.filechooser;uses:="javax.swing";version="0.0.0.1_007_JavaSE", \ - javax.swing.plaf.basic;uses:="javax.swing.border,javax.swing,javax.swing.plaf,javax.swing.text,javax.swing.event,javax.swing.colorchooser,javax.accessibility,javax.swing.filechooser,javax.swing.text.html,javax.sound.sampled,javax.swing.table,javax.swing.plaf.synth,javax.swing.tree";version="0.0.0.1_007_JavaSE", \ - javax.swing.plaf.metal;uses:="javax.swing.plaf,javax.swing,javax.swing.border,javax.swing.text,javax.swing.plaf.basic,javax.swing.filechooser,javax.swing.event,javax.swing.tree";version="0.0.0.1_007_JavaSE", \ - javax.swing.plaf.multi;uses:="javax.accessibility,javax.swing,javax.swing.plaf,javax.swing.filechooser,javax.swing.text,javax.swing.tree";version="0.0.0.1_007_JavaSE", \ - javax.swing.plaf.nimbus;uses:="javax.swing,javax.swing.plaf,javax.swing.border,javax.swing.plaf.synth";version="0.0.0.1_007_JavaSE", \ - javax.swing.plaf.synth;uses:="javax.swing,javax.swing.plaf,javax.swing.text,javax.swing.border,javax.swing.plaf.basic,javax.swing.colorchooser,javax.swing.event,javax.xml.parsers,org.xml.sax,org.xml.sax.helpers,javax.swing.table,javax.swing.tree";version="0.0.0.1_007_JavaSE", \ - javax.swing.plaf;uses:="javax.swing,javax.swing.border,javax.accessibility,javax.swing.filechooser,javax.swing.text,javax.swing.tree";version="0.0.0.1_007_JavaSE", \ - javax.swing.table;uses:="javax.swing.event,javax.swing.plaf,javax.swing.border,javax.swing,javax.accessibility";version="0.0.0.1_007_JavaSE", \ - javax.swing.text.html.parser;uses:="javax.swing.text,javax.swing.text.html";version="0.0.0.1_007_JavaSE", \ - javax.swing.text.html;uses:="javax.swing.event,javax.swing.text,javax.accessibility,javax.swing,javax.swing.plaf,javax.swing.border,javax.swing.undo";version="0.0.0.1_007_JavaSE", \ - javax.swing.text.rtf;uses:="javax.swing.text";version="0.0.0.1_007_JavaSE", \ - javax.swing.text;uses:="javax.swing.event,javax.swing.tree,javax.swing.undo,javax.swing,javax.swing.plaf,javax.swing.plaf.basic,javax.print,javax.print.attribute,javax.accessibility,javax.swing.text.html";version="0.0.0.1_007_JavaSE", \ - javax.swing.tree;uses:="javax.swing.event,javax.swing,javax.swing.border,javax.swing.plaf,javax.swing.plaf.basic";version="0.0.0.1_007_JavaSE", \ - javax.swing.undo;uses:="javax.swing,javax.swing.event";version="0.0.0.1_007_JavaSE", \ - javax.swing;uses:="javax.swing.event,javax.accessibility,javax.swing.text,javax.swing.plaf,javax.swing.border,javax.swing.tree,javax.swing.table,javax.swing.colorchooser,javax.swing.plaf.basic,javax.swing.text.html,javax.swing.filechooser,javax.print,javax.print.attribute,javax.swing.plaf.metal";version="0.0.0.1_007_JavaSE", \ - javax.tools;uses:="javax.lang.model.element,javax.annotation.processing,javax.lang.model";version="0.0.0.1_007_JavaSE", \ - javax.transaction.xa;version="0.0.0.1_007_JavaSE", \ - javax.transaction;version="0.0.0.1_007_JavaSE", \ - javax.xml.bind.annotation.adapters;uses:="javax.xml.bind";version="0.0.0.1_007_JavaSE", \ - javax.xml.bind.annotation;uses:="javax.xml.transform,javax.xml.bind,javax.xml.parsers,javax.xml.transform.dom,org.w3c.dom";version="0.0.0.1_007_JavaSE", \ - javax.xml.bind.attachment;uses:="javax.activation";version="0.0.0.1_007_JavaSE", \ - javax.xml.bind.helpers;uses:="javax.xml.bind.annotation.adapters,javax.xml.transform.dom,org.w3c.dom,org.xml.sax,javax.xml.bind.attachment,javax.xml.stream,javax.xml.transform,javax.xml.transform.stream,javax.xml.validation,javax.xml.transform.sax,javax.xml.bind,javax.xml.parsers";version="0.0.0.1_007_JavaSE", \ - javax.xml.bind.util;uses:="javax.xml.transform.sax,javax.xml.bind,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers";version="0.0.0.1_007_JavaSE", \ - javax.xml.bind;uses:="javax.xml.validation,javax.xml.namespace,javax.xml.datatype,javax.xml.transform,javax.xml.bind.annotation,javax.xml.transform.stream,org.w3c.dom,javax.xml.bind.attachment,javax.xml.stream,javax.xml.bind.annotation.adapters,org.xml.sax";version="0.0.0.1_007_JavaSE", \ - javax.xml.crypto.dom;uses:="javax.xml.crypto,org.w3c.dom";version="0.0.0.1_007_JavaSE", \ - javax.xml.crypto.dsig.dom;uses:="javax.xml.crypto.dsig,javax.xml.crypto,org.w3c.dom,javax.xml.crypto.dom";version="0.0.0.1_007_JavaSE", \ - javax.xml.crypto.dsig.keyinfo;uses:="javax.xml.crypto";version="0.0.0.1_007_JavaSE", \ - javax.xml.crypto.dsig.spec;uses:="javax.xml.crypto";version="0.0.0.1_007_JavaSE", \ - javax.xml.crypto.dsig;uses:="javax.xml.crypto,javax.xml.crypto.dsig.spec,javax.xml.crypto.dsig.keyinfo";version="0.0.0.1_007_JavaSE", \ - javax.xml.crypto;uses:="javax.xml.crypto.dsig.keyinfo";version="0.0.0.1_007_JavaSE", \ - javax.xml.datatype;uses:="javax.xml.namespace";version="0.0.0.1_007_JavaSE", \ - javax.xml.namespace;version="0.0.0.1_007_JavaSE", \ - javax.xml.parsers;uses:="javax.xml.validation,org.w3c.dom,org.xml.sax,org.xml.sax.helpers";version="0.0.0.1_007_JavaSE", \ - javax.xml.soap;uses:="javax.activation,javax.xml.namespace,org.w3c.dom,javax.xml.transform.dom,javax.xml.transform";version="0.0.0.1_007_JavaSE", \ - javax.xml.stream.events;uses:="javax.xml.namespace,javax.xml.stream";version="0.0.0.1_007_JavaSE", \ - javax.xml.stream.util;uses:="javax.xml.stream,javax.xml.stream.events,javax.xml.namespace";version="0.0.0.1_007_JavaSE", \ - javax.xml.stream;uses:="javax.xml.stream.events,javax.xml.namespace,javax.xml.stream.util,javax.xml.transform";version="0.0.0.1_007_JavaSE", \ - javax.xml.transform.dom;uses:="javax.xml.transform,org.w3c.dom";version="0.0.0.1_007_JavaSE", \ - javax.xml.transform.sax;uses:="org.xml.sax.ext,javax.xml.transform,org.xml.sax,javax.xml.transform.stream";version="0.0.0.1_007_JavaSE", \ - javax.xml.transform.stax;uses:="javax.xml.stream,javax.xml.transform,javax.xml.stream.events";version="0.0.0.1_007_JavaSE", \ - javax.xml.transform.stream;uses:="javax.xml.transform";version="0.0.0.1_007_JavaSE", \ - javax.xml.transform;version="0.0.0.1_007_JavaSE", \ - javax.xml.validation;uses:="org.w3c.dom.ls,javax.xml.transform,javax.xml.transform.stream,org.xml.sax,org.w3c.dom";version="0.0.0.1_007_JavaSE", \ - javax.xml.ws.handler.soap;uses:="javax.xml.ws.handler,javax.xml.namespace,javax.xml.soap,javax.xml.bind";version="0.0.0.1_007_JavaSE", \ - javax.xml.ws.handler;uses:="javax.xml.ws,javax.xml.namespace";version="0.0.0.1_007_JavaSE", \ - javax.xml.ws.http;uses:="javax.xml.ws";version="0.0.0.1_007_JavaSE", \ - javax.xml.ws.soap;uses:="javax.xml.ws.spi,javax.xml.ws,javax.xml.soap";version="0.0.0.1_007_JavaSE", \ - javax.xml.ws.spi.http;version="0.0.0.1_007_JavaSE", \ - javax.xml.ws.spi;uses:="javax.xml.ws,javax.xml.ws.wsaddressing,javax.xml.transform,org.w3c.dom,javax.xml.namespace,javax.xml.ws.handler,javax.xml.bind";version="0.0.0.1_007_JavaSE", \ - javax.xml.ws.wsaddressing;uses:="javax.xml.bind.annotation,javax.xml.namespace,org.w3c.dom,javax.xml.transform,javax.xml.bind,javax.xml.ws,javax.xml.ws.spi";version="0.0.0.1_007_JavaSE", \ - javax.xml.ws;uses:="javax.xml.ws.handler,javax.xml.ws.spi,javax.xml.ws.spi.http,javax.xml.transform,org.w3c.dom,javax.xml.bind.annotation,javax.xml.transform.stream,javax.xml.bind,javax.xml.namespace";version="0.0.0.1_007_JavaSE", \ - javax.xml.xpath;uses:="org.xml.sax,javax.xml.namespace";version="0.0.0.1_007_JavaSE", \ - javax.xml;version="0.0.0.1_007_JavaSE", \ - org.ietf.jgss;version="0.0.0.1_007_JavaSE", \ - org.omg.CORBA.DynAnyPackage;uses:="org.omg.CORBA";version="0.0.0.1_007_JavaSE", \ - org.omg.CORBA.ORBPackage;uses:="org.omg.CORBA";version="0.0.0.1_007_JavaSE", \ - org.omg.CORBA.TypeCodePackage;uses:="org.omg.CORBA";version="0.0.0.1_007_JavaSE", \ - org.omg.CORBA.portable;uses:="org.omg.CORBA,org.omg.CORBA_2_3.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.CORBA;uses:="org.omg.CORBA.portable,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA_2_3.portable,org.omg.CORBA.TypeCodePackage";version="0.0.0.1_007_JavaSE", \ - org.omg.CORBA_2_3.portable;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.CORBA_2_3;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.CosNaming.NamingContextExtPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.CosNaming.NamingContextPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.CosNaming";version="0.0.0.1_007_JavaSE", \ - org.omg.CosNaming;uses:="org.omg.CORBA.portable,org.omg.CORBA,org.omg.PortableServer,org.omg.CosNaming.NamingContextPackage,org.omg.CosNaming.NamingContextExtPackage";version="0.0.0.1_007_JavaSE", \ - org.omg.Dynamic;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.DynamicAny.DynAnyFactoryPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.DynamicAny.DynAnyPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.DynamicAny;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage";version="0.0.0.1_007_JavaSE", \ - org.omg.IOP.CodecFactoryPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.IOP.CodecPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.IOP;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage";version="0.0.0.1_007_JavaSE", \ - org.omg.Messaging;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.PortableInterceptor.ORBInitInfoPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.PortableInterceptor;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.IOP,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.CORBA_2_3.portable,org.omg.Dynamic";version="0.0.0.1_007_JavaSE", \ - org.omg.PortableServer.CurrentPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.PortableServer.POAManagerPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.PortableServer.POAPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.PortableServer.ServantLocatorPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.PortableServer.portable;uses:="org.omg.CORBA,org.omg.PortableServer";version="0.0.0.1_007_JavaSE", \ - org.omg.PortableServer;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.PortableServer.CurrentPackage,org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.portable,org.omg.CORBA_2_3,org.omg.PortableServer.ServantLocatorPackage";version="0.0.0.1_007_JavaSE", \ - org.omg.SendingContext;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", \ - org.omg.stub.java.rmi;uses:="javax.rmi.CORBA";version="0.0.0.1_007_JavaSE", \ - org.w3c.dom.bootstrap;uses:="org.w3c.dom";version="0.0.0.1_007_JavaSE", \ - org.w3c.dom.events;uses:="org.w3c.dom,org.w3c.dom.views";version="0.0.0.1_007_JavaSE", \ - org.w3c.dom.ls;uses:="org.w3c.dom,org.w3c.dom.events,org.w3c.dom.traversal";version="0.0.0.1_007_JavaSE", \ - org.w3c.dom;version="0.0.0.1_007_JavaSE", \ - org.xml.sax.ext;uses:="org.xml.sax,org.xml.sax.helpers";version="0.0.0.1_007_JavaSE", \ - org.xml.sax.helpers;uses:="org.xml.sax";version="0.0.0.1_007_JavaSE", \ - org.xml.sax;version="0.0.0.1_007_JavaSE" ----- - -Remove the definition for the `javax.transaction` packages, and remove the `uses:=` clause for the `javax.sql` packages (but leaving the `version` clause). Concatenate all the lines together. -You'll wind up with something like this in your `conf/config.properties` file: - -[source,properties] ----- -org.osgi.framework.system.packages=org.osgi.framework;version=1.7.0, org.osgi.framework.hooks.bundle;version=1.1.0, org.osgi.framework.hooks.resolver;version=1.0.0, org.osgi.framework.hooks.service;version=1.1.0, org.osgi.framework.hooks.weaving;version=1.0.0, org.osgi.framework.launch;version=1.1.0, org.osgi.framework.namespace;version=1.0.0, org.osgi.framework.startlevel;version=1.0.0, org.osgi.framework.wiring;version=1.1.0, org.osgi.resource;version=1.0.0, org.osgi.service.packageadmin; version=1.2.0, org.osgi.service.startlevel; version=1.1.0, org.osgi.service.url;version=1.0.0, org.osgi.util.tracker;version=1.5.1 javax.accessibility;uses:="javax.swing.text";version="0.0.0.1_007_JavaSE", javax.activation;version="0.0.0.1_007_JavaSE", javax.activity;version="0.0.0.1_007_JavaSE", javax.annotation.processing;uses:="javax.tools,javax.lang.model,javax.lang.model.element,javax.lang.model.util";version="0.0.0.1_007_JavaSE", javax.annotation;version="0.0.0.1_007_JavaSE", javax.crypto.interfaces;uses:="javax.crypto.spec,javax.crypto";version="0.0.0.1_007_JavaSE", javax.crypto.spec;uses:="javax.crypto";version="0.0.0.1_007_JavaSE", javax.crypto;uses:="javax.crypto.spec";version="0.0.0.1_007_JavaSE", javax.imageio.event;uses:="javax.imageio";version="0.0.0.1_007_JavaSE", javax.imageio.metadata;uses:="org.w3c.dom,javax.imageio";version="0.0.0.1_007_JavaSE", javax.imageio.plugins.bmp;uses:="javax.imageio";version="0.0.0.1_007_JavaSE", javax.imageio.plugins.jpeg;uses:="javax.imageio";version="0.0.0.1_007_JavaSE", javax.imageio.spi;uses:="javax.imageio.stream,javax.imageio,javax.imageio.metadata";version="0.0.0.1_007_JavaSE", javax.imageio.stream;uses:="javax.imageio";version="0.0.0.1_007_JavaSE", javax.imageio;uses:="javax.imageio.metadata,javax.imageio.stream,javax.imageio.spi,javax.imageio.event";version="0.0.0.1_007_JavaSE", javax.jws.soap;version="0.0.0.1_007_JavaSE", javax.jws;version="0.0.0.1_007_JavaSE", javax.lang.model.element;uses:="javax.lang.model.type,javax.lang.model";version="0.0.0.1_007_JavaSE", javax.lang.model.type;uses:="javax.lang.model.element,javax.lang.model";version="0.0.0.1_007_JavaSE", javax.lang.model.util;uses:="javax.lang.model,javax.lang.model.element,javax.annotation.processing,javax.lang.model.type";version="0.0.0.1_007_JavaSE", javax.lang.model;version="0.0.0.1_007_JavaSE", javax.management.loading;uses:="javax.management";version="0.0.0.1_007_JavaSE", javax.management.modelmbean;uses:="javax.management,javax.management.loading";version="0.0.0.1_007_JavaSE", javax.management.monitor;uses:="javax.management";version="0.0.0.1_007_JavaSE", javax.management.openmbean;uses:="javax.management";version="0.0.0.1_007_JavaSE", javax.management.relation;uses:="javax.management";version="0.0.0.1_007_JavaSE", javax.management.remote.rmi;uses:="javax.management.remote,javax.security.auth,javax.management,javax.management.loading,javax.naming,javax.rmi.ssl,org.omg.CORBA,org.omg.CORBA_2_3.portable,org.omg.CORBA.portable,javax.rmi.CORBA,javax.rmi";version="0.0.0.1_007_JavaSE", javax.management.remote;uses:="javax.security.auth,javax.management";version="0.0.0.1_007_JavaSE", javax.management.timer;uses:="javax.management";version="0.0.0.1_007_JavaSE", javax.management;uses:="javax.management.loading,javax.management.openmbean";version="0.0.0.1_007_JavaSE", javax.naming.directory;uses:="javax.naming";version="0.0.0.1_007_JavaSE", javax.naming.event;uses:="javax.naming,javax.naming.directory";version="0.0.0.1_007_JavaSE", javax.naming.ldap;uses:="javax.naming,javax.naming.directory,javax.net.ssl,javax.naming.event";version="0.0.0.1_007_JavaSE", javax.naming.spi;uses:="javax.naming,javax.naming.directory";version="0.0.0.1_007_JavaSE", javax.naming;uses:="javax.naming.spi";version="0.0.0.1_007_JavaSE", javax.net.ssl;uses:="javax.security.cert,javax.security.auth.x500,javax.net";version="0.0.0.1_007_JavaSE", javax.net;version="0.0.0.1_007_JavaSE", javax.print.attribute.standard;uses:="javax.print.attribute";version="0.0.0.1_007_JavaSE", javax.print.attribute;version="0.0.0.1_007_JavaSE", javax.print.event;uses:="javax.print,javax.print.attribute";version="0.0.0.1_007_JavaSE", javax.print;uses:="javax.print.attribute,javax.print.event,javax.print.attribute.standard";version="0.0.0.1_007_JavaSE", javax.rmi.CORBA;uses:="org.omg.CORBA,org.omg.CORBA_2_3.portable,org.omg.CORBA.portable,org.omg.SendingContext";version="0.0.0.1_007_JavaSE", javax.rmi.ssl;uses:="javax.net,javax.net.ssl";version="0.0.0.1_007_JavaSE", javax.rmi;uses:="org.omg.CORBA,javax.rmi.CORBA";version="0.0.0.1_007_JavaSE", javax.script;version="0.0.0.1_007_JavaSE", javax.security.auth.callback;version="0.0.0.1_007_JavaSE", javax.security.auth.kerberos;uses:="javax.security.auth,javax.crypto";version="0.0.0.1_007_JavaSE", javax.security.auth.login;uses:="javax.security.auth,javax.security.auth.callback";version="0.0.0.1_007_JavaSE", javax.security.auth.spi;uses:="javax.security.auth.callback,javax.security.auth.login,javax.security.auth";version="0.0.0.1_007_JavaSE", javax.security.auth.x500;uses:="javax.security.auth";version="0.0.0.1_007_JavaSE", javax.security.auth;version="0.0.0.1_007_JavaSE", javax.security.cert;version="0.0.0.1_007_JavaSE", javax.security.sasl;uses:="javax.security.auth.callback";version="0.0.0.1_007_JavaSE", javax.sound.midi.spi;uses:="javax.sound.midi";version="0.0.0.1_007_JavaSE", javax.sound.midi;uses:="javax.sound.midi.spi";version="0.0.0.1_007_JavaSE", javax.sound.sampled.spi;uses:="javax.sound.sampled";version="0.0.0.1_007_JavaSE", javax.sound.sampled;uses:="javax.sound.sampled.spi";version="0.0.0.1_007_JavaSE", javax.sql.rowset.serial;version="0.0.0.1_007_JavaSE", javax.sql.rowset.spi;version="0.0.0.1_007_JavaSE", javax.sql.rowset;version="0.0.0.1_007_JavaSE", javax.sql;version="0.0.0.1_007_JavaSE", javax.swing.border;uses:="javax.swing";version="0.0.0.1_007_JavaSE", javax.swing.colorchooser;uses:="javax.swing,javax.swing.border,javax.swing.event,javax.swing.text";version="0.0.0.1_007_JavaSE", javax.swing.event;uses:="javax.swing,javax.swing.text,javax.swing.table,javax.swing.tree,javax.swing.undo";version="0.0.0.1_007_JavaSE", javax.swing.filechooser;uses:="javax.swing";version="0.0.0.1_007_JavaSE", javax.swing.plaf.basic;uses:="javax.swing.border,javax.swing,javax.swing.plaf,javax.swing.text,javax.swing.event,javax.swing.colorchooser,javax.accessibility,javax.swing.filechooser,javax.swing.text.html,javax.sound.sampled,javax.swing.table,javax.swing.plaf.synth,javax.swing.tree";version="0.0.0.1_007_JavaSE", javax.swing.plaf.metal;uses:="javax.swing.plaf,javax.swing,javax.swing.border,javax.swing.text,javax.swing.plaf.basic,javax.swing.filechooser,javax.swing.event,javax.swing.tree";version="0.0.0.1_007_JavaSE", javax.swing.plaf.multi;uses:="javax.accessibility,javax.swing,javax.swing.plaf,javax.swing.filechooser,javax.swing.text,javax.swing.tree";version="0.0.0.1_007_JavaSE", javax.swing.plaf.nimbus;uses:="javax.swing,javax.swing.plaf,javax.swing.border,javax.swing.plaf.synth";version="0.0.0.1_007_JavaSE", javax.swing.plaf.synth;uses:="javax.swing,javax.swing.plaf,javax.swing.text,javax.swing.border,javax.swing.plaf.basic,javax.swing.colorchooser,javax.swing.event,javax.xml.parsers,org.xml.sax,org.xml.sax.helpers,javax.swing.table,javax.swing.tree";version="0.0.0.1_007_JavaSE", javax.swing.plaf;uses:="javax.swing,javax.swing.border,javax.accessibility,javax.swing.filechooser,javax.swing.text,javax.swing.tree";version="0.0.0.1_007_JavaSE", javax.swing.table;uses:="javax.swing.event,javax.swing.plaf,javax.swing.border,javax.swing,javax.accessibility";version="0.0.0.1_007_JavaSE", javax.swing.text.html.parser;uses:="javax.swing.text,javax.swing.text.html";version="0.0.0.1_007_JavaSE", javax.swing.text.html;uses:="javax.swing.event,javax.swing.text,javax.accessibility,javax.swing,javax.swing.plaf,javax.swing.border,javax.swing.undo";version="0.0.0.1_007_JavaSE", javax.swing.text.rtf;uses:="javax.swing.text";version="0.0.0.1_007_JavaSE", javax.swing.text;uses:="javax.swing.event,javax.swing.tree,javax.swing.undo,javax.swing,javax.swing.plaf,javax.swing.plaf.basic,javax.print,javax.print.attribute,javax.accessibility,javax.swing.text.html";version="0.0.0.1_007_JavaSE", javax.swing.tree;uses:="javax.swing.event,javax.swing,javax.swing.border,javax.swing.plaf,javax.swing.plaf.basic";version="0.0.0.1_007_JavaSE", javax.swing.undo;uses:="javax.swing,javax.swing.event";version="0.0.0.1_007_JavaSE", javax.swing;uses:="javax.swing.event,javax.accessibility,javax.swing.text,javax.swing.plaf,javax.swing.border,javax.swing.tree,javax.swing.table,javax.swing.colorchooser,javax.swing.plaf.basic,javax.swing.text.html,javax.swing.filechooser,javax.print,javax.print.attribute,javax.swing.plaf.metal";version="0.0.0.1_007_JavaSE", javax.tools;uses:="javax.lang.model.element,javax.annotation.processing,javax.lang.model";version="0.0.0.1_007_JavaSE", javax.xml.bind.annotation.adapters;uses:="javax.xml.bind";version="0.0.0.1_007_JavaSE", javax.xml.bind.annotation;uses:="javax.xml.transform,javax.xml.bind,javax.xml.parsers,javax.xml.transform.dom,org.w3c.dom";version="0.0.0.1_007_JavaSE", javax.xml.bind.attachment;uses:="javax.activation";version="0.0.0.1_007_JavaSE", javax.xml.bind.helpers;uses:="javax.xml.bind.annotation.adapters,javax.xml.transform.dom,org.w3c.dom,org.xml.sax,javax.xml.bind.attachment,javax.xml.stream,javax.xml.transform,javax.xml.transform.stream,javax.xml.validation,javax.xml.transform.sax,javax.xml.bind,javax.xml.parsers";version="0.0.0.1_007_JavaSE", javax.xml.bind.util;uses:="javax.xml.transform.sax,javax.xml.bind,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers";version="0.0.0.1_007_JavaSE", javax.xml.bind;uses:="javax.xml.validation,javax.xml.namespace,javax.xml.datatype,javax.xml.transform,javax.xml.bind.annotation,javax.xml.transform.stream,org.w3c.dom,javax.xml.bind.attachment,javax.xml.stream,javax.xml.bind.annotation.adapters,org.xml.sax";version="0.0.0.1_007_JavaSE", javax.xml.crypto.dom;uses:="javax.xml.crypto,org.w3c.dom";version="0.0.0.1_007_JavaSE", javax.xml.crypto.dsig.dom;uses:="javax.xml.crypto.dsig,javax.xml.crypto,org.w3c.dom,javax.xml.crypto.dom";version="0.0.0.1_007_JavaSE", javax.xml.crypto.dsig.keyinfo;uses:="javax.xml.crypto";version="0.0.0.1_007_JavaSE", javax.xml.crypto.dsig.spec;uses:="javax.xml.crypto";version="0.0.0.1_007_JavaSE", javax.xml.crypto.dsig;uses:="javax.xml.crypto,javax.xml.crypto.dsig.spec,javax.xml.crypto.dsig.keyinfo";version="0.0.0.1_007_JavaSE", javax.xml.crypto;uses:="javax.xml.crypto.dsig.keyinfo";version="0.0.0.1_007_JavaSE", javax.xml.datatype;uses:="javax.xml.namespace";version="0.0.0.1_007_JavaSE", javax.xml.namespace;version="0.0.0.1_007_JavaSE", javax.xml.parsers;uses:="javax.xml.validation,org.w3c.dom,org.xml.sax,org.xml.sax.helpers";version="0.0.0.1_007_JavaSE", javax.xml.soap;uses:="javax.activation,javax.xml.namespace,org.w3c.dom,javax.xml.transform.dom,javax.xml.transform";version="0.0.0.1_007_JavaSE", javax.xml.stream.events;uses:="javax.xml.namespace,javax.xml.stream";version="0.0.0.1_007_JavaSE", javax.xml.stream.util;uses:="javax.xml.stream,javax.xml.stream.events,javax.xml.namespace";version="0.0.0.1_007_JavaSE", javax.xml.stream;uses:="javax.xml.stream.events,javax.xml.namespace,javax.xml.stream.util,javax.xml.transform";version="0.0.0.1_007_JavaSE", javax.xml.transform.dom;uses:="javax.xml.transform,org.w3c.dom";version="0.0.0.1_007_JavaSE", javax.xml.transform.sax;uses:="org.xml.sax.ext,javax.xml.transform,org.xml.sax,javax.xml.transform.stream";version="0.0.0.1_007_JavaSE", javax.xml.transform.stax;uses:="javax.xml.stream,javax.xml.transform,javax.xml.stream.events";version="0.0.0.1_007_JavaSE", javax.xml.transform.stream;uses:="javax.xml.transform";version="0.0.0.1_007_JavaSE", javax.xml.transform;version="0.0.0.1_007_JavaSE", javax.xml.validation;uses:="org.w3c.dom.ls,javax.xml.transform,javax.xml.transform.stream,org.xml.sax,org.w3c.dom";version="0.0.0.1_007_JavaSE", javax.xml.ws.handler.soap;uses:="javax.xml.ws.handler,javax.xml.namespace,javax.xml.soap,javax.xml.bind";version="0.0.0.1_007_JavaSE", javax.xml.ws.handler;uses:="javax.xml.ws,javax.xml.namespace";version="0.0.0.1_007_JavaSE", javax.xml.ws.http;uses:="javax.xml.ws";version="0.0.0.1_007_JavaSE", javax.xml.ws.soap;uses:="javax.xml.ws.spi,javax.xml.ws,javax.xml.soap";version="0.0.0.1_007_JavaSE", javax.xml.ws.spi.http;version="0.0.0.1_007_JavaSE", javax.xml.ws.spi;uses:="javax.xml.ws,javax.xml.ws.wsaddressing,javax.xml.transform,org.w3c.dom,javax.xml.namespace,javax.xml.ws.handler,javax.xml.bind";version="0.0.0.1_007_JavaSE", javax.xml.ws.wsaddressing;uses:="javax.xml.bind.annotation,javax.xml.namespace,org.w3c.dom,javax.xml.transform,javax.xml.bind,javax.xml.ws,javax.xml.ws.spi";version="0.0.0.1_007_JavaSE", javax.xml.ws;uses:="javax.xml.ws.handler,javax.xml.ws.spi,javax.xml.ws.spi.http,javax.xml.transform,org.w3c.dom,javax.xml.bind.annotation,javax.xml.transform.stream,javax.xml.bind,javax.xml.namespace";version="0.0.0.1_007_JavaSE", javax.xml.xpath;uses:="org.xml.sax,javax.xml.namespace";version="0.0.0.1_007_JavaSE", javax.xml;version="0.0.0.1_007_JavaSE", org.ietf.jgss;version="0.0.0.1_007_JavaSE", org.omg.CORBA.DynAnyPackage;uses:="org.omg.CORBA";version="0.0.0.1_007_JavaSE", org.omg.CORBA.ORBPackage;uses:="org.omg.CORBA";version="0.0.0.1_007_JavaSE", org.omg.CORBA.TypeCodePackage;uses:="org.omg.CORBA";version="0.0.0.1_007_JavaSE", org.omg.CORBA.portable;uses:="org.omg.CORBA,org.omg.CORBA_2_3.portable";version="0.0.0.1_007_JavaSE", org.omg.CORBA;uses:="org.omg.CORBA.portable,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA_2_3.portable,org.omg.CORBA.TypeCodePackage";version="0.0.0.1_007_JavaSE", org.omg.CORBA_2_3.portable;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.CORBA_2_3;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.CosNaming.NamingContextExtPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.CosNaming.NamingContextPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.CosNaming";version="0.0.0.1_007_JavaSE", org.omg.CosNaming;uses:="org.omg.CORBA.portable,org.omg.CORBA,org.omg.PortableServer,org.omg.CosNaming.NamingContextPackage,org.omg.CosNaming.NamingContextExtPackage";version="0.0.0.1_007_JavaSE", org.omg.Dynamic;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.DynamicAny.DynAnyFactoryPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.DynamicAny.DynAnyPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.DynamicAny;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage";version="0.0.0.1_007_JavaSE", org.omg.IOP.CodecFactoryPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.IOP.CodecPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.IOP;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage";version="0.0.0.1_007_JavaSE", org.omg.Messaging;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.PortableInterceptor.ORBInitInfoPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.PortableInterceptor;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.IOP,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.CORBA_2_3.portable,org.omg.Dynamic";version="0.0.0.1_007_JavaSE", org.omg.PortableServer.CurrentPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.PortableServer.POAManagerPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.PortableServer.POAPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.PortableServer.ServantLocatorPackage;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.PortableServer.portable;uses:="org.omg.CORBA,org.omg.PortableServer";version="0.0.0.1_007_JavaSE", org.omg.PortableServer;uses:="org.omg.CORBA,org.omg.CORBA.portable,org.omg.PortableServer.CurrentPackage,org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.portable,org.omg.CORBA_2_3,org.omg.PortableServer.ServantLocatorPackage";version="0.0.0.1_007_JavaSE", org.omg.SendingContext;uses:="org.omg.CORBA,org.omg.CORBA.portable";version="0.0.0.1_007_JavaSE", org.omg.stub.java.rmi;uses:="javax.rmi.CORBA";version="0.0.0.1_007_JavaSE", org.w3c.dom.bootstrap;uses:="org.w3c.dom";version="0.0.0.1_007_JavaSE", org.w3c.dom.events;uses:="org.w3c.dom,org.w3c.dom.views";version="0.0.0.1_007_JavaSE", org.w3c.dom.ls;uses:="org.w3c.dom,org.w3c.dom.events,org.w3c.dom.traversal";version="0.0.0.1_007_JavaSE", org.w3c.dom;version="0.0.0.1_007_JavaSE", org.xml.sax.ext;uses:="org.xml.sax,org.xml.sax.helpers";version="0.0.0.1_007_JavaSE", org.xml.sax.helpers;uses:="org.xml.sax";version="0.0.0.1_007_JavaSE", org.xml.sax;version="0.0.0.1_007_JavaSE" ----- - -You should now be able to start Felix, and deploy all the jars listed on this page. -You should see output similar to this on the console, using the `felix:lb` command: - -.... - ID|State |Level|Name - 0|Active | 0|System Bundle (4.4.1) - 1|Active | 1|ASM (7.0) - 2|Active | 1|ASM commons classes (7.0) - 3|Active | 1|ASM Tree class visitor (7.0) - 4|Active | 1|geronimo-jta_1.1_spec (1.1.1) - 5|Active | 1|javax.annotation API (1.2.0) - 6|Active | 1|javax.mail bundle from Glassfish (1.4.1.v201005082020) - 7|Active | 1|Java Server Pages Standard Tag Library API Bundle (1.2.0.v201105211821) - 8|Active | 1|JavaServer Pages (TM) TagLib Implementation (1.2.2) - 9|Active | 1|Jetty :: Servlet Annotations ({VERSION}) - 10|Active | 1|Jetty :: Deployers ({VERSION}) - 11|Active | 1|Jetty :: Http Utility ({VERSION}) - 12|Active | 1|Jetty :: IO Utility ({VERSION}) - 13|Active | 1|Jetty :: JNDI Naming ({VERSION}) - 14|Active | 1|Jetty :: OSGi :: Boot ({VERSION}) - 15|Resolved | 1|Jetty-OSGi-Jasper Integration ({VERSION}) - 16|Active | 1|Jetty Servlet API and Schemas for OSGi (3.1.0) - 17|Active | 1|Jetty :: Plus ({VERSION}) - 18|Active | 1|Jetty :: Security ({VERSION}) - 19|Active | 1|Jetty :: Server Core ({VERSION}) - 20|Active | 1|Jetty :: Servlet Handling ({VERSION}) - 21|Active | 1|Jetty :: Utility Servlets and Filters ({VERSION}) - 22|Active | 1|Jetty :: Utilities ({VERSION}) - 23|Active | 1|Jetty :: Webapp Application Support ({VERSION}) - 24|Active | 1|Jetty :: XML utilities ({VERSION}) - 25|Active | 1|Apache Aries SPI Fly Dynamic Weaving Bundle (1.2) - 27|Active | 1|Apache Felix Bundle Repository (2.0.2) - 28|Active | 1|Apache Felix Configuration Admin Service (1.8.0) - 29|Active | 1|Apache Felix EventAdmin (1.3.2) - 30|Active | 1|Apache Felix Gogo Command (0.14.0) - 31|Active | 1|Apache Felix Gogo Runtime (0.12.1) - 32|Active | 1|Apache Felix Gogo Shell (0.10.0) - 33|Active | 1|Apache Felix Log Service (1.0.1) - 34|Active | 1|Jetty :: Apache JSP ({VERSION}) - 35|Active | 1|Eclipse Compiler for Java(TM) (3.8.2.v20130121-145325) - 36|Active | 1|Mortbay EL API and Implementation (8.5.33.1) - 37|Active | 1|Mortbay Jasper (8.5.33.1) -.... - -===== Eclipse - -The Jetty OSGi integration has been successfully tested against https://www.eclipse.org/equinox/[Equinox] Mars RC1. - -Ensure that these services are present: - -* https://www.eclipse.org/equinox/bundles/[Configuration Admin] -* https://www.eclipse.org/equinox/bundles/[Event Admin] - -====== Eclipse Update Site - -There is a list of Eclipse P2 sites for the jetty releases maintained at http://download.eclipse.org/jetty/updates/jetty-bundles-9.x/ - -Each P2 repo has one big feature group that defines most of the Jetty jars. -*Beware: No 3rd party dependency jars are included, so you will need to have installed the dependencies listed previously in this document.* - -In addition, as the feature group includes websocket, you will need to download and have installed the `javax.websocket-api` jar: - -.Extra Jars Required for Websocket -[cols=",,",options="header",] -|======================================================================= -|Jar |Bundle Symbolic Name |Location -|javax.websocket-api |javax.websocket-api -|https://repo1.maven.org/maven2/javax/websocket/[Maven -central] -|======================================================================= diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/configuring/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/configuring/chapter.adoc deleted file mode 100644 index b20e4b18f91d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/configuring/chapter.adoc +++ /dev/null @@ -1,17 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[quick-start-configure]] -== An Introduction to Jetty Configuration - -include::what-to-configure.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/configuring/what-to-configure.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/configuring/what-to-configure.adoc deleted file mode 100644 index 638abfac59a4..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/configuring/what-to-configure.adoc +++ /dev/null @@ -1,281 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[quickstart-config-what]] -=== What to Configure in Jetty - -This section gives an overview of the components of Jetty you typically configure using the mechanisms outlined in the previous section. -xref:basic-architecture[] describes the structure of a Jetty server, which is good background reading to understand configuration, and is vital if you want to change the structure of the server as set up by the default configurations in the Jetty distribution. -However, for most purposes, configuration is a matter of identifying the correct configuration file and modifying existing configuration values. - -[[intro-jetty-configuration-server]] -==== Configuring the Server - -The Server instance is the central coordination object of a Jetty server; it provides services and life cycle management for all other Jetty server components. -In the standard Jetty distribution, the core server configuration is in `etc/jetty.xml` file, but you can mix in other server configurations which can include: - -ThreadPool:: - The Server instance provides a ThreadPool instance that is the default Executor service other Jetty server components use. - The prime configuration of the thread pool is the maximum and minimum size and is set in `start.ini` or `start.d/server.ini`. -Handlers:: - A Jetty server can have only a single Handler instance to handle incoming HTTP requests. - However a handler may be a container or wrapper of other handlers forming a tree of handlers that typically - handle a request as a collaboration between the handlers from a branch of the tree from root to leaf. - The default handler tree set up in the `etc/jetty.xml` file is a Handler Collection containing a Context Handler Collection and the Default Handler. - The Context Handler Collection selects the next handler by context path and is where deployed Context Handler and Web Application Contexts are added to the handler tree. - The Default Handler handles any requests not already handled and generates the standard 404 page. - Other configuration files may add handlers to this tree (for example, `jetty-rewrite.xml`, `jetty-requestlog.xml`) or configure components to hot deploy handlers (for example, `jetty-deploy.xml`). -Server Attributes:: - The server holds a generic attribute map of strings to objects so that other Jetty components can associate named objects with the server, and if the value objects implement the LifeCycle interface, they are started and stopped with the server. - Typically server attributes hold server-wide default values. -Server fields:: - The server also has some specific configuration fields that you set in `start.ini` or `start.d/server.ini` for controlling, among other things, the sending of dates and versions in HTTP responses. -Connectors:: - The server holds a collection of connectors that receive connections for HTTP and the other protocols that Jetty supports. - The next section, xref:intro-jetty-configuration-connectors[] describes configuration of the connectors themselves. - For the server you can either set the collection of all connectors or add/remove individual connectors. -Services:: - The server can hold additional service objects, sometimes as attributes, but often as aggregated LifeCycle beans. - Examples of services are Login Services and DataSources, which you configure at the server level and then inject into the web applications that use them. - -[[intro-jetty-configuration-connectors]] -==== Configuring Connectors - -A Jetty Server Connector is a network end point that accepts connections for one or more protocols which produce requests and/or messages for the Jetty server. -In the standard Jetty server distribution, several provided configuration files add connectors to the server for various protocols and combinations of protocols: `http.ini`, `https.ini` and `jetty-http2.xml`. -The configuration needed for connectors is typically: - -Port:: - The TCP/IP port on which the connector listens for connections is set using the the XML Property element which looks up the `jetty.http.port` (or `jetty.ssl.port`) property, and if not found defaults to 8080 (or 8443 for TLS). -Host:: - You can configure a host either as a host name or IP address to identify a specific network interface on which to listen. - If not set, or set to the value of 0.0.0.0, the connector listens on all local interfaces. - The XML Property element is used to look up the host value from the `jetty.host` property. -Idle Timeout:: - The time in milliseconds that a connection can be idle before the connector takes action to close the connection. -HTTP Configuration:: - Connector types that accept HTTP semantics (including HTTP, HTTPS and HTTP2) are configured with a `HttpConfiguration` instance that contains common HTTP configuration that is independent of the specific wire protocol used. - Because these values are often common to multiple connector types, the standard Jetty Server distribution creates a single `HttpConfiguration` in the `jetty.xml` file which is used via the XML Ref element in the specific connector files. -SSL Context Factory:: - The TLS connector types (HTTPS and HTTP2) configure an SSL Context Factory with the location of the server keystore and truststore for obtaining server certificates. - - -____ -[NOTE] -Virtual hosts are not configured on connectors. You must configure individual contexts with the virtual hosts to which they respond. -____ - -____ -[NOTE] -Prior to Jetty 9, the type of the connector reflected both the protocol supported (HTTP, HTTPS, AJP, SPDY), and the nature of the implementation (NIO or BIO). -From Jetty 9 onwards there is only one prime Connector type (`ServerConnector`), which is NIO based and uses Connection Factories to handle one or more protocols. -____ - -[[intro-jetty-configuration-contexts]] -==== Configuring Contexts - -A Jetty context is a handler that groups other handlers under a context path together with associated resources and is roughly equivalent to the standard ServletContext API. -A context may contain either standard Jetty handlers or a custom application handler. - -____ -[NOTE] -The servlet specification defines a web application. -In Jetty a standard web application is a specialized context that uses a standard layout and `WEB-INF/web.xml` to instantiate and configure classpath, resource base and handlers for sessions, security, and servlets, plus servlets for JSPs and static content. -Standard web applications often need little or no additional configuration, but you can also use the techniques for arbitrary contexts to refine or modify the configuration of standard web applications. -____ - -Configuration values that are common to all contexts are: - -contextPath:: - The contextPath is a URL prefix that identifies which context a HTTP request is destined for. - For example, if a context has a context path `/foo`, it handles requests to `/foo`, `/foo/index.html`, - `/foo/bar/`, and `/foo/bar/image.png` but it does not handle requests like `/`, `/other/`, or `/favicon.ico`. - A context with a context path of / is called the root context. -+ -The context path can be set by default from the deployer (which uses the filename as the basis for the context path); or in code; or it can be set by a Jetty IoC XML that is either applied by the deployer or found in the `WEB-INF/jetty-web.xml` file of a standard web app context. - -virtualHost:: - A context may optionally have one or more virtual hosts set. - Unlike the host set on a connector (which selects the network interface on which to listen), a virtual host does not set any network parameters. - Instead a virtual host represents an alias assigned by a name service to an IP address, which may have many aliases. - To determine which virtual host a request is intended for, the HTTP client (browser) includes in the request the name used to look up the network address. - A context with a virtual host set only handles requests that have a matching virtual host in their request headers. -classPath:: - A context may optionally have a classpath, so that any thread that executes a handler within the context has a thread context classloader set with the classpath. - A standard web application has the classpath initialized by the `WEB-INF/lib` and `WEB-INF/classes` directory and - has additional rules about delegating classloading to the parent classloader. - All contexts may have additional classpath entries added. -attributes:: - Attributes are arbitrary named objects that are associated with a context and are frequently used to pass entities between a web application and its container. - For example the attribute `javax.servlet.context.tempdir` is used to pass the File instance that represents the assigned temporary directory for a web application. -resourceBase:: - The resource base is a directory (or collection of directories or URL) that contains the static resources for the context. - These can be images and HTML files ready to serve or JSP source files ready to be compiled. - In traditional web servers this value is often called the docroot. - -===== Context Configuration by API - -In an embedded server, you configure contexts by directly calling the link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html[ContextHandler] API as in the following example: - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/OneContext.java[] ----- - -===== Context Configuration by IoC XML - -You can create and configure a context entirely by IoC XML (either Jetty's or Spring). -The deployer discovers and hot deploys context IoC descriptors like the following which creates a context to serve the Javadoc from the Jetty distribution: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - /javadoc - /javadoc/ - - - - - index.html - - - max-age=3600,public - - - ----- - -[[intro-jetty-configuration-webapps]] -===== Configuring Web Applications - -The servlet specification defines a web application, which when packaged as a zip is called WAR file (Web application ARchive). -Jetty implements both WAR files and unpacked web applications as a specialized context that is configured by means of: - -* A standard layout which sets the location of the resourceBase (the root of the WAR) and initializes the classpath from jars found in `WEB-INF/lib` and classes found in `WEB-INF/classes`. -* The standard `WEB-INF/web.xml` deployment descriptor which is parsed to define and configure init parameters, filters, servlets, listeners, security constraints, welcome files and resources to be injected. -* A default `web.xml` format deployment descriptor provided either by Jetty or in configuration configures the JSP servlet and the default servlet for handling static content. -The standard `web.xml` may override the default `web.xml`. -* Annotations discovered on classes in Jars contained in `WEB-INF/lib` can declare additional filters, servlets and listeners. -* Standard deployment descriptor fragments discovered in Jars contained in `WEB-INF/lib` can declare additional init parameters, filters, servlets, listeners, security constraints, welcome files and resources to be injected. -* An optional `WEB-INF/jetty-web.xml` file may contain Jetty IoC configuration to configure the Jetty specific APIs of the context and handlers. - -Because these configuration mechanisms are contained within the WAR file (or unpacked web application), typically a web application contains much of its own configuration and deploying a WAR is often just a matter of dropping the WAR file in to the webapps directory that is scanned by the link:#quickstart-config-deployer[Jetty deployer]. - -If you need to configure something within a web application, often you do so by unpacking the WAR file and editing the `web.xml` and other configuration files. -However, both the servlet standard and some Jetty features allow for other configuration to be applied to a web application externally from the WAR: - -* Configured data sources and security realms in the server can be injected into a web application either explicitly or by name matching. -* Jetty allows one or more override deployment descriptors, in `web.xml` format, to be set on a context (via code or IoC XML) to amend the configuration set by the default and standard `web.xml`. -* The normal Jetty Java API may be called by code or IoC XML to amend the configuration of a web application. - -===== Setting the Context Path - -The web application standard provides no configuration mechanism for a web application or WAR file to set its own `contextPath`. -By default the deployer uses conventions to set the context path: -If you deploy a WAR file called `foobar.WAR`, the context path is `/foobar`; if you deploy a WAR file called `ROOT.WAR` the context path is `/`. - -However, it is often desirable to explicitly set the context path so that information (for example, version numbers) may be included in the filename of the WAR. -Jetty allows the context Path of a WAR file to be set internally (by the WAR itself) or externally (by the deployer of the WAR). - -To set the contextPath from within the WAR file, you can include a `WEB-INF/jetty-web.xml` file which contains IoC XML to set the context path: - -[source, xml, subs="{sub-order}"] ----- - - - - - /contextpath - ----- - -Alternately, you can configure the classpath externally without the need to modify the WAR file itself. -Instead of allowing the WAR file to be discovered by the deployer, an IoC XML file may be deployed that both sets the context path and declares the WAR file that it applies to: - -[source, xml, subs="{sub-order}"] ----- - - - - - /webapps/test.war - /test - ----- - -An example of setting the context path is included with the Jetty distribution in `$JETTY_HOME/webapps/test.xml`. - -[[quickstart-config-deployer]] -===== Web Application Deployment - -Jetty is capable of deploying a variety of Web Application formats. -This is accomplished via scans of the `${jetty.base}/webapps` directory for contexts to deploy. - -A Context can be any of the following: - -* A standard WAR file. (must in "`.war`"). -* A directory containing an expanded WAR file. (must contain `{dir}/WEB-INF/web.xml` file). -* A directory containing static content. -* A XML descriptor in xref:jetty-xml-syntax[] that configures a link:{JDURL}/org/eclipse/jetty/server/handler/ContextHandler.html[ContextHandler] instance (Such as a -link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html[WebAppContext]). - -The new WebAppProvider will attempt to avoid double deployments during the directory scan with the following heuristics: - -* Hidden files (starting with `"."`) are ignored -* Directories with names ending in `".d"` are ignored -* If a directory and matching WAR file exist with the same base name (eg: `foo/` and `foo.war`), then the directory is assumed to be the unpacked WAR and only the WAR is deployed (which may reuse the unpacked directory) -* If a directory and matching XML file exists (eg: `foo/` and `foo.xml`), then the directory is assumed to be an unpacked WAR and only the XML is deployed (which may use the directory in its own configuration) -* If a WAR file and matching XML file exist (eg: `foo.war` and `foo.xml`), then the WAR is assumed to be configured by the XML and only the XML is deployed. - -____ -[NOTE] -In prior versions of Jetty there was a separate ContextDeployer that provided XML-based deployment. As of Jetty 9 the ContextDeployer no longer exists and its functionality has been merged with the new link:{JDURL}/org/eclipse/jetty/deploy/providers/WebAppProvider.html[WebAppProvider] to avoid double deployment scenarios. -____ - -//A Context is an instance of ContextHandler that aggregates other handlers with common resources for handling HTTP requests (such as resource base, class loader, configuration attributes). -//A standard web application is a specialized instance of a context (called a WebAppContext) that uses standard layouts and `web.xml` deployment descriptors to configure the context. - -===== Setting an Authentication Realm - -The authentication method and realm name for a standard web application may be set in the `web.xml` deployment descriptor with elements like: - -[source, xml, subs="{sub-order}"] ----- -... - - BASIC - Test Realm - -... ----- - -This example declares that the BASIC authentication mechanism will be used with credentials validated against a realm called "Test Realm." -However the standard does not describe how the realm itself is implemented or configured. -In Jetty, there are several realm implementations (called LoginServices) and the simplest of these is the HashLoginService, which can read usernames and credentials from a Java properties file. - -To configure an instance of HashLoginService that matches the "Test Realm" configured above, the following `$JETTY_BASE/etc/test-realm.xml` IoC XML file should be passed on the command line or set in `start.ini` or `start.d/server.ini`. - -[source, xml, subs="{sub-order}"] ----- -include::{SRCDIR}/tests/test-webapps/test-jetty-webapp/src/main/config/demo-base/etc/test-realm.xml[] ----- - -This creates and configures the LoginService as an aggregate bean on the server. -When a web application is deployed that declares a realm called "Test Realm," the server beans are searched for a matching Login Service. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/chapter.adoc deleted file mode 100644 index 8e3184b88e8a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/chapter.adoc +++ /dev/null @@ -1,22 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[quick-start-getting-started]] -== Using Jetty - -You can use Jetty in many different ways ranging from embedding Jetty in applications, launching it from different build systems, from different JVM-based languages, or as a standalone distribution. -This guide covers the latter, a standalone distribution suitable for deploying web applications. - -include::jetty-installing.adoc[] -include::jetty-running.adoc[] -include::jetty-common-configuration.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-common-configuration.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-common-configuration.adoc deleted file mode 100644 index 4622b55d0169..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-common-configuration.adoc +++ /dev/null @@ -1,184 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[quickstart-common-config]] - -=== Common Jetty Configuration - -[[creating-jetty-base]] -==== Creating a new Jetty Base - -The `demo-base` directory described earlier is an example of the link:#startup-base-and-home[`jetty.base`] mechanism. -A Jetty base directory allows the configuration and web applications of a server instance to be stored separately from the Jetty distribution, so that upgrades can be done with minimal disruption. -Jetty's default configuration is based on two properties: - -jetty.home:: - The property that defines the location of the Jetty distribution, its libs, default modules and default XML files (typically start.jar, lib, etc). -jetty.base:: - The property that defines the location of a specific implementation of a Jetty server, its configuration, logs and web applications (typically start.d/*.ini files, logs and webapps). - -____ -[IMPORTANT] -Your Jetty Home directory should be treated as a standard of truth and remain unmodified or changed. -Changes or additions to your configuration should take place in the Jetty Base directory. -____ - -The `jetty.home` and `jetty.base` properties may be explicitly set on the command line, or they can be inferred from the environment if used with commands like: - -[source, screen, subs="{sub-order}"] ----- -> cd $JETTY_BASE -> java -jar $JETTY_HOME/start.jar ----- - -The following commands create a new base directory, enables both the HTTP connector and the web application deployer modules, and copies a demo webapp to be deployed: - -[source, screen, subs="{sub-order}"] ----- -> JETTY_BASE=/tmp/mybase -> mkdir $JETTY_BASE -> cd $JETTY_BASE -> java -jar $JETTY_HOME/start.jar - -WARNING: Nothing to start, exiting ... - -Usage: java -jar start.jar [options] [properties] [configs] - java -jar start.jar --help # for more information - -> java -jar $JETTY_HOME/start.jar --create-startd -INFO : Base directory was modified -> java -jar $JETTY_HOME/start.jar --add-to-start=http,deploy - -INFO: server initialised (transitively) in ${jetty.base}/start.d/server.ini -INFO: http initialised in ${jetty.base}/start.d/http.ini -INFO: security initialised (transitively) in ${jetty.base}/start.d/security.ini -INFO: servlet initialised (transitively) in ${jetty.base}/start.d/servlet.ini -INFO: webapp initialised (transitively) in ${jetty.base}/start.d/webapp.ini -INFO: deploy initialised in ${jetty.base}/start.d/deploy.ini -MKDIR: ${jetty.base}/webapps -INFO: Base directory was modified - -> cp $JETTY_HOME/demo-base/webapps/async-rest.war webapps/ROOT.war -> java -jar $JETTY_HOME/start.jar - -2015-06-04 11:10:16.286:INFO::main: Logging initialized @274ms -2015-06-04 11:10:16.440:INFO:oejs.Server:main: jetty-9.3.0.v20150601 -2015-06-04 11:10:16.460:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:///tmp/mybase/webapps/] at interval 1 -2015-06-04 11:10:16.581:WARN::main: async-rest webapp is deployed. DO NOT USE IN PRODUCTION! -2015-06-04 11:10:16.589:INFO:oejw.StandardDescriptorProcessor:main: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet -2015-06-04 11:10:16.628:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@1a407d53{/,[file:///tmp/jetty-0.0.0.0-8080-ROOT.war-_-any-4510228025526425427.dir/webapp/, jar:file:///tmp/jetty-0.0.0.0-8080-ROOT.war-_-any-4510228025526425427.dir/webapp/WEB-INF/lib/example-async-rest-jar-{VERSION}.jar!/META-INF/resources],AVAILABLE}{/ROOT.war} -2015-06-04 11:10:16.645:INFO:oejs.ServerConnector:main: Started ServerConnector@3abbfa04{HTTP/1.1,[http/1.1]}{0.0.0.0:8080} -2015-06-04 11:10:16.646:INFO:oejs.Server:main: Started @634ms ----- - -[[quickstart-changing-jetty-port]] -==== Changing the Jetty Port - -You can configure Jetty to run on a different port by setting the `jetty.http.port` property on the command line: - -[source, screen, subs="{sub-order}"] ----- -> cd $JETTY_BASE -> java -jar $JETTY_HOME/start.jar jetty.http.port=8081 -... ----- - -When the server starts, it will now run on port `8081`. -It is important to note that setting properties on the command line will only take affect for that instance of the server. -To change the configuration so that the server will always start on the desired port, you will need to edit the `start.d/http.ini` - -____ -[NOTE] --- -The configuration by properties works via the following chain: - -* The `start.d/http.ini` file is part of the effective command line and contains the `--module=http` argument which activates the http module. -* The `modules/http.mod` file defines the http module which specifies the `etc/jetty-http.xml` configuration file and the template ini properties it uses. -* The `jetty.http.port` property is used by the Property XML element in `etc/jetty.http.xml` to inject the `ServerConnector` instance with the port. - -For more information see the link:#quick-start-configure[Quickstart Configuration Guide] and link:#configuring-connectors[Configuring Connectors]. --- -____ - -[[quickstart-starting-https]] -==== Adding SSL for HTTPS & HTTP2 - -Building on the example above, we can activate additional modules to add support HTTPS and HTTP2 for the server. -To add HTTPS and HTTP2 connectors to a Jetty configuration, the modules can be activated by the following command: - -[source, screen, subs="{sub-order}"] ----- -> java -jar $JETTY_HOME/start.jar --add-to-start=https,http2 - -ALERT: There are enabled module(s) with licenses. -The following 1 module(s): - + contains software not provided by the Eclipse Foundation! - + contains software not covered by the Eclipse Public License! - + has not been audited for compliance with its license - - Module: alpn-impl/alpn-8 - + ALPN is a hosted at github under the GPL v2 with ClassPath Exception. - + ALPN replaces/modifies OpenJDK classes in the sun.security.ssl package. - + http://github.com/jetty-project/jetty-alpn - + http://openjdk.java.net/legal/gplv2+ce.html - -Proceed (y/N)? y -INFO : alpn-impl/alpn-1.8.0_92 dynamic dependency of alpn-impl/alpn-8 -INFO : alpn transitively enabled, ini template available with --add-to-start=alpn -INFO : alpn-impl/alpn-8 dynamic dependency of alpn -INFO : http2 initialized in ${jetty.base}/start.d/http2.ini -INFO : https initialized in ${jetty.base}/start.d/https.ini -INFO : ssl transitively enabled, ini template available with --add-to-start=ssl -MKDIR : ${jetty.base}/lib/alpn -DOWNLD: https://repo1.maven.org/maven2/org/mortbay/jetty/alpn/alpn-boot/8.1.8.v20160420/alpn-boot-8.1.8.v20160420.jar to ${jetty.base}/lib/alpn/alpn-boot-8.1.8.v20160420.jar -MKDIR : ${jetty.base}/etc -COPY : ${jetty.home}/modules/ssl/keystore to ${jetty.base}/etc/keystore -INFO : Base directory was modified - -> java -jar $JETTY_HOME/start.jar -[...] -2017-05-22 12:48:23.271:INFO:oejs.AbstractConnector:main: Started ServerConnector@134d0064{SSL,[ssl, alpn, h2, http/1.1]}{0.0.0.0:8443} -[...] ----- - -The `--add-to-start` command sets up the effective command line in the ini files to run an ssl connection that supports the HTTPS and HTTP2 protocols as follows: - -* transitively enabled the `ssl` module that configures an SSL connector (eg port, keystore etc.) by adding `etc/jetty-ssl.xml` and `etc/jetty-ssl-context.xml` to the effective command line. -* transitively enabled the `alpn` module that configures protocol negotiation on the SSL connector by adding `etc/jetty-alpn.xml` to the effective command line. -* creates `start.d/https.ini` that configures the HTTPS protocol on the SSL connector by adding `etc/jetty-https.xml` to the effective command line. -* creates `start.d/http2.ini` that configures the HTTP/2 protocol on the SSL connector by adding `etc/jetty-http2.xml` to the effective command line. -* checks for the existence of a `etc/keystore` file and if not present, downloads a demonstration keystore file. - -[[quickstart-changing-https-port]] -===== Changing the Jetty HTTPS Port - -You can configure the SSL connector to run on a different port by setting the `jetty.ssl.port` property on the command line: - -[source, screen, subs="{sub-order}"] ----- -> cd $JETTY_BASE -> java -jar $JETTY_HOME/start.jar jetty.ssl.port=8444 ----- - -Alternatively, property values can be added to the effective command line built from the `start.ini` file or `start.d/*.ini` files, depending on your set up. -Please see the section on link:#start-vs-startd[Start.ini vs. Start.d] for more information. - -==== More start.jar Options - -The job of the `start.jar` is to interpret the command line, `start.ini` and `start.d` directory (and associated .ini files) to build a Java classpath and list of properties and configuration files to pass to the main class of the Jetty XML configuration mechanism. -The `start.jar` mechanism has many options which are documented in the xref:startup[] administration section and you can see them in summary by using the command: - -[source, screen, subs="{sub-order}"] ----- -> java -jar $JETTY_HOME/start.jar --help ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-installing.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-installing.adoc deleted file mode 100644 index dafffe55eec8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-installing.adoc +++ /dev/null @@ -1,94 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-downloading]] -=== Downloading Jetty - -==== Downloading the Jetty Distribution - -The standalone Jetty distribution is available for download from the Eclipse Foundation: -____ -*Jetty* -https://jetty.org/download.html -____ - -It is available in both zip and gzip formats; download the one most appropriate for your system. -When you download and unpack the binary, it is extracted into a directory called `jetty-home-VERSION.` -Put this directory in a convenient location. -The rest of the instructions in this documentation refer to this location as either `$JETTY_HOME` or as `$(jetty.home).` - -_____ -[IMPORTANT] -It is important that *only* stable releases are used in production environments. -Versions that have been deprecated or are released as Milestones (M) or Release Candidates (RC) are *not* suitable for production as they may contain security flaws or incomplete/non-functioning feature sets. -_____ - -[[distribution-content]] -===== Distribution Content - -A summary of the distribution's contents follows. -The top-level directory contains: - -.Contents -[width="80%",cols="40%,60%",options="header"] -|======================================================================= -|Location |Description |license-eplv10-aslv20.html |License file for Jetty -|README.txt |Useful getting started information -|VERSION.txt |Release information -|bin/ |Utility shell scripts to help run Jetty on Unix systems -|demo-base/ |A Jetty base directory to run a Jetty server with demonstration webapps -|etc/ |Directory for Jetty XML configuration files -|lib/ |All the JAR files necessary to run Jetty -|logs/ |Directory for request logs -|modules/ |Directory of module definitions -|notice.html |License information and exceptions -|resources/ |Directory containing additional resources for classpath, activated via configuration -|start.ini |File containing the arguments that are added to the effective command line (modules, properties and XML configuration files) -|start.jar |Jar that invokes Jetty (see also xref:quickstart-running-jetty[]) -|webapps/ |Directory containing webapps that run under the default configuration of Jetty -|======================================================================= - -[[jetty-home-downloading]] -==== Downloading the Jetty-Home Distribution - -Jetty-Home is an alternate version of the distribution that contains only the necessary items to host a Jetty distribution. -It is intended for advanced users who are already familiar with Jetty and want to download a smaller distribution package. -Jetty-Home can be downloaded from the Maven Central repository: - -____ -*Jetty-Home* -https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-home/ -____ - -Like the main Jetty distribution, Jetty-Home is available in both zip and gzip formats; download the one most appropriate for your system. -Notice that there are a number of other files with extensions of .sha or .md5 which are checksum files. -When you download and unpack the binary, it is extracted into a directory called `jetty-home-VERSION.` -Put this directory in a convenient location. - -[[jetty-home-distribution-content]] -===== Distribution Content - -A summary of the Jetty-Home's distribution contents follows. -The top-level directory contains: - -.Contents -[width="80%",cols="40%,60%",options="header"] -|======================================================================= -|Location |Description |license-eplv10-aslv20.html |License file for Jetty -|VERSION.txt |Release information -|etc/ |Directory for Jetty XML configuration files -|lib/ |All the JAR files necessary to run Jetty -|modules/ |Directory of module definitions -|notice.html |License information and exceptions -|start.jar |Jar that invokes Jetty (see also xref:quickstart-running-jetty[]) -|======================================================================= diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-running.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-running.adoc deleted file mode 100644 index 89e33a2326c1..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/getting-started/jetty-running.adoc +++ /dev/null @@ -1,121 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[quickstart-running-jetty]] -=== Running Jetty - -Once you have a copy of the Jetty distribution downloaded, extract the `zip` or `tar.gz` file to a location where you have read and write access. -Jetty has no GUI (Graphical User Interface), so running the server and performing many configuration options is done from the command line. - -Once you have access to your system's command line, navigate to the directory where you unpacked your copy of the Jetty distribution. -To start Jetty on the default port of 8080, run the following command: - -[source,screen,subs="{sub-order}"] ----- -$ java -jar start.jar -2017-09-20 15:45:11.986:INFO::main: Logging initialized @683ms to org.eclipse.jetty.util.log.StdErrLog -2017-09-20 15:45:12.197:WARN:oejs.HomeBaseWarning:main: This instance of Jetty is not running from a separate {jetty.base} directory, this is not recommended. See documentation at https://jetty.org/docs/ -2017-09-20 15:45:12.243:INFO:oejs.Server:main: {VERSION} -2017-09-20 15:45:12.266:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:///installs/repository/jetty/webapps/] at interval 1 -2017-09-20 15:45:12.298:INFO:oejs.AbstractConnector:main: Started ServerConnector@39c0f4a{HTTP/1.1,[http/1.1]}{0.0.0.0:8080} -2017-09-20 15:45:12.298:INFO:oejs.Server:main: Started @995ms ----- - -You can point a browser at this server at link:http://localhost:8080[]. -However, as there are no webapps deployed in the `$JETTY_HOME` directory, you will see a 404 error page served by Jetty. -To stop the server, press `CTRL` + `c` or `CTRL` + `z` in your terminal. - -*Note* the `HomeBaseWarning` - it is *not* recommended to run Jetty from the `$JETTY_HOME` directory. -Instead, see how to link:#creating-jetty-base[create a Jetty Base] below. - -____ -[NOTE] -You will see examples throughout the documentation referencing `$JETTY_HOME` and `$JETTY_BASE` as well as `{jetty.home}` and `{jetty.base}`. -These terms are used to refer to the location of your Jetty installation directories. -Many users find it helpful to define `$JETTY_HOME` as an environment variable that maps to their Jetty distribution directory. -More information can be found in our Administration section on link:#startup-base-and-home[managing Jetty Home and Jetty Base.] -____ - -[[demo-webapps-base]] -==== Demo Base - -Within the standard Jetty distribution there is the `demo-base` directory. -This is a fully-functioning Jetty Base (more on that later) complete with numerous web applications demonstrating different Jetty functionality. -Additionally, the `demo-base` demonstrates the recommended way to run a Jetty base in a directory separate from `$JETTY_HOME`: - -[source,screen,subs="{sub-order}"] ----- -$ cd demo-base/ -[my-base]$ java -jar /path/to/jetty-home/start.jar -2017-09-20 16:23:03.563:INFO::main: Logging initialized @429ms to org.eclipse.jetty.util.log.StdErrLog -2017-09-20 16:23:03.802:WARN::main: demo test-realm is deployed. DO NOT USE IN PRODUCTION! -2017-09-20 16:23:03.804:INFO:oejs.Server:main: {VERSION} -2017-09-20 16:23:03.819:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:///installs/repository/jetty/demo-base/webapps/] at interval 1 -2017-09-20 16:23:04.098:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=102ms -2017-09-20 16:23:04.103:WARN::main: async-rest webapp is deployed. DO NOT USE IN PRODUCTION! -2017-09-20 16:23:04.267:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0 -2017-09-20 16:23:04.267:INFO:oejs.session:main: No SessionScavenger set, using defaults -2017-09-20 16:23:04.268:INFO:oejs.session:main: Scavenging every 660000ms -2017-09-20 16:23:04.306:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@371a67ec{/async-rest,[file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-async-rest.war-_async-rest-any-5319296087878801290.dir/webapp/, jar:file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-async-rest.war-_async-rest-any-5319296087878801290.dir/webapp/WEB-INF/lib/example-async-rest-jar-{VERSION}.jar!/META-INF/resources],AVAILABLE}{/async-rest.war} -2017-09-20 16:23:04.429:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=53ms -2017-09-20 16:23:04.432:WARN::main: test webapp is deployed. DO NOT USE IN PRODUCTION! -2017-09-20 16:23:04.516:INFO:oejsh.ManagedAttributeListener:main: update QoSFilter null->org.eclipse.jetty.servlets.QoSFilter@7770f470 on o.e.j.w.WebAppContext@35e2d654{/test,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test.war-_test-any-6279588879522983394.dir/webapp/,STARTING}{/test.war} -2017-09-20 16:23:04.519:WARN:oeju.DeprecationWarning:main: Using @Deprecated Class org.eclipse.jetty.servlets.MultiPartFilter -2017-09-20 16:23:04.549:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@35e2d654{/test,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test.war-_test-any-6279588879522983394.dir/webapp/,AVAILABLE}{/test.war} -2017-09-20 16:23:04.646:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=12ms -2017-09-20 16:23:04.649:WARN::main: test-jndi webapp is deployed. DO NOT USE IN PRODUCTION! -2017-09-20 16:23:04.697:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@561b6512{/test-jndi,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test-jndi.war-_test-jndi-any-6023636263414992288.dir/webapp/,AVAILABLE}{/test-jndi.war} -2017-09-20 16:23:04.770:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=40ms -2017-09-20 16:23:05.036:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@2beee7ff{/proxy,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-javadoc-proxy.war-_javadoc-proxy-any-2758874759195597975.dir/webapp/,AVAILABLE}{/javadoc-proxy.war} -2017-09-20 16:23:05.072:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=16ms -2017-09-20 16:23:05.074:WARN::main: test-jaas webapp is deployed. DO NOT USE IN PRODUCTION! -2017-09-20 16:23:05.098:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@506ae4d4{/test-jaas,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test-jaas.war-_test-jaas-any-8067423971450448377.dir/webapp/,AVAILABLE}{/test-jaas.war} -2017-09-20 16:23:05.182:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=37ms -2017-09-20 16:23:05.184:WARN::main: test-spec webapp is deployed. DO NOT USE IN PRODUCTION! -2017-09-20 16:23:05.243:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@45099dd3{/test-spec,[file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test-spec.war-_test-spec-any-1205866915335004234.dir/webapp/, jar:file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test-spec.war-_test-spec-any-1205866915335004234.dir/webapp/WEB-INF/lib/test-web-fragment-{VERSION}.jar!/META-INF/resources],AVAILABLE}{/test-spec.war} -2017-09-20 16:23:05.247:INFO:oejsh.ContextHandler:main: Started o.e.j.s.h.MovedContextHandler@3e08ff24{/oldContextPath,null,AVAILABLE} -2017-09-20 16:23:05.274:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=18ms -2017-09-20 16:23:05.296:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@5ddeb7cb{/,file:///installs/repository/jetty/demo-base/webapps/ROOT/,AVAILABLE}{/ROOT} -2017-09-20 16:23:05.326:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=21ms -2017-09-20 16:23:05.352:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@6b695b06{/doc,file:///installs/repository/jetty/demo-base/webapps/doc/,AVAILABLE}{/doc} -2017-09-20 16:23:05.370:INFO:oejs.AbstractConnector:main: Started ServerConnector@28cda624{HTTP/1.1,[http/1.1]}{0.0.0.0:8080} -2017-09-20 16:23:05.380:INFO:oejus.SslContextFactory:main: x509=X509@126253fd(jetty,h=[jetty.eclipse.org],w=[]) for SslContextFactory@57db2b13(file:///installs/repository/jetty/demo-base/etc/keystore,file:///installs/repository/jetty/demo-base/etc/keystore) -2017-09-20 16:23:05.381:INFO:oejus.SslContextFactory:main: x509=X509@475c9c31(mykey,h=[],w=[]) for SslContextFactory@57db2b13(file:///installs/repository/jetty/demo-base/etc/keystore,ffile:///installs/repository/jetty/demo-base/etc/keystore) -2017-09-20 16:23:05.523:INFO:oejs.AbstractConnector:main: Started ServerConnector@53f3bdbd{SSL,[ssl, http/1.1]}{0.0.0.0:8443} -2017-09-20 16:23:05.524:INFO:oejs.Server:main: Started @2390ms ----- - -You can visit this demo server by pointing a browser at link:http://localhost:8080[], which will now show a welcome page and several demo/test web applications. - -____ -[WARNING] -The demonstration web applications are not necessarily secure and should *not* be deployed in production web servers. -____ - -You can see the configuration of the `demo-base` by using the following commands: - -[source, screen, subs="{sub-order}"] ----- -> cd $JETTY_HOME/demo-base/ -> java -jar $JETTY_HOME/start.jar --list-modules -... - -> java -jar $JETTY_HOME/start.jar --list-config -... ----- - -The `--list-modules` command will return a complete list of available and enabled modules for the server. -It will also display the location of the modules, how and in what order they are implemented, dependent modules, and associated jar files. - -The `--list-config` command displays a trove of information about the server including the Java and Jetty environments, the configuration order, any JVM arguments or System Properties set, general server properties, a full listing of the Jetty server class path, and active Jetty XML files. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/chapter.adoc deleted file mode 100644 index 046f970eb76c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/chapter.adoc +++ /dev/null @@ -1,20 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[introduction]] -== Introducing Jetty - -include::what-is-jetty.adoc[] -include::what-version.adoc[] -include::jetty-javaee.adoc[] -include::jetty-coordinates.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/jetty-coordinates.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/jetty-coordinates.adoc deleted file mode 100644 index add6e26fa575..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/jetty-coordinates.adoc +++ /dev/null @@ -1,56 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[quickstart-jetty-coordinates]] -=== Finding Jetty in Maven - -_____ -[IMPORTANT] -It is important that only stable releases are used in production environments. -Versions that have been deprecated or are released as Milestones (M) or Release Candidates (RC) are not suitable for production as they may contain security flaws or incomplete/non-functioning feature sets. -_____ - -==== Maven Coordinates - -Jetty has existed in Maven Central almost since its inception, though the coordinates have changed over the years. -When Jetty was based at SourceForge and then The Codehaus it was located under the `groupId` of `org.mortbay.jetty`. -With Jetty 7 the project moved to the Eclipse foundation and to a new `groupId` at that time to reflect its new home. - -The top level Project Object Model (POM) for the Jetty project is located under the following coordinates. - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty - jetty-project - ${project.version} - ----- - -==== Changelogs in Maven Central - -The changes between versions of Jetty are tracked in a file called VERSIONS.txt, which is under source control and is generated on release. -Those generated files are also uploaded into Maven Central during the release of the top level POM. You can find them as a classifier marked artifact. - -https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-project/ - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty - jetty-project - ${project.version} - version - txt - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/jetty-javaee.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/jetty-javaee.adoc deleted file mode 100644 index 2efe30f051a1..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/jetty-javaee.adoc +++ /dev/null @@ -1,104 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-javaee]] -=== Jetty and Java EE Web Profile - -Jetty implements aspects of the Java EE specification, primarily the Servlet Specification. -Recent releases of the Java EE platform have introduced a Web Profile, recognizing that many developers need only a subset of the many technologies under the Java EE umbrella. - -While Jetty itself does not ship all of the Web Profile technologies, Jetty architecture is such that you can plug in third party implementations to produce a container customized to your exact needs. - -[[jetty-javaee-7]] -==== Java EE 7 Web Profile - -In the forthcoming Java EE-7 specification, the Web Profile reflects updates in its component specifications and adds some new ones: - -.JavaEE7 Web Profile -[cols=",,,",options="header",] -|======================================================================= -|JSR |Name |Included with jetty-9.1.x |Pluggable - -|http://jcp.org/en/jsr/detail?id=340[JSR 340] |Servlet Specification API 3.1 |Yes | - -|http://jcp.org/en/jsr/detail?id=344[JSR 344] |Java Server Faces 2.2 (JSF) |No |Yes, https://javaserverfaces.java.net/[Mojarra] or http://myfaces.apache.org/[MyFaces] - -|http://jcp.org/en/jsr/detail?id=245[JSR 245] / http://jcp.org/en/jsr/detail?id=341[JSR 341] |Java Server Pages 2.3/Java Expression Language 3.0 (JSP/EL) |Yes |Yes - -|http://jcp.org/en/jsr/detail?id=52[JSR 52] |Java Standard Tag Library 1.2 (JSTL) |Yes |Yes - -|http://jcp.org/en/jsr/detail?id=45[JSR 45] |Debugging Support for Other Languages 1.0 |Yes (via JSP) |Yes (via JSP) - -|http://jcp.org/en/jsr/detail?id=346[JSR 346] |Contexts and Dependency Injection for the JavaEE Platform 1.1 (Web Beans) |No |Yes, http://seamframework.org/Weld[Weld] - -|http://jcp.org/en/jsr/detail?id=330[JSR 330] |Dependency Injection for Java 1.0 |No |Yes as part of a CDI implementation, http://seamframework.org/Weld[Weld] - -|http://jcp.org/en/jsr/detail?id=316[JSR 316] |Managed Beans 1.0 |No |Yes, as part of another technology - -|http://jcp.org/en/jsr/detail?id=345[JSR 345] |Enterprise JavaBeans 3.2 Lite |No | - -|http://jcp.org/en/jsr/detail?id=338[JSR 338] |Java Persistence 2.1 (JPA) |No |Yes, eg http://www.hibernate.org/[Hibernate] - -|http://jcp.org/en/jsr/detail?id=250[JSR 250] |Common Annotations for the Java Platform 1.2 |Yes |Partially (for non-core Servlet Spec annotations) - -|http://jcp.org/en/jsr/detail?id=907[JSR 907] |Java Transaction API 1.2 (JTA) |Yes |Yes - -|http://jcp.org/en/jsr/detail?id=349[JSR 349] |Bean Validation 1.1 |No |Yes as part of another technology eg JSF, or a stand-alone implementation such as http://www.hibernate.org/subprojects/validator/docs.html[Hiberate -Validator] - -|http://jcp.org/en/jsr/detail?id=339[JSR 339] |Java API for RESTful Web Services 2.0 (JAX-RS) |No | - -|http://jcp.org/en/jsr/detail?id=356[JSR 356] |Java API for Websocket 1.0 |Yes |No - -|http://jcp.org/en/jsr/detail?id=353[JSR 353] |Java API for JSON Processing 1.0 (JSON-P) |No |Yes, eg JSON-P https://java.net/projects/jsonp/[reference implementation] - -|http://jcp.org/en/jsr/detail?id=318[JSR 318] |Interceptors 1.2 |No |Yes as part of a CDI implementation -|======================================================================= - -[[jetty-javaee-6]] -==== Jetty EE 6 Web Profile - -Here is the matrix of JSRs for Java EE 6 Web Profile, and how they relate to Jetty: - -.Java EE 6 Web Profile -[cols=",,,",options="header",] -|======================================================================= -|JSR |Name |Included with jetty-9.0.x |Pluggable - -|http://jcp.org/en/jsr/detail?id=315[JSR 315] |Servlet Specification API 3.0 |Yes | - -|http://jcp.org/en/jsr/detail?id=314[JSR 314] |JavaServer Faces 2.0 (JSF) |No |Yes, for example, https://javaserverfaces.java.net/[Mojarra] or http://myfaces.apache.org/[MyFaces] - -|http://jcp.org/en/jsr/detail?id=245[JSR 245] |JavaServer Pages 2.2/Java Expression Language 2.2 (JSP/EL) |Yes |Yes - -|http://jcp.org/en/jsr/detail?id=52[JSR 52] |Java Standard Tag Library 1.2 (JSTL) |Yes |Yes - -|http://jcp.org/en/jsr/detail?id=45[JSR 45] |Debugging Support for Other Languages 1.0 |Yes (via JSP) |Yes (via JSP) - -|http://jcp.org/en/jsr/detail?id=299[JSR 299] |Contexts and Dependency Injection for the Java EE Platform 1.0 (Web Beans) |No |Yes, http://seamframework.org/Weld[Weld] or http://openwebbeans.apache.org/[OpenWebBeans] - -|http://jcp.org/en/jsr/detail?id=330[JSR 330] |Dependency Injection for Java 1.0 |No |Yes as part of a CDI implementation, http://seamframework.org/Weld[Weld] - -|http://jcp.org/en/jsr/detail?id=316[JSR 316] |Managed Beans 1.0 |No |Yes, as part of another technology. - -|http://jcp.org/en/jsr/detail?id=318[JSR 318] |Enterprise JavaBeans 3.1 |No |Yes, OpenEJB - -|http://jcp.org/en/jsr/detail?id=317[JSR 317] |Java Persistence 2.0 (JPA) |No |Yes, http://www.hibernate.org/[Hibernate] - -|http://jcp.org/en/jsr/detail?id=250[JSR 250] |Common Annotations for the Java Platform |Yes |Partially (for non-core Servlet Spec annotations) - -|http://jcp.org/en/jsr/detail?id=907[JSR 907] |Java Transaction API (JTA) |Yes |Implementations are pluggable, such as http://www.atomikos.com/[Atomikos], http://jotm.ow2.org/[JOTM], http://jencks.codehaus.org/Transaction+Manager[Jencks (Geronimo Transaction Manager)] - -|http://jcp.org/en/jsr/detail?id=303[JSR 303] |Bean Validation 1.0 |No |Yes as part of another technology (JSF), or a stand-alone implementation such as http://www.hibernate.org/subprojects/validator/docs.html[Hiberate -Validator] -|======================================================================= diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/what-is-jetty.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/what-is-jetty.adoc deleted file mode 100644 index b232ff4a3be5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/what-is-jetty.adoc +++ /dev/null @@ -1,36 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[what-is-jetty]] -=== What is Jetty? - -Eclipse Jetty is an open-source project providing an HTTP server, HTTP client, and servlet container. - -The Jetty documentation is broken up in to four parts: - -* The link:{GSTARTEDGUIDE}[Getting Started Guide] emphasizes beginning to use Jetty. -It provides information about what Jetty is and where you can download it, and where to find Jetty in repositories like Central Maven. -It also provides a Quick Start guide on how to get Jetty up and running as well as an overview of how and what to configure in Jetty. - -* The link:{OPGUIDE}[Operations Guide] details configuring Jetty as a distributed package at a more granular level. -From server startup to session management, logging, HTTP/2 support and Jetty optimization, these chapters will help administrators get the most out of their distributed Jetty server instances. -This section also covers configuring many of the most common servlet container features such as JNDI and JMX. - -* Aimed at advanced users of Jetty, the link:{PROGGUIDE}[Programming Guide] focuses on Jetty development. -A large portion of this section is focused on using Jetty as an embedded server in existing applications. -It contains several examples and how-to guides for making the most out of the Jetty framework. -This section also includes a guide on using the Jetty Maven plugin as well as information on debugging Jetty. - -* The link:#{CONTRIBGUIDE}[Contribution Guide] is aimed at those who want to contribute to the Jetty open source project. -It includes instructions on interacting with the community, how to raise bugs, and how to report security issues. -In addition, it also details source control and build information for the project. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/what-version.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/what-version.adoc deleted file mode 100644 index 8adfc0a5a691..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/introduction/what-version.adoc +++ /dev/null @@ -1,50 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[what-jetty-version]] -=== What Version Do I Use? - -Jetty 10 and 11 are the most recent versions of Jetty and has a great many improvements over previous versions. -This documentation which focuses on Jetty 10. -While many people continue to use older versions of Jetty, we generally recommend using Jetty 10 or 11 (more on the differences later) as they represent the version of Jetty that we will actively maintain and improve over the next few years. - -_____ -[IMPORTANT] -It is important that only stable releases are used in production environments. -Versions that have been deprecated or are released as Milestones (M) or Release Candidates (RC) are not suitable for production as they may contain security flaws or incomplete/non-functioning feature sets. -_____ - -.Jetty Versions -[width="100%",cols="12%,9%,15%,6%,21%,10%,6%,21%",options="header",] -|======================================================================= -|Version |Year |Home |Min JVM |Protocols |Servlet |JSP |Status -|11 |2020- |Eclipse |11 ^(2)^ |HTTP/1.1 (RFC 7230), HTTP/2 (RFC 7540), WebSocket (RFC 6455, JSR 356), FastCGI, *JakartaEE Namespace*^(1)^ |5.0.0 |3.0.0 |Stable -|10 |2019- |Eclipse |11 ^(2)^ |HTTP/1.1 (RFC 7230), HTTP/2 (RFC 7540), WebSocket (RFC 6455, JSR 356), FastCGI |4.0.1 |2.2 |Stable -|9.4 |2016- |Eclipse |1.8 |HTTP/1.1 (RFC 7230), HTTP/2 (RFC 7540), WebSocket (RFC 6455, JSR 356), FastCGI |3.1 |2.3 |Stable -|9.3 |2015- |Eclipse |1.8 ^(3)^ |HTTP/1.1 (RFC 7230), HTTP/2 (RFC 7540), WebSocket (RFC 6455, JSR 356), FastCGI |3.1 |2.3 |Deprecated / *End of Life December 2020* -|9.2 |2014-2018 |Eclipse |1.7 ^(3)^ |HTTP/1.1 RFC2616, javax.websocket, SPDY v3 |3.1 |2.3 |Deprecated / *End of Life January 2018* -|9.1 |2013-2014 |Eclipse |1.7 ^(3)^ |HTTP/1.1 RFC2616 |3.1 |2.3 |Deprecated / *End of Life May 2014* -|9.0 |2013-2013 |Eclipse |1.7 ^(3)^ |HTTP/1.1 RFC2616 |3.1-beta |2.3 |Deprecated / *End of Life November 2013* -|8 |2009-2014 |Eclipse/Codehaus |1.6 ^(3)^ |HTTP/1.1 RFC2616, WebSocket RFC 6455, SPDY v3 |3.0 |2.2 |Deprecated / *End of Life November 2014* -|7 |2008-2014 |Eclipse/Codehaus |1.5 |HTTP/1.1 RFC2616, WebSocket RFC 6455, SPDY v3 |2.5 |2.1 |Deprecated / *End of Life November 2014* -|6 |2006-2010 |Codehaus |1.4-1.5 |HTTP/1.1 RFC2616 |2.5 |2.0 |Deprecated / *End of Life November 2010* -|5 |2003-2009 |Sourceforge |1.2-1.5 |HTTP/1.1 RFC2616 |2.4 |2.0 |Antique -|4 |2001-2006 |Sourceforge |1.2, J2ME |HTTP/1.1 RFC2616 |2.3 |1.2 |Ancient -|3 |1999-2002 |Sourceforge |1.2 |HTTP/1.1 RFC2068 |2.2 |1.1 |Fossilized -|2 |1998-2000 |Mortbay |1.1 |HTTP/1.0 RFC1945 |2.1 |1.0 |Legendary -|1 |1995-1998 |Mortbay |1.0 |HTTP/1.0 RFC1945 |- |- |Mythical -|======================================================================= - - 1. Due to Oracle's ownership of the "Java" trademark, usage of the javax.* namespace has been restricted and the jakarta.* namespace link:https://www.eclipse.org/lists/jakartaee-platform-dev/msg00029.html[was adopted] by the Eclipse Foundation. - 2. JPMS module support is optional - 3. JDK9 and newer is not supported if using MultiRelease JAR Files, or Bytecode / Annotation scanning. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/chapter.adoc deleted file mode 100644 index e9e0d298db80..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/chapter.adoc +++ /dev/null @@ -1,17 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[upgrading-jetty]] -== Upgrading Jetty - -include::upgrading-from-jetty-9.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/sample.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/sample.adoc deleted file mode 100644 index 611404806771..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/sample.adoc +++ /dev/null @@ -1,20 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -= Sample Title - -This is a sample paragraph. - -== Sample Subsection - -More sample text. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/upgrading-9.3-to-9.4.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/upgrading-9.3-to-9.4.adoc deleted file mode 100644 index 35863e2cdaa8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/upgrading-9.3-to-9.4.adoc +++ /dev/null @@ -1,259 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -=== Upgrading from Jetty 9.3.x to Jetty 9.4.0 - -The purpose of this guide is to assist users migrating from Jetty 9.3.x to 9.4.0. -It is not comprehensive, but covers many of the major changes included in the release that may prove as problem areas for users. - -==== The jetty.sh Script - -The file `jetty.sh`, typically used to start Jetty as a service in Linux/Unix machines underwent only small changes, such as the addition of https://wiki.debian.org/LSBInitScripts[LSB tags]. - -You can safely replace the `jetty.sh` file packaged with Jetty 9.3 with the version found in Jetty 9.4. - -==== Removed Classes - -`ConcurrentArrayQueue` was removed from use in Jetty 9.3 and the class has been removed entirely as part of Jetty 9.4. - -==== Module Changes in Jetty 9.4 - -[cols="1,1", options="header"] -|=== -| Jetty 9.3 Module | Jetty 9.4 Module -| `logging` | `console-capture` -| `infinispan` | `session-store-infinispan-embedded` or `session-store-infinispan-remote` -| `jdbc-sessions` | `session-store-jdbc` -| `gcloud-memcached-sessions`, `gcloud-session-idmgr` and `gcloud-sessions` | `session-store-gcloud` and `session-store-cache` -| `nosql` | `session-store-mongo` -|=== - -===== Logging Modules - -The module `logging` is no longer available in Jetty 9.4. - -The logging module structure present in Jetty 9.3 has been replaced with a more fine-grained structure in Jetty 9.4, so that you have now more choices available that are also easier to configure. - -The migration path is different depending on whether you have completely customized this module or not. - -If you have a Jetty 9.3 installation, and you have both `$jetty.base/modules/logging.mod` and `$jetty.base/etc/jetty-logging.xml`, then this module is local to your `$jetty.base` setup and will be used by Jetty 9.4 as before. -No changes are required for your implementation. - -If either `$jetty.base/modules/logging.mod` or `$jetty.base/etc/jetty-logging.xml` are missing, then you were relying on those present in `$jetty.home`, which were present in Jetty 9.3, but are no longer available in Jetty 9.4. - -The Jetty 9.3 `logging` module has been renamed to `console-capture` in Jetty 9.4. -You need to open your Jetty 9.3 `start.ini` and replace the references to the `logging` modules with `console-capture`. - -For example, in an existing Jetty 9.3 `start.ini` file the module declaration for logging would look like this: - -[source, screen, subs="{sub-order}"] ----- ---module=logging -jetty.logging.retainDays=7 ----- - -In 9.4, it should be replaced by: - -[source, screen, subs="{sub-order}"] ----- ---module=console-capture -jetty.console-capture.retainDays=7 ----- - -The properties that may be present in your Jetty 9.3's `start.ini`, such as `jetty.logging.retainDays` will still be working in Jetty 9.4, but a warning will be printed at Jetty 9.4 startup, saying to replace them with correspondent `jetty.console-capture.*` properties such as `jetty.console-capture.retainDays`. - -For information on logging modules in the Jetty 9.4 architecture please see the section on link:#configuring-logging-modules[configuring logging modules.] - -==== Session Management - -Session management received a significant overhaul in Jetty 9.4. -Session functionality has been refactored to promote code-reuse, easier configuration and easier customization. -Whereas previously users needed to edit xml configuration files, in Jetty 9.4 all session behavior is controlled by properties that are exposed by the various session modules. -Users now configure session management by selecting a composition of session modules. - -===== Change Overview - -SessionIdManager:: Previously there was a different class of SessionIdManager - with different configuration options - depending upon which type of clustering technology chosen. -In Jetty 9.4, there is only one type, the link:{JDURL}/org/eclipse/jetty/server/session/DefaultSessionIdManager.html[org.eclipse.jetty.server.session.DefaultSessionIdManager]. - -SessionManager:: Previously, there was a different class of SessionManager depending upon which the type of clustering technology chosen. -In Jetty 9.4 we have removed the SessionManager class and split its functionality into different, more easily extensible and composable classes: -General setters::: -All of the common setup of sessions such as the maxInactiveInterval and session cookie-related configuration has been moved to the link:{JDURL}/org/eclipse/jetty/server/session/SessionHandler.html[org.eclipse.jetty.server.session.SessionHandler] - -[cols="1,1", options="header"] -|=== -| 9.3 SessionManager | 9.4 SessionHandler -| `setMaxInactiveInterval(sec)` | `setMaxInactiveInterval(sec)` -| `setSessionCookie(String)` | `setSessionCookie(String)` -| `setRefreshCookieAge(sec)` | `setRefreshCookieAge(sec)` -| `setSecureRequestOnly(boolean)` | `setSecureRequestOnly(boolean)` -| `setSessionIdPathParameterName(String)` | `setSessionIdPathParameterName(String)` -| `setSessionTrackingModes(Set)` | `setSessionTrackingModes(Set)` -| `setHttpOnly(boolean)` | `setHttpOnly(boolean)` -| `setUsingCookies(boolean)` | `setUsingCookies(boolean)` -| `setCheckingRemoteSessionIdEncoding(boolean)` | `setCheckingRemoteSessionIdEncoding(boolean)` -|=== - -Persistence::: -In Jetty 9.3 `SessionManagers` (and sometimes `SessionIdManagers`) implemented the persistence mechanism. -In Jetty 9.4 we have moved this functionality into the link:{JDURL}/org/eclipse/jetty/server/session/SessionDataStore.html[`org.eclipse.jetty.server.session.SessionDataStore`]. - -Session cache::: -In Jetty 9.3 the `SessionManager` held a map of session objects in memory. -In Jetty 9.4 this has been moved into the new link:{JDURL}/org/eclipse/jetty/server/session/SessionCache.html[`org.eclipse.jetty.server.session.SessionCache`] interface. - -For more information, please refer to the documentation on link:#jetty-sessions-architecture[Jetty Session Architecture.] - -===== Default Sessions - -As with earlier versions of Jetty, if you do not explicitly configure any session modules, the default session infrastructure will be enabled. -In previous versions of Jetty this was referred to as "hash" session management. -The new default provides similar features to the old hash session management: - -* A session scavenger thread that runs every 10mins and removes expired sessions -* A session id manager that generates unique session ids and handles session id sharing during context forwarding -* An in-memory cache of session objects. - -Requests for the same session in the same context share the same session object. -Session objects remain in the cache until they expire or are explicitly invalidated. - -If you wish to configure the default setup further, enable the `session-cache-hash` module. - -*Compatibility* - -As Session objects do not persist beyond a server restart, there are no compatibility issues. - - -===== Sessions using the Filesystem - -In earlier versions of Jetty, persisting sessions to the local filesystem was an option of the "hash" session manager. -In Jetty 9.4 this has been refactored to its own configurable module `session-store-file`. - -*Compatibility* - -Sessions stored to files by earlier versions of jetty are not compatible with jetty-9.4 sessions. -Here is a comparison of file formats, note that the file contents are listed in order of file output: - -[cols="1,1", options="header"] -|=== -| Jetty 9.3 | Jetty 9.4 -| File name: `sessionid` | File name: `expirytime_contextpath_vhost_sessionid` -| `sessionid (utf)` | `sessionid (utf)` -| | `contextpath (utf)` -| | `vhost (utf)` -| `nodeid (utf)` | `lastnode (utf)` -| `createtime (long)` | `createtime (long)` -| `accessed (long)` | `accessed (long)` -| | `lastaccessed (long)` -| | `cookiesettime (long)` -| | `expiry (long)` -| `requests (int)` | -| | `maxInactive (long)` -| `attributes size (int)` | `attributes size (int)` -| `attributes serialized (obj)` | `attributes serialized (obj)` -| `maxInactive (long)` | -|=== - -____ -[NOTE] -Session data is now only loaded when requested. -Previous functionality such as `setLazyLoad` has been removed. -____ - - -===== JDBC Sessions - -As with earlier versions of Jetty, sessions may be persisted to a relational database. -Enable the `session-store-jdbc` module. - -*Compatibility* - -Sessions stored to the database by earlier versions of jetty are not compatible with jetty-9.4 sessions. -The incompatibility is minor: in jetty-9.4 the `rowid` primary key column is no longer used, and the primary key is a composite of `(sessionid,contextpath,vhost)` columns. - -===== NoSQL Sessions - -As with earlier versions of Jetty, sessions may be persisted to a document database. -Jetty supports the Mongo document database. -Enable the `session-store-mongo` module. - - -*Compatibility* - -Sessions stored to mongo by earlier versions of jetty are not compatible with jetty-9.4 sessions. -The key for each subdocument that represents the session information for a context is different between jetty-9.3 and 9.4: - - -[cols="1,1", options="header"] -|=== -| Jetty 9.3 | Jetty 9.4 -|Each context key is: vhost+context+path, where empty vhosts="::" and root context = "*" and / is replaced by _ -|Each context key is: vhost:contextpath, where empty vhosts="0_0_0_0" and root context = "" and / replaced by _ -| eg "::/contextA" | eg " 0_0_0_0:_contextA" -|=== - - -===== Infinispan Sessions - -As with earlier versions of Jetty, sessions may be clustered via Infinispan to either an in-process or remote infinispan instance. -Enable the `session-store-infinispan` module. - -*Compatibility* - -Sessions stored in infinispan by jetty-9.3 are incompatible with jetty-9.4. -In Jetty 9.3 the serialized object stored to represent the session data was `org.eclipse.jetty.session.infinispan.SerializableSessionData`. -In Jetty 9.4 the serialized object is `org.eclipse.jetty.serer.session.SessionData`. - -===== GCloud Datastore - -As with earlier versions of Jetty, sessions may be persisted to Google's GCloud Datastore. -Enable the `session-store-gcloud` module. - -*Compatibility* - -Sessions stored into GCloud Datastore by Jetty 9.3 are *incompatible* with Jetty 9.4, although the incompatibility is trivial: the name of the session id entity property has changed: - -[cols="1,1", options="header"] -|=== -|Jetty 9.3 | Jetty 9.4 -|Kind: `GCloudSession` | Kind: `GCloudSession` -|key: `contextpath_vhost_sessionid` | key: `contextpath_vhost_sessionid` -|*"clusterId"*: `sessionId` | *"id"*: `sessionId` -|"contextPath" : `contextpath` | "contextPath": `contextpath` -|"vhost" : `vhost` | "vhost": `vhost` -|"accessed": `accesstime` | "accessed": `accesstime` -|"lastAccessed": `lastaccesstime` | "lastAccessed": `lastaccesstime` -|"createTime": `createtime` | "createTime": `createtime` -|"cookieSetTime": `cookiesettime` | "cookieSetTime": `cookiesettime` -|"lastNode": `lastnode` | "lastNode": `lastnode` -|"expiry": `expiry` | "expiry": `expiry` -|"maxInactive": `maxInactive` | "maxInactive": `maxInactive` -|"attributes": `blob` | "attributes": `blob` -|=== - -===== GCloud Datastore with Memcached - -As with earlier versions of Jetty, sessions can be both persisted to Google's GCloud Datastore, and cached into Memcached for faster access. -Enable the `session-store-gcloud` and `session-store-cache` modules. - -*Compatibility* - -Sessions stored into Memcached by earlier versions of jetty are incompatible with Jetty 9.4. -Previous versions of jetty stored `org.eclipse.jetty.gcloud.memcached.session.SerializableSessionData` whereas Jetty 9.4 stores `org.eclipse.jetty.server.session.SessionData`. - -==== ServletContainerInitializers - -As of Jetty-9.4.4, unless the `web.xml` is version 3.0 or greater, only `ServletContainerInitializers` that are on the container classpath will be discovered. -Users wishing to use `ServletContainerInitializers` from within the webapp with older versions of `web.xml` must either upgrade their `web.xml` version, or call `WebAppContext.setConfigurationDiscovered(true)` either programmatically or in xml. -Upgrading the `web.xml` version is preferable. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/upgrading-9.4-to.10.0.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/upgrading-9.4-to.10.0.adoc deleted file mode 100644 index 707a43fe4f8c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/gettingstarted/upgrading/upgrading-9.4-to.10.0.adoc +++ /dev/null @@ -1,58 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -=== Upgrading from Jetty 9.4.x to Jetty 10.0.x - -The purpose of this guide is to assist users migrating from Jetty 9.4 to 10. -It is not comprehensive, but covers many of the major changes included in the release that may prove as problem areas for users. - -==== Required Java Version - -Jetty 10 requires, at a minimum, Java 11 to function. -Items such as the Java Platform Module System (JPMS), which Jetty 10 supports, are not available in earlier versions of Java. - -==== ServletContainerInitializers - -As of Jetty 10, Annotations will be discovered even for old versions of `web.xml` (2.5). -Users wishing not to use annotations from the webapp classpath with older versions of `web.xml` must call `WebAppContext.setConfigurationDiscovered(false)` either programmatically or in xml. - -==== Removed Classes - -//TODO - Insert major removed/refactored classes from Jetty-9.x.x to Jetty-10.0.x - -==== Changes to Websocket - -//TODO - List of changes to Websocket -- Joakim/Lachlan - -==== `javax.mail` and `javax.transaction` - -Both `javax.mail` and `javax.transaction` have been removed from the Jetty Distribution in Jetty 10. -If you require these jars, you will need to enable the `ext` link:#startup-modules[module] and copy the files to your `$JETTY_BASE/lib/ext` directory. - -==== Module Changes in Jetty 10.0 - -===== New Modules in Jetty 10.0 - -//TODO - Insert new modules introduced in Jetty 10 - -===== Changes to Existing Modules in Jetty 10.0 - -//TODO - Insert module changes introduced in Jetty 10 - -==== Changes to Sessions - -//TODO - List of changes to Sessions -- Jan - -==== Removal of System Properties(?) - -//TODO - List of removed System bits --- Greg diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/http2/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/http2/chapter.adoc deleted file mode 100644 index 16606c777ad2..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/http2/chapter.adoc +++ /dev/null @@ -1,17 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[http2]] -== HTTP/2 - -include::configuring-push.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/http2/configuring-push.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/http2/configuring-push.adoc deleted file mode 100644 index a7d6824c0865..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/http2/configuring-push.adoc +++ /dev/null @@ -1,64 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[http2-configuring-push]] -=== Configuring HTTP/2 Push - -HTTP/2 Push is a spec deprecated 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 configuring a link:{JDURL}/org/eclipse/jetty/servlets/PushCacheFilter.html[`PushCacheFilter`] in the `web.xml`, in this way: - -[source, xml, subs="{sub-order}"] ----- - - - - ... - - PushFilter - org.eclipse.jetty.servlets.PushCacheFilter - true - - - PushFilter - /* - - ... - - ----- - -`PushCacheFilter` analyzes the HTTP requests for resources that arrive to your web application. -Some of these requests contain the HTTP `Referer` header that points to a resource that has been requested previously. - -This allows the `PushCacheFilter` to organize resources in a tree, for example a root `index.html` resource having two children resources, `styles.css` and `application.js`, and `styles.css` having a child resource, `background.png`. -The root resource is called the _primary_ resource, while descendant resources are called _secondary_ resources. - -The resource tree is built using a time window so that when a root resource is requested, only subsequent requests that are made within the time window will be added to the resource tree. -The resource tree can also be limited in size so that the number of secondary resources associated to a primary resource is limited. - -By default, only the resource _path_ (without the _query_ string) is used to associate secondary resources to the primary resource, but you can configure `PushCacheFilter` to take the query string into account. - -`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; defaults to 4000 ms -* `maxAssociations`: the max number of secondary resources that may be associated to a primary resource; defaults to 16 -* `hosts`: a comma separated list of hosts that are allowed in the `Referer` header; defaults to the host in the `Host` header -* `ports`: a comma separated list of ports that are allowed in the `Referer` header; defaults to the port in the `Host` header -* `useQueryInKey`: a boolean indicating whether the query string of the request should be considered when associating secondary resources to primary resources; defaults to `false` diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_AppLifeCycle-1.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_AppLifeCycle-1.png deleted file mode 100644 index 522551a7946b..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_AppLifeCycle-1.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_DefaultAppLifeCycleBindings.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_DefaultAppLifeCycleBindings.png deleted file mode 100644 index 9436817ac334..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_DefaultAppLifeCycleBindings.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_DeploymentManager_Roles.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_DeploymentManager_Roles.png deleted file mode 100644 index d37aefe7d8a2..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/Jetty_DeployManager_DeploymentManager_Roles.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/SessionsHierarchy.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/SessionsHierarchy.png deleted file mode 100644 index 90a543f95ac1..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/SessionsHierarchy.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-handlers.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-handlers.png deleted file mode 100644 index 47dd0e69bb28..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-handlers.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-nested-handlers.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-nested-handlers.png deleted file mode 100644 index 877400141d59..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-nested-handlers.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-patterns.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-patterns.png deleted file mode 100644 index 777eed91c15f..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-patterns.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-servlet-handler.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-servlet-handler.png deleted file mode 100644 index d8f2ea8e3cf9..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-servlet-handler.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-web-application.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-web-application.png deleted file mode 100644 index e5232a20d8e8..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/basic-architecture-web-application.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/certificate-chain.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/certificate-chain.png deleted file mode 100644 index 6d2a614526f0..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/certificate-chain.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-1.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-1.png deleted file mode 100644 index f6ebb055b940..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-1.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-2.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-2.png deleted file mode 100644 index c90e163997dd..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-2.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-3.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-3.png deleted file mode 100644 index df7f7280a061..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/debug-eclipse-3.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_debug_view.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_debug_view.png deleted file mode 100644 index ed034e40407c..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_debug_view.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_new_remote_config.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_new_remote_config.png deleted file mode 100644 index 0e031eefc80a..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_new_remote_config.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_select_debug.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_select_debug.png deleted file mode 100644 index d53984c5bdd7..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_select_debug.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_set_breakpoint.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_set_breakpoint.png deleted file mode 100644 index fc4eb9503916..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/intellij_set_breakpoint.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/jetty-high-level-architecture.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/jetty-high-level-architecture.png deleted file mode 100644 index 02bf6476bb20..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/jetty-high-level-architecture.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/modules-9.3-simplified.dot b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/modules-9.3-simplified.dot deleted file mode 100644 index b78647f17393..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/modules-9.3-simplified.dot +++ /dev/null @@ -1,254 +0,0 @@ -/* - * GraphViz Graph of Jetty Modules - * - * Jetty: https://jetty.org/ - * 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=< - -
server
>]; - "ext" [ color="#B8FFB8" label=< - -
ext
>]; - "jvm" [ color="#B8FFB8" label=< - -
jvm
>]; - "apache-jstl" [ color="#B8FFB8" label=< - -
apache-jstl
>]; - "client" [ color="#B8FFB8" label=< - -
client
>]; - "logging" [ color="#B8FFB8" label=< - -
logging
>]; - "resources" [ color="#B8FFB8" label=< - -
resources
>]; - "apache-jsp" [ color="#B8FFB8" label=< - -
apache-jsp
>]; - "protonego-boot" [ color="#B8FFB8" label=< - -
protonego-boot
>]; - } - - /* Level 1 */ - { rank = same; - "requestlog" [ color="#B8FFB8" label=< - -
requestlog
>]; - "servlet" [ color="#66FFCC" label=< - -
servlet
>]; - "gzip" [ color="#B8FFB8" label=< - -
gzip
>]; - "monitor" [ color="#B8FFB8" label=< - -
monitor
>]; - "rewrite" [ color="#B8FFB8" label=< - -
rewrite
>]; - "ssl" [ color="#B8FFB8" label=< - -
ssl
>]; - "security" [ color="#66FFCC" label=< - -
security
>]; - "setuid" [ color="#B8FFB8" label=< - -
setuid
>]; - "spring" [ color="#B8FFB8" label=< - -
spring
>]; - "stats" [ color="#B8FFB8" label=< - -
stats
>]; - "jmx" [ color="#B8FFB8" label=< - -
jmx
>]; - "http" [ color="#66FFCC" label=< - -
http
>]; - "debuglog" [ color="#B8FFB8" label=< - -
debuglog
>]; - "ipaccess" [ color="#B8FFB8" label=< - -
ipaccess
>]; - "jaas" [ color="#B8FFB8" label=< - -
jaas
>]; - "jndi" [ color="#B8FFB8" label=< - -
jndi
>]; - "lowresources" [ color="#B8FFB8" label=< - -
lowresources
>]; - } - - /* Level 2 */ - { rank = same; - "fcgi" [ color="#B8FFB8" label=< - -
fcgi
>]; - "jmx-remote" [ color="#B8FFB8" label=< - -
jmx-remote
>]; - "webapp" [ color="#66FFCC" label=< - -
webapp
>]; - "proxy" [ color="#B8FFB8" label=< - -
proxy
>]; - "alpn" [ color="#B8FFB8" label=< - -
alpn
>]; - "jaspi" [ color="#B8FFB8" label=< - -
jaspi
>]; - "http2c" [ color="#B8FFB8" label=< - -
http2c
>]; - "https" [ color="#B8FFB8" label=< - -
https
>]; - "servlets" [ color="#B8FFB8" label=< - -
servlets
>]; - } - - /* Level 3 */ - { rank = same; - "http2" [ color="#B8FFB8" label=< - -
http2
>]; - "plus" [ color="#B8FFB8" label=< - -
plus
>]; - "deploy" [ color="#66FFCC" label=< - -
deploy
>]; - "nosql" [ color="#B8FFB8" label=< - -
nosql
>]; - } - - /* Level 4 */ - { rank = same; - "annotations" [ color="#B8FFB8" label=< - -
annotations
>]; - } - - /* Level 5 */ - { rank = same; - "jdbc-sessions" [ color="#B8FFB8" label=< - -
jdbc-sessions
>]; - "infinispan" [ color="#B8FFB8" label=< - -
infinispan
>]; - "quickstart" [ color="#B8FFB8" label=< - -
quickstart
>]; - "jsp" [ color="#B8FFB8" label=< - -
jsp
>]; - "websocket" [ color="#B8FFB8" label=< - -
websocket
>]; - } - - /* Level 6 */ - { rank = same; - "jstl" [ color="#B8FFB8" label=< - -
jstl
>]; - "cdi" [ color="#B8FFB8" label=< - - -
cdi
(experimental)
>]; - } - "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"; -} - diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/modules-9.3-simplified.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/modules-9.3-simplified.png deleted file mode 100644 index bf38325232e4..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/modules-9.3-simplified.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/windows-service-jetty.png b/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/windows-service-jetty.png deleted file mode 100644 index c78557bc4eeb..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/old_docs/images/windows-service-jetty.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/index.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/index.adoc deleted file mode 100644 index 19df836e5866..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/index.adoc +++ /dev/null @@ -1,60 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -:doctitle: Eclipse Jetty: Old Documentation -:toc-title: Old Jetty Documentation -:sub-order: attributes+ - -include::../config.adoc[] - -== OLD JETTY DOCUMENTATION - -[IMPORTANT] -==== -The Jetty documentation that follows refers to old Jetty versions, and it is currently being ported to the current Jetty version. - -Please be patient if you find incorrect documentation for the current Jetty version: eventually, the old documentation will be ported to the current Jetty version and it will be up to date. -==== - -include::alpn/chapter.adoc[] -include::annotations/chapter.adoc[] -include::ant/chapter.adoc[] -include::architecture/chapter.adoc[] -include::connectors/chapter.adoc[] -include::contexts/chapter.adoc[] -//include::contributing/chapter.adoc[] -include::debugging/chapter.adoc[] -include::deploying/chapter.adoc[] -include::embedding/chapter.adoc[] -include::extras/chapter.adoc[] -include::fastcgi/chapter.adoc[] -include::frameworks/chapter.adoc[] -include::gettingstarted/introduction/chapter.adoc[] -include::gettingstarted/getting-started/chapter.adoc[] -include::gettingstarted/configuring/chapter.adoc[] -include::gettingstarted/upgrading/chapter.adoc[] -include::http2/chapter.adoc[] -include::jetty-xml/chapter.adoc[] -include::jmx/chapter.adoc[] -include::jndi/chapter.adoc[] -include::jsp/chapter.adoc[] -include::logging/chapter.adoc[] -include::maven/jetty-maven-scanning.adoc[] -include::platforms/chapter.adoc[] -include::runner/chapter.adoc[] -include::security/chapter.adoc[] -include::startup/chapter.adoc[] -include::troubleshooting/chapter.adoc[] -include::tuning/chapter.adoc[] -include::websockets/jetty/chapter.adoc[] -include::websockets/java/chapter.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/chapter.adoc deleted file mode 100644 index ff93a2315fca..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/chapter.adoc +++ /dev/null @@ -1,22 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[reference-section]] -== Jetty XML Reference - -include::jetty-xml-usage.adoc[] -include::jetty-xml-config.adoc[] -include::jetty-web-xml-config.adoc[] -include::jetty-env-xml.adoc[] -include::webdefault-xml.adoc[] -include::override-web-xml.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-env-xml.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-env-xml.adoc deleted file mode 100644 index 9ce585eecc69..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-env-xml.adoc +++ /dev/null @@ -1,94 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-env-xml]] -=== jetty-env.xml - -`jetty-env.xml` is an optional Jetty file that configures JNDI resources for an individual webapp. -The format of `jetty-env.xml` is the same as xref:jetty-xml-config[] –it is an XML mapping of the Jetty API. - -When Jetty deploys a web application, it automatically looks for a file called ` WEB-INF/jetty-env.xml` within the web application (or WAR), and sets up the webapp naming environment so that naming references in the `WEB-INF/web.xml` file can be resolved from the information provided in the `WEB-INF/jetty-env.xml` and xref:jetty-xml-config[] files. -You define global naming resources on the server via `jetty.xml`. - -[[jetty-env-root-element]] -==== jetty-env.xml Root Element - -Jetty applies `jetty-env.xml` on a per-webapp basis, and configures an instance of `org.eclipse.jetty.webapp.WebAppContext.` - -[source, xml, subs="{sub-order}"] ----- - - - - - - .. - - - ----- - -____ -[CAUTION] -Make sure you are applying the configuration to an instance of the proper class. `jetty-env.xml` configures an instance of WebAppContext, and not an instance of Server. -____ - -[[using-jetty-env-xml]] -==== Using `jetty-env.xml` - -Place the `jetty-env.xml` file in your web application's WEB-INF folder. - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - gargle - 100 - true - - - - - wiggle - 55.0 - true - - - - - jdbc/mydatasource99 - - - org.apache.derby.jdbc.EmbeddedXADataSource - databaseName=testdb99;createDatabase=create - mydatasource99 - - - - - - - ----- - -[[additional-jetty-env-xml-resources]] -==== Additional jetty-env.xml Resources - -* xref:jetty-xml-syntax[] –In-depth reference for Jetty-specific configuration XML syntax. -* xref:jetty-xml-config[] –Configuration file for configuring the entire server. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-web-xml-config.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-web-xml-config.adoc deleted file mode 100644 index 90958e5e2d81..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-web-xml-config.adoc +++ /dev/null @@ -1,64 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-web-xml-config]] -=== jetty-web.xml - -`jetty-web.xml` is a Jetty configuration file that you can bundle with a specific web application. -The format of `jetty-web.xml` is the same as xref:jetty-xml-config[] – it is an XML mapping of the Jetty API. - -This document offers an overview for using the `jetty-web.xml` configuration file. -For a more in-depth look at the syntax, see xref:jetty-xml-syntax[]. - -[[root-element-jetty-web-xml]] -==== Root Element - -`jetty-web.xml` applies on a per-webapp basis, and configures an instance of `org.eclipse.jetty.webapp.WebAppContext`. - -[source, xml, subs="{sub-order}"] ----- - - - - - .. - ----- - -____ -[CAUTION] -Make sure you are applying the configuration to an instance of the proper class. `jetty-web.xml` configures an instance of `WebAppContext`; `jetty.xml` configures an instance of `Server`. -____ - -[[using-jetty-web-xml]] -==== Using jetty-web.xml - -Place the `jetty-web.xml` into your web application's `WEB-INF` folder. -When Jetty deploys a web application, it looks for a file called `WEB-INF/jetty-web.xml` or `WEB-INF/web-jetty.xml` within the web application (or WAR) and applies the configuration found there. -Be aware that `jetty-web.xml` is called _after_ all other configuration has been applied to the web application. - -____ -[IMPORTANT] -It is important to note that `jetty-web.xml` files utilize the webapp classpath, not the classpath of the server. -____ - -[[jetty-web-xml-examples]] -==== jetty-web.xml Examples - -The distribution contains an example of `jetty-web.xml` inside the WEB-INF folder of the `test` webapp WAR (`$JETTY_HOME/demo-base/webapps/test.war/WEB-INF/jetty-web.xml`). - -[[additional-jetty-web-xml-resources]] -==== Additional `jetty-web.xml` Resources - -* xref:jetty-xml-syntax[] –in-depth reference for Jetty-specific configuration XML syntax. -* xref:jetty-xml-config[] –configuration file for configuring the entire server diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-xml-config.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-xml-config.adoc deleted file mode 100644 index 926eafcf92bb..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-xml-config.adoc +++ /dev/null @@ -1,59 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-xml-config]] -=== jetty.xml - -`jetty.xml` is the default configuration file for Jetty, typically located at `$JETTY_HOME/etc/jetty.xml`. Usually the `jetty.xml` configures: - -* The Server class (or subclass if extended) and global options. -* A ThreadPool (min and max thread). -* Connectors (ports, timeouts, buffer sizes, protocol). -* The handler structure (default handlers and/or a contextHandlerCollections). -* The deployment manager that scans for and deploys webapps and contexts. -* Login services that provide authentication checking. -* A request log. - -Not all Jetty features are configured in `jetty.xml`. -There are several optional configuration files that share the same format as `jetty.xml` and, if specified, concatenate to it. -These configuration files are also stored in `$JETTY_HOME/etc/`, and examples of them are in http://github.com/jetty/jetty.project/jetty-server/src/main/config/etc/[Github Repository]. -The selection of which configuration files to use is controlled by `start.jar` and the process of merging configuration is described in xref:jetty-xml-usage[]. - -[[root-element-jetty-xml]] -==== Root Element - -`jetty.xml` configures an instance of the `Jetty org.eclipse.jetty.server.Server.` - -[source, xml, subs="{sub-order}"] ----- - - - - - - ... - - - ----- - -[[jetty-xml-examples]] -==== Examples - -`$JETTY_HOME/etc` contains the default `jetty.xml`, as well as other sample configuration files (`jetty-*.xml`) which can be passed to the server via the command line. - -[[jetty-xml-additional-resources]] -==== Additional Resources - -* xref:jetty-xml-syntax[] –in-depth reference for Jetty-specific configuration XML syntax. -* xref:jetty-xml-config[] –configuration file for configuring the entire server diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-xml-usage.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-xml-usage.adoc deleted file mode 100644 index 55a2a8ccd5d4..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/jetty-xml-usage.adoc +++ /dev/null @@ -1,68 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-xml-usage]] -=== Jetty XML Usage - -Jetty provides an XML-based configuration. -It is grounded in Java's Reflection API. Classes in the `java.lang.reflect` represent Java methods and classes, such that you can instantiate objects and invoke their methods based on their names and argument types. -Behind the scenes, Jetty's XML config parser translates the XML elements and attributes into Reflection calls. - -[[using-jettyxml]] -==== Using jetty.xml - -To use `jetty.xml`, specify it as a configuration file when running Jetty. - -[source, java, subs="{sub-order}"] ----- - java -jar start.jar etc/jetty.xml ----- - -____ -[NOTE] -If you start Jetty without specifying a configuration file, Jetty automatically locates and uses the default installation `jetty.xml` file. -Therefore `java -jar start.jar` is equivalent to `java -jar start.jar etc/jetty.xml` . -____ - -[[using-multiple-configuration-files]] -==== Using Multiple Configuration Files - -You are not limited to one configuration file; you can use multiple configuration files when running Jetty, and Jetty will configure the appropriate server instance. -The ID of the server in the `` tag specifies the instance you want to configure. -Each server ID in a configuration file creates a new server instance within the same JVM. -If you use the same ID across multiple configuration files, those configurations are all applied to the same server. - -[[setting-parameters-in-configuration-files]] -==== Setting Parameters in Configuration Files - -You can set parameters in configuration files either with system properties (using ``) or properties files (using ``) passed via the command line. -For example, this code in `jetty.xml` allows the port to be defined on the command line, falling back onto `8080`if the port is not specified: - -[source, xml, subs="{sub-order}"] ----- - ----- - -Then you modify the port while running Jetty by using this command: - -[source, java, subs="{sub-order}"] ----- - java -Djetty.http.port=8888 -jar start.jar etc/jetty.xml ----- - -An example of defining both system properties and properties files from the command line: - -[source, java, subs="{sub-order}"] ----- - java -Djetty.http.port=8888 -jar start.jar myjetty.properties etc/jetty.xml etc/other.xml ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/override-web-xml.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/override-web-xml.adoc deleted file mode 100644 index 1310b1e86872..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/override-web-xml.adoc +++ /dev/null @@ -1,90 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[override-web-xml]] -=== Jetty override-web.xml - -To deploy a web application or WAR into different environments, most likely you will need to customize the webapp for compatibility with each environment. -The challenge is to do so without changing the webapp itself. You can use a `jetty.xml` file for some of this work since it is not part of the webapp. -But there are some changes that `jetty.xml` cannot accomplish, for example, modifications to servlet init-params and context init-params. -Using `webdefault.xml` is not an option because Jetty applies `webdefault.xml` to a web application _before_ the application's own `WEB-INF/web.xml`, which means that it cannot override values inside the webapp's ` web.xml`. - -The solution is `override-web.xml`. -It is a `web.xml` file that Jetty applies to a web application _after_ the application's own `WEB-INF/web.xml`, which means that it can override values or add new elements. -This is defined on a per-webapp basis, using the xref:jetty-xml-syntax[]. - -[[using-override-web-xml]] -==== Using override-web.xml - -You can specify the `override-web.xml` to use for an individual web application in a deployable xml file located in Jetty webapps folder . -For example, if you had a webapp named MyApp, you would place a deployable xml file named `myapp.xml` in `${jetty.base}/webapps` which includes an `overrideDescriptor` entry for the `override-web.xml` file. - -[source, xml, subs="{sub-order}"] ----- - - ... - - /my/path/to/override-web.xml - ... - ----- - -The equivalent in code is: - -[source, java, subs="{sub-order}"] ----- -import org.eclipse.jetty.webapp.WebAppContext; - - ... - - WebAppContext wac = new WebAppContext(); - ... - //Set the path to the override descriptor, based on your $(jetty.home) directory - wac.setOverrideDescriptor(System.getProperty("jetty.home")+"/my/path/to/override-web.xml"); - ... ----- - -Alternatively, you can use the classloader (xref:jetty-classloading[]) to get the path to the override descriptor as a resource. - -[[override-using-jetty-maven-plugin]] -==== Using the Jetty Maven Plugin - -Use the `` tag as follows: - -[source, xml, subs="{sub-order}"] ----- - - ... - - - ... - jetty-maven-plugin - - - ... - src/main/resources/override-web.xml - - - - ... - - ... - ----- - -[[override-web-xml-additional-resources]] -==== Additional Resources - -* xref:webdefault-xml[] –Information for this `web.xml` -formatted file, applied before the webapp's `web.xml` webapp. -* xref:jetty-xml-config[] –Reference for `jetty.xml` files diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/webdefault-xml.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/webdefault-xml.adoc deleted file mode 100644 index d9a2cedb90d4..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jetty-xml/webdefault-xml.adoc +++ /dev/null @@ -1,131 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[webdefault-xml]] -=== webdefault.xml - -The `webdefault.xml` file saves web applications from having to define a lot of house-keeping and container-specific elements in their own `web.xml` files. -For example, you can use it to set up MIME-type mappings and JSP servlet-mappings. -Jetty applies `webdefault.xml` to a web application _before_ the application's own `WEB-INF/web.xml`, which means that it *cannot* override values inside the webapp's `web.xml`. -It uses the xref:jetty-xml-config[] syntax. -Generally, it is convenient for all webapps in a Jetty instance to share the same `webdefault.xml` file. -However, it is certainly possible to provide differentiated ` webdefault.xml` files for individual web applications. - -The `webdefault.xml` file is located in `$(jetty.home)/etc/webdefault.xml`. - -[[using-webdefault-xml]] -==== Using webdefault.xml - -You can specify a custom configuration file to use for specific webapps, or for all webapps. If you do not specify an alternate defaults descriptor, the `$JETTY-HOME/etc/jetty-deploy.xml` file will configure jetty to automatically use `$JETTY_HOME/etc/webdefault.xml`. - -[NOTE] -==== -To ensure your `webdefault.xml` files are validated, you will need to set the `validateXml` attribute to true as described link:#jetty-xml-dtd[here.] -==== - -The `webdefault.xml` link:{GITBROWSEURLSURL}/jetty-webapp/src/main/config/etc/webdefault.xml[included with the Jetty Distribution] contains several configuration options, such as init params and servlet mappings, and is separated into sections for easy navigation. -Some of the more common options include, but are not limited to: - -dirAllowed:: -If true, directory listings are returned if no welcome file is found. -Otherwise 403 Forbidden displays. -precompressed:: -If set to a comma separated list of file extensions, these indicate compressed formats that are known to map to a MIME-type that may be listed in a requests Accept-Encoding header. -If set to a boolean True, then a default set of compressed formats will be used, otherwise no pre-compressed formats. -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. - -[[creating-custom-webdefault-xml-one-webapp]] -===== Creating a Custom webdefault.xml for One WebApp - -You can specify a custom `webdefault.xml` for an individual web application in that webapp's xref:jetty-xml-config[] as follows: - -[source, xml, subs="{sub-order}"] ----- - - - ... - - /my/path/to/webdefault.xml - ... - - - ----- - -The equivalent in code is: - -[source, java, subs="{sub-order}"] ----- - -import org.eclipse.jetty.webapp.WebAppContext; - - ... - - WebAppContext wac = new WebAppContext(); - ... - //Set up the absolute path to the custom webdefault.xml. - wac.setDefaultsDescriptor("/my/path/to/webdefault.xml"); - ... ----- - -Alternatively, you can use a xref:jetty-classloading[] to find the resource representing your custom `webdefault.xml`. - -[[creating-custom-webdefault-xml-multiple-webapps]] -===== Creating a Custom webdefault.xml for Multiple WebApps - -If you want to apply the same custom `webdefault.xml` to a number of webapps, provide the path to the file in xref:jetty-xml-config[] in the `$JETTY_HOME/etc/jetty-deploy.xml` file: - -[source, xml, subs="{sub-order}"] ----- - /other/path/to/another/webdefault.xml ----- - -[[webdefault-xml-using-jetty-maven-plugin]] -===== Using the Jetty Maven Plugin - -Similarly, when using the link:#jetty-maven-plugin[Jetty Maven Plugin] you provide a customized `webdefault.xml` file for your webapp as follows: - -[source, xml, subs="{sub-order}"] ----- - - ... - - - ... - jetty-maven-plugin - - - ... - /my/path/to/webdefault.xml - - - - ... - - ... - - - ----- - -[[webdefault-xml-additional-resources]] -===== Additional Resources - -* xref:jetty-web-xml-config[] –Reference for `web.xml` files -* xref:override-web-xml[] –Information for this `web.xml` -formatted file, applied after the webapp's `web.xml` webapp. -* xref:jetty-xml-config[] –Reference for `jetty.xml` files diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/chapter.adoc deleted file mode 100644 index 8c32f55549d7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/chapter.adoc +++ /dev/null @@ -1,29 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jmx-chapter]] -== 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. - -include::jetty-jmx-annotations.adoc[] -include::jetty-jconsole.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/jetty-jconsole.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/jetty-jconsole.adoc deleted file mode 100644 index 3ba07aea832e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/jetty-jconsole.adoc +++ /dev/null @@ -1,113 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-jconsole]] -=== Managing Jetty with JConsole and JMC - -JConsole and the Java Mission Control (JMX) are graphical tools; they allow 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 or JMC from running. - -==== Starting Jetty Standalone - -The simplest way to enable support is to add the JMX-Remote support module to your `{$jetty.base}`. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=jmx-remote, jmx -INFO: jmx-remote initialised in ${jetty.base}/start.ini -INFO: jmx initialised in ${jetty.base}/start.ini -.... - -Then open the `{$jetty.base}/start.ini` (or `{$jetty.base}/start.d/jmx-remote.ini`) file and edit the properties to suit your needs: - -[source, screen, subs="{sub-order}"] -.... -# -# Initialize module jmx-remote -# ---module=jmx-remote -## JMX Configuration -## Enable for an open port accessible by remote machines -jetty.jmxrmihost=localhost -jetty.jmxrmiport=1099 -.... - -[[jetty-jconsole-monitoring]] -==== Monitoring Jetty with JConsole - -To monitor Jetty's server status with JConsole, start Jetty and then start JConsole by typing `jconsole` on the command line. - -===== Connecting to your server process - -After you start Jetty, you will see a dialog box in JConsole with a list of running processes to which you can connect. -It should look something like so: - -image: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: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. - -image:jconsole3.png[image,width=576] - -[[jetty-jmc-monitoring]] -==== Monitoring Jetty with JMC - -To monitor Jetty's server status with JMC, start Jetty and then start JMC by typing `jmc` on the command line. - -===== Connecting to your server process - -After you start Jetty, you will see a dialog box in JMC with a list of running processes to which you can connect. -It should look something like so: - -image:jmc1.png[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 JMC to refresh the list, and recognize your newly-started Jetty process. -____ - -Double-click the start.jar entry or right-click the start.jar entry and select "Start JMX Console". -A new JMC window opens on the right: - -image:jmc2.png[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. -JMC is an extremely powerful and useful tool. - -==== Managing Jetty Objects with JConsole - -The MBean tab of JMC 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 JMC, you need to start Jetty JMX in a form that JMC can access. -See xref:using-jmx[] for more information. - -image:jmc3.png[image,width=576] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/jetty-jmx-annotations.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/jetty-jmx-annotations.adoc deleted file mode 100644 index 2ed8abd6571f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jmx/jetty-jmx-annotations.adoc +++ /dev/null @@ -1,135 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 an MBran is created with the description of the version `@ManagedObject` discovered. -3. Once a 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 `@ManagedObject` annotations on `.jmx.ClassMBean` allows for a normal POJOs 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, subs="{sub-order}"] ----- - -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); - } -} ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/chapter.adoc deleted file mode 100644 index 693a58658eb5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/chapter.adoc +++ /dev/null @@ -1,23 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jndi]] -== Configuring JNDI - -Jetty supports `java:comp/env` lookups in webapps. -This is an optional feature for which some configuration is required. - -include::using-jndi.adoc[] -include::jndi-configuration.adoc[] -include::jndi-embedded.adoc[] -include::jndi-datasources.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-configuration.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-configuration.adoc deleted file mode 100644 index 1e76742467db..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-configuration.adoc +++ /dev/null @@ -1,339 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 the `org.eclipse.jetty.plus.jndi.EnvEntry` class, and even override an entry of the same name in `web.xml`. - -[source, xml, subs="{sub-order}"] ----- - - - mySpecialValue - 4000 - true - ----- - -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, subs="{sub-order}"] ----- -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, subs="{sub-order}"] ----- - - - - jdbc/myds - - - test - create - - - - ----- - -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, subs="{sub-order}"] ----- - - jdbc/myds - javax.sql.DataSource - Container - ----- - -To look up your DataSource in your `servlet/filter/etc.`: - -[source, java, subs="{sub-order}"] ----- -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, subs="{sub-order}"] ----- - - - - jms/connectionFactory - - - vm://localhost?broker.persistent=false - - - - ----- - -The entry in `web.xml` would be: - -[source, xml, subs="{sub-order}"] ----- - - jms/connectionFactory - javax.jms.ConnectionFactory - Container - ----- - -//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, subs="{sub-order}"] ----- - - - - mail/Session - - - fred - OBF:1xmk1w261z0f1w1c1xmq - - - XXX - me@me - true - - - - - - ----- - -This setup creates an instance of the `org.eclipse.jetty.jndi.factories.MailSessionReference` class, calls it's 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. - -____ -[NOTE] -As of Jetty 10, the link:{MVNCENTRAL}/org/eclipse/jetty/orbit/javax.mail.glassfish/1.4.1.v201005082020/javax.mail.glassfish-1.4.1.v201005082020.jar[`javax.mail`] and link:{MVNCENTRAL}/org/eclipse/jetty/orbit/javax.activation/1.1.0.v201105071233/javax.activation-1.1.0.v201105071233.jar[`javax.activation`] jar files are not included in the Jetty Distribution and will need to be downloaded separately from Maven Central. -____ - -____ -[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, subs="{sub-order}"] ----- - - - - - ----- - -[[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, subs="{sub-order}"] ----- - - - - jdbc/mydatasource - - - test - create - - - - ----- - -In a `web.xml` file: - -[source, xml, subs="{sub-order}"] ----- - - jdbc/mydatasource - javax.sql.DataSource - Container - - com.acme.JNDITest - myDatasource - - ----- - -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, subs="{sub-order}"] ----- - - - - jdbc/mydatasource - - - test - create - - - - ----- - -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, subs="{sub-order}"] ----- - - - jdbc/mydatasource1 - jdbc/mydatasource - ----- - -Now you can refer to `jdbc/mydatasource1` in the `web.xml` like this: - -[source, xml, subs="{sub-order}"] ----- - - jdbc/mydatasource1 - javax.sql.DataSource - Container - - com.acme.JNDITest - myDatasource - - ----- - -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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-datasources.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-datasources.adoc deleted file mode 100644 index c77aa4dda6bf..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-datasources.adoc +++ /dev/null @@ -1,400 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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, subs="{sub-order}"] ----- - - My DataSource Reference - jdbc/DSTest - javax.sql.DataSource - Container - ----- - -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, 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, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - - - 5 - 20 - com.mysql.jdbc.jdbc2.optional.MysqlDataSource - jdbc.user - jdbc.pass - - url - jdbc.url - - - - - - ----- - -[[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, subs="{sub-order}"] ----- - - - - jdbc/DSTest - - - com.mysql.jdbc.Driver - jdbc.url - jdbc.user - jdbc.pass - 5 - 50 - 5 - 30 - - - ----- - -[[c3p0-datasource]] -===== c3p0 - -Connection pooling, available at https://repo1.maven.org/maven2/c3p0/c3p0/0.9.1.2/c3p0-0.9.1.2.jar[c3p0 Jar]. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - org.some.Driver - jdbc.url - jdbc.user - jdbc.pass - - - ----- - -[[dbcp-datasource]] -===== DBCP - -Connection pooling, available at https://repo1.maven.org/maven2/commons-dbcp/commons-dbcp/1.2/commons-dbcp-1.2.jar[dbcp Jar]. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - org.some.Driver - jdbc.url - jdbc.user - jdbc.pass - - - - ----- - -[[atomikos-datasource]] -===== Atomikos 3.3.2+ - -Connection pooling + XA transactions. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - 2 - 50 - com.mysql.jdbc.jdbc2.optional.MysqlXADataSource - DSTest - - - url - jdbc:mysql://localhost:3306/databasename - - - user - some_username - - - password - some_password - - - - - ----- - -[[mysql-pooled-datasource]] -===== MySQL - -Implements `javax.sql.DataSource` and `javax.sql.ConnectionPoolDataSource`. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - jdbc:mysql://localhost:3306/databasename - user - pass - - - ----- - -[[postgreSQL-pooled-datasource]] -===== PostgreSQL - -Implements `javax.sql.ConnectionPoolDataSource`. - -[source, xml, subs="{sub-order}"] ----- - - - - jdbc/DSTest - - - user - pass - dbname - localhost - 5432 - - - - - - ----- - -[[DB2-pooled-datasource]] -===== DB2 - -Implements `javax.sql.ConnectionPoolDataSource`. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - dbname - user - pass - servername - 50000 - - - ----- - -[[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` and `javax.sql.ConnectionPoolDataSource`. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - user - pass - dbname - localhost - 1433 - - - ----- - -[[oracle-9i10g-datasource]] -===== Oracle 9i/10g - -Implements `javax.sql.DataSource` and `javax.sql.ConnectionPoolDataSource`. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - thin - jdbc:oracle:thin:@fmsswdb1:10017:otcd - xxxx - xxxx - true - - - - MinLimit - 5 - - - - - - - ----- - -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, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - user - pass - dbname - localhost - 5432 - - - ----- - -[[sybase-datasource]] -===== Sybase - -Implements `javax.sql.DataSource`. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - dbname - user - pass - servername - 5000 - - - ----- - -[[DB2-datasource]] -===== DB2 - -Implements `javax.sql.DataSource`. - -[source, xml, subs="{sub-order}"] ----- - - - jdbc/DSTest - - - dbname - user - pass - servername - 50000 - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-embedded.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-embedded.adoc deleted file mode 100644 index 78c50582ad04..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/jndi-embedded.adoc +++ /dev/null @@ -1,128 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 obtain this jar link:{MVNCENTRAL}/org/eclipse/jetty/orbit/javax.transaction/1.1.1.v201105210645/javax.transaction-1.1.1.v201105210645.jar[here.] - -If you wish to use mail, you will also need the `javax.mail` api and implementation which link:{MVNCENTRAL}/org/eclipse/jetty/orbit/javax.mail.glassfish/1.4.1.v201005082020/javax.mail.glassfish-1.4.1.v201005082020.jar[you can download here.] -Note that this jar also requires the `javax.activation` classes, which is available link:{MVNCENTRAL}/org/eclipse/jetty/orbit/javax.activation/1.1.0.v201105071233/javax.activation-1.1.0.v201105071233.jar[at this link.] - -==== 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, subs="{sub-order}"] ----- -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: - // - // woggle - // java.lang.Integer - // 4000 - // - 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: - // - // wiggle - // 100 - // java.lang.Double - // - //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: - // - // mail/Session - // javax.mail.Session - // Container - // - //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: - // - // jdbc/mydatasource - // javax.sql.DataSource - // Container - // - //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(); - } -} ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/using-jndi.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/using-jndi.adoc deleted file mode 100644 index 89081be2d170..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jndi/using-jndi.adoc +++ /dev/null @@ -1,149 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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, subs="{sub-order}"] ----- - - - ----- - -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 the link between a `web.xml` resource name and a naming entry - -Declarations of each of these types follow the same general pattern: - -[source, xml, subs="{sub-order}"] ----- - - - - - ----- - -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, subs="{sub-order}"] ----- - - - - jms/connectionFactory - - - vm://localhost?broker.persistent=false - - - ----- -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, subs="{sub-order}"] ----- - - - - jms/connectionFactory - - - vm://localhost?broker.persistent=false - - - - ----- -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, subs="{sub-order}"] ----- - - - - jms/connectionFactory - - - vm://localhost?broker.persistent=false - - - - ----- - -[[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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jsp/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jsp/chapter.adoc deleted file mode 100644 index 29715488c3a6..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jsp/chapter.adoc +++ /dev/null @@ -1,17 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-jsp]] -== Configuring JSP Support - -include::configuring-jsp.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jsp/configuring-jsp.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/jsp/configuring-jsp.adoc deleted file mode 100644 index 2c8b502dd36e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/jsp/configuring-jsp.adoc +++ /dev/null @@ -1,339 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jsp-support]] -=== Configuring JSP - -This document provides information about configuring Java Server Pages (JSP) for Jetty. - -[[which-jsp-implementation]] -==== Which JSP Implementation - -Jetty uses Jasper from http://tomcat.apache.org/tomcat-8.0-doc/jasper-howto.html[Apache] as the default JSP container implementation. - -By default the Jetty distribution enables the JSP link:#startup-modules[module], and by default, this module is set to Apache Jasper. - -[source, plain, subs="{sub-order}"] ----- -include::{SRCDIR}/jetty-home/src/main/resources/modules/jsp.mod[] ----- - -Note that the availability of some JSP features may depend on which JSP container implementation you are using. -Note also that it may not be possible to precompile your JSPs with one container and deploy to the other. - -===== Logging - -The Apache Jasper logging system is bridged to the jetty logging system. -Thus, you can enable logging for jsps in the same way you have setup for your webapp. -For example, assuming you are using Jetty's default StdErr logger, you would enable DEBUG level logging for jsps by adding the system property `-Dorg.apache.jasper.LEVEL=DEBUG` to the command line. - -===== JSPs and Embedding - -If you have an embedded setup for your webapp and wish to use JSPs, you will need to ensure that a JSP engine is correctly initialized. - -For Apache, a Servlet Specification 3.1 style link:#servlet-container-initializers[ServletContainerInitializer] is used to accomplish this. -You will need to ensure that this ServletContainerInitializer is run by jetty. Perhaps the easiest way to do this is to enable annotations processing so that Jetty automatically discovers and runs it. -The link:#embedded-examples[Embedded Examples] section includes a link:#embedded-webapp-jsp[worked code example] of how to do this. - -Alternatively, you can manually wire in the appropriate ServletContainerInitializer as shown in the https://github.com/jetty-project/embedded-jetty-jsp/blob/master/src/main/java/org/eclipse/jetty/demo/Main.java[embedded-jetty-jsp] example on https://github.com/jetty-project[GitHub], in which case you will not need the jetty-annotations jar on your classpath, nor include the AnnotationConfiguration in the list of link:#webapp-configurations[configuration classes]. - -==== Precompiling JSPs - -You can either follow the instructions on precompilation provided by Apache, or if you are using Maven for your builds, you can use the link:#jetty-jspc-maven-plugin[jetty-jspc-maven] plugin to do it for you. - -If you have precompiled your JSPs, and have customized the output package prefix (which is `org.apache.jsp` by default), you should configure your webapp context to tell Jetty about this custom package name. -You can do this using a servlet context init-param called `org.eclipse.jetty.servlet.jspPackagePrefix`. - -For example, suppose you have precompiled your JSPs with the custom package prefix of `com.acme`, then you would add the following lines to your `web.xml` file: - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty.servlet.jspPackagePrefix - com.acme - ----- - -____ -[NOTE] -Both Jetty Maven plugins - link:#jetty-jspc-maven-plugin[jetty-jspc-maven-plugin] and the link:#jetty-maven-plugin[jetty-maven-plugin] - will only use Apache Jasper. -____ - -[[compiling-jsps]] -===== Apache JSP Container - -By default, the Apache JSP container will look for the Eclipse Java Compiler (jdt). -The Jetty distribution ships a copy of this in `{$jetty.home}/lib/apache-jsp`. -If you wish to use a different compiler, you will need to configure the `compilerClassName` init-param on the `JspServlet` with the name of the class. - -.Understanding Apache JspServlet Parameters -[cols=",,,",options="header",] -|======================================================================= -|init param |Description |Default |`webdefault.xml` - -|checkInterval |If non-zero and `development` is `false`, background jsp recompilation is enabled. This value is the interval in seconds between background recompile checks. - |0 |– -|classpath |The classpath is dynamically generated if the context has a URL classloader. The `org.apache.catalina.jsp_classpath` -context attribute is used to add to the classpath, but if this is not set, this `classpath` configuration item is added to the classpath instead.` |- |– - -|classdebuginfo |Include debugging info in class file. |TRUE |– - -|compilerClassName |If not set, defaults to the Eclipse jdt compiler. |- |– - -|compiler |Used if the Eclipse jdt compiler cannot be found on the -classpath. It is the classname of a compiler that Ant should invoke. |– -|– - -|compilerTargetVM |Target vm to compile for. |1.8 |1.8 - -|compilerSourceVM |Sets source compliance level for the jdt compiler. -|1.8 |1.8 - -|development |If `true` recompilation checks occur at the frequency governed by `modificationTestInterval`. |TRUE |– - -|displaySourceFragment |Should a source fragment be included in -exception messages |TRUE |– - -|dumpSmap |Dump SMAP JSR45 info to a file. |FALSE |– - -|enablePooling |Determines whether tag handler pooling is enabled. |TRUE |– - -|engineOptionsClass |Allows specifying the Options class used to -configure Jasper. If not present, the default EmbeddedServletOptions -will be used. |- |– - -|errorOnUseBeanInvalidClassAttribute |Should Jasper issue an error when -the value of the class attribute in an useBean action is not a valid -bean class |TRUE |– - -|fork |Only relevant if you use Ant to compile jsps: by default Jetty will use the Eclipse jdt compiler.|TRUE |- - -|genStrAsCharArray |Option for generating Strings as char arrays. |FALSE |– - -|ieClassId |The class-id value to be sent to Internet Explorer when -using tags. |clsid:8AD9C840-044E-11D1-B3E9-00805F499D93 |– - -|javaEncoding |Pass through the encoding to use for the compilation. -|UTF8 |– - -|jspIdleTimeout |The amount of time in seconds a JSP can be idle before -it is unloaded. A value of zero or less indicates never unload. |-1 |– - -|keepgenerated |Do you want to keep the generated Java files around? -|TRUE |– - -|mappedFile |Support for mapped Files. Generates a servlet that has a -print statement per line of the JSP file  |TRUE |– - -|maxLoadedJsps |The maximum number of JSPs that will be loaded for a web -application. If more than this number of JSPs are loaded, the least -recently used JSPs will be unloaded so that the number of JSPs loaded at -any one time does not exceed this limit. A value of zero or less -indicates no limit. |-1 |– - -|modificationTestInterval |If `development=true`, interval between -recompilation checks, triggered by a request. |4 |– - -|quoteAttributeEL | When EL is used in an attribute value on a JSP page, should the rules for quoting of attributes described in JSP.1.6 be applied to the expression - |TRUE |- - -|recompileOnFail |If a JSP compilation fails should the -modificationTestInterval be ignored and the next access trigger a -re-compilation attempt? Used in development mode only and is disabled by -default as compilation may be expensive and could lead to excessive -resource usage. |FALSE |– - -|scratchDir |Directory where servlets are generated. The default is the value of the context attribute `javax.servlet.context.tempdir`, or the system property `java.io.tmpdir` if the context attribute is not set. |– |– - -|strictQuoteEscaping |Should the quote escaping required by section JSP.1.6 of the JSP specification be applied to scriplet expression. - |TRUE|- - -|suppressSmap |Generation of SMAP info for JSR45 debugging. |FALSE |– - -|trimSpaces |Should template text that consists entirely of whitespace be removed from the output (true), replaced with a single space (single) or left unchanged (false)? Note that if a JSP page or tag file specifies a trimDirectiveWhitespaces value of true, that will take precedence over this configuration setting for that page/tag. -trimmed? |FALSE |– - -|xpoweredBy |Generate an X-Powered-By response header. |FALSE |FALSE - -|======================================================================= - -[[configuring-jsp-for-jetty]] -===== Configuration - -The JSP engine has many configuration parameters. -Some parameters affect only precompilation, and some affect runtime recompilation checking. -Parameters also differ among the various versions of the JSP engine. -This page lists the configuration parameters, their meanings, and their default settings. -Set all parameters on the `org.eclipse.jetty.jsp.JettyJspServlet` instance defined in the link:#webdefault-xml[`webdefault.xml`] file. - -____ -[NOTE] -Be careful: for all of these parameters, if the value you set doesn't take effect, try using all lower case instead of camel case, or capitalizing only some of the words in the name, as JSP is inconsistent in its parameter naming strategy. -____ - -[[modifying-configuration]] -==== Modifying Configuration - -[[overriding-webdefault.xml]] -===== Overriding `webdefault.xml` - -You can make a copy of the link:#webdefault-xml[{$jetty.home}/etc/webdefault.xml] that ships with Jetty, apply your changes, and use it instead of the shipped version. -The example below shows how to do this when using the Jetty Maven plugin. - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty - jetty-maven-plugin - - - src/main/resources/webdefault.xml - - ----- - -If you are using the Jetty distribution, and you want to change the JSP settings for just one or a few of your webapps, copy the `{$jetty.home}/etc/webdefault.xml` file somewhere, modify it, and then use a link:#intro-jetty-configuration-contexts[context xml] file to set this file as the `defaultsDescriptor` for your webapp. Here's a snippet: - -[source, xml, subs="{sub-order}"] ----- - - /foo - /webapps/foobar.war - /home/smith/dev/webdefault.xml - ----- - -If you want to change the JSP settings for all webapps, edit the `{$jetty.home}/etc/webdefaults.xml` file directly instead. - -[[configuring-jsp-servlet-in-web.xml]] -===== Configuring the JSP Servlet in web.xml - -Another option is to add an entry for the JSPServlet to the `WEB-INF/web.xml` file of your webapp and change or add init-params. -You may also add (but not remove) servlet-mappings. -You can use the entry in link:#webdefault-xml[{$jetty.home}/etc/webdefault.xml] as a starting point. - -[source, xml, subs="{sub-order}"] ----- - - jsp - org.eclipse.jetty.jsp.JettyJspServlet - - keepgenerated - true - - ... - - 0 - - - - jsp - *.jsp - *.jspf - *.jspx - *.xsp - *.JSP - *.JSPF - *.JSPX - *.XSP - - - - myServlet - com.acme.servlet.MyServlet - ... ----- - -[[jsp-async-support]] -===== Configuring Async Support - -By default, Jetty does not enable async support for the JSP servlet. -Configuring the JSP servlet for async is relatively easy - simply define the `async-supported` parameter as `true` in either your `webdefault.xml` or the `web.xml` for a specific context. - -[source, xml, subs="{sub-order}"] ----- - - jsp - true - ----- - -[[using-jstl-taglibs-for-jetty7-jetty8]] -==== Using JSTL Taglibs - -The JavaServer Pages Standlard Tag Library (JSTL) is part of the Jetty distribution and is automatically put on the classpath when you link:#which-jsp-implementation[select your flavour of JSP]. -It is also automatically on the classpath for the Jetty Maven plugin, which uses the Apache JSP engine. - -===== Embedding - -If you are using Jetty in an embedded scenario, and you need to use JSTL, then you must ensure that the JSTL jars are included on the _container's_ classpath - that is the classpath that is the _parent_ of the webapp's classpath. -This is a restriction that arises from the JavaEE specification. - -====== Apache JSP - -You will need to put the jars that are present in the `{$jetty.home}/lib/apache-jstl` directory onto the _container's_ classpath. -The Apache JSP engine will find the JSTL tag definitions inside these jars during startup. - -As an efficiency enhancement, you can have jetty examine the JSTL jars to find the tags, and pre-feed them into the Apache JSP engine. -This is more efficient, because jetty will only scan the jars you tell it to, whereas the Apache JSP engine will scan every jar, which can be time-consuming in applications with a lot of jars on the container classpath. - -To take advantage of this efficiency enhancement, set up the link:#container-include-jar-pattern[org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern] to include a http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html[pattern] that will match the names of the JSTL jars. -The link:#embedded-examples[Embedded Examples] section includes a link:#embedded-webapp-jsp[worked code example] of how to do this. -Below is a snippet from the example: - -[source, java, subs="{sub-order}"] ----- - webapp.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",".*/[^/]*taglibs.*\\.jar$"); ----- - -[[using-jsf-taglibs]] -==== Using JSF Taglibs - -The following sections provide information about using JSF TagLibs with Jetty Standalone and the Jetty Maven Plugin. - -[[using-jsf-taglibs-with-jetty-standalone]] -===== Using JSF Taglibs with Jetty Distribution - -If you want to use JSF with your webapp, you need to copy the JSF implementation Jar (whichever Jar contains the `META-INF/*.tld` files from your chosen JSF implementation) into Jetty's shared container lib directory. -You can either put them into the lib directory for Apache `{$jetty.home}/lib/apache-jsp` or put them into `{$jetty.home}/lib/ext`. - -[[using-jsf-taglibs-with-jetty-maven-plugin]] -===== Using JSF Taglibs with Jetty Maven Plugin - -You should make your JSF jars dependencies of the plugin and _not_ the webapp itself. -For example: - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty - jetty-maven-plugin - - - /${artifactId} - - - - - com.sun.faces - jsf-api - 2.0.8 - - - com.sun.faces - jsf-impl - 2.0.8 - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/chapter.adoc deleted file mode 100644 index 8c1d6d5bae66..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/chapter.adoc +++ /dev/null @@ -1,22 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-logging]] -== Jetty Logging - -This chapter discusses various options for configuring logging. - -include::configuring-jetty-logging.adoc[] -include::default-logging-with-stderrlog.adoc[] -include::configuring-logging-modules.adoc[] -include::example-logback-centralized-logging.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/configuring-jetty-logging.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/configuring-jetty-logging.adoc deleted file mode 100644 index f3bbd96ea319..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/configuring-jetty-logging.adoc +++ /dev/null @@ -1,68 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 or Log4j2 via SLF4J] -* Using link:#example-logging-logback[Logback via SLF4J] -* Using link:#example-logging-java-util-logging[Java Util Logging via SLF4J] -* Using link:#example-logging-java-commons-logging[Java Commons Logging via SLF4J] -* link:#example-logging-logback-centralized[Centralized Logging with Logback and Sfl4jLog] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/configuring-logging-modules.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/configuring-logging-modules.adoc deleted file mode 100644 index c0e51a68ce5d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/configuring-logging-modules.adoc +++ /dev/null @@ -1,489 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-logging-modules]] -=== Jetty Logging Integrations (SLF4J, Log4j, Logback, JCL, JUL) - -Jetty provides support for several logging frameworks including SLF4J, Java Commons Logging (JCL), Java Util Logging (JUL), Log4j (including version 2), and Logback. -This page includes examples of how to enable the associated modules for these different frameworks. -These modules are designed to capture container/server logs; link:#configuring-jetty-request-logs[request logs] and application logs need to be configured separately. -Please note that enabling these modules provides typical and basic functionality for each framework; advanced implementations may require their link:#startup-modules[own modules] or additional configuration. - -Enabling these frameworks in the Jetty distribution is as easy as activating any other module, by adding `--add-to-start=` to the start command for your server, such as: - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging-jetty -INFO : logging-jetty initialized in ${jetty.base}/start.d/logging-jetty.ini -INFO : resources transitively enabled -MKDIR : ${jetty.base}/resources -COPY : ${jetty.home}/modules/logging-jetty/resources/jetty-logging.properties to ${jetty.base}/resources/jetty-logging.properties -INFO : Base directory was modified -.... - -As noted above, Jetty supports a wide array of logging technologies. -If a particular logging framework requires additional jar files, Jetty will automatically download these as part of enabling the associated module and any dependent modules will be transitively enabled. - -A list of the base Jetty logging modules by running `java -jar /start.jar --list-modules=logging,-internal`. - -logging-jcl:: -Configures Jetty logging to use Java Commons Logging (JCL), using SLF4J as a binding. -logging-jetty:: -Standard Jetty logging that captures `System.err` and `System.out` output. -logging-jul:: -Configures Jetty logging to use Java Util Logging (JUL), using SLF4J as a binding. -logging-log4j:: -Configures Jetty logging to use Log4j as the logging implementation, using SLF4J as a binding. -logging-log4j2:: -Configures Jetty logging to use Log4j2 as the logging implementation, using SLF4J as a binding. -logging-logback:: -Configures Jetty logging to use Logback as the logging implementation, using SLF4J as a binding. -logging-slf4j:: -Configures Jetty logging to use SLF4J and provides a `slf4j-impl` which can be used by other logging frameworks. -If no other logging is configured, `slf4j-simple` is used. - -You can view a list of *all* the Jetty logging modules by running `java -jar /start.jar --list-modules=logging`. -This will display all logging modules, including implementation and binding modules. - -All these modules (with the exception of `logging-jetty`) arrange for the Jetty private logging API to be routed to the named technology to actually be logged. -For example, enabling the `logging-log4j` module will do several things: - -* it enables an internal Log4j API module so that any container code that uses Log4j will find the API. -* it enables an internal Log4j Implementation so that any container code that uses the Log4j API will also use a Log4j implementation to handle the logs (and all the normal Log4j configuration mechanisms etc.) -* it enables the internal `slf4j-log4j` logging binding so that any container code that uses the SLF4j API to also use the Log4j implementation via the Log4j API. -* it configures the Jetty logging API to use the SLF4J API, which is then bound to Log4j. - -So, after enabling `logging-log4j`, within the server container there are 3 logging APIs available: Jetty, SLF4J and Log4J. -But there is only a single logging *implementation* - Log4j; the 3 APIs act only as facades over the Log4j implementation. - -Note that you can add additional APIs to this configuration. -For example, enabling the internal module `jcl-slf4j` would add in a Java Commons Logging facade that also would use the Log4j implementation via the SLF4J binding. - -Most other top level logging modules work in the same way: `logging-jcl`, `logging-jul`, `logging-slf4j`, `logging-log4j2` and `logging-logback` all bind their implementation via SLF4J. - -[[example-logging-slf4j]] -==== Logging with SLF4J - -Jetty uses the SLF4J api as a binding to provide logging information to additional frameworks such as Log4j or Logback. -It can also be used on it's own to provide simple server logging. -To enable the SLF4J framework, you need to activate the `logging-slf4j` module. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging-slf4j - -ALERT: There are enabled module(s) with licenses. -The following 1 module(s): - + contains software not provided by the Eclipse Foundation! - + contains software not covered by the Eclipse Public License! - + has not been audited for compliance with its license - - Module: slf4j-api - + SLF4J is distributed under the MIT License. - + Copyright (c) 2004-2013 QOS.ch - + All rights reserved. - + Permission is hereby granted, free of charge, to any person obtaining - + a copy of this software and associated documentation files (the - + "Software"), to deal in the Software without restriction, including - + without limitation the rights to use, copy, modify, merge, publish, - + distribute, sublicense, and/or sell copies of the Software, and to - + permit persons to whom the Software is furnished to do so, subject to - + the following conditions: - + The above copyright notice and this permission notice shall be - + included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Proceed (y/N)? y -INFO : slf4j-api transitively enabled -INFO : logging-slf4j initialized in ${jetty.base}/start.d/logging-slf4j.ini -MKDIR : ${jetty.base}/lib/slf4j -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.21/slf4j-api-1.7.21.jar to ${jetty.base}/lib/slf4j/slf4j-api-1.7.21.jar -INFO : Base directory was modified -ERROR : Module logging-slf4j requires a module providing slf4j-impl from one of [slf4j-simple-impl, slf4j-logback, slf4j-jul, slf4j-log4j2, slf4j-log4j] - -ERROR : Unsatisfied module dependencies: logging-slf4j - -Usage: java -jar $JETTY_HOME/start.jar [options] [properties] [configs] - java -jar $JETTY_HOME/start.jar --help # for more information -.... - -As you probably noticed, the system gives an `ERROR` when trying to enable the `logging-slf4j` on it's own. -The `logging-slf4j` module itself provides the SLF4J api, but as SLF4J is often used as a binding for other logging frameworks does not by default provide an implementation. -To enable the simple SLF4J implementation, we will also need to activate the `slf4j-simple-impl` module. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=slf4j-simple-impl -INFO : slf4j-simple-impl initialized in ${jetty.base}/start.d/slf4j-simple-impl.ini -INFO : resources transitively enabled -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-simple/1.7.21/slf4j-simple-1.7.21.jar to ${jetty.base}/lib/slf4j/slf4j-simple-1.7.21.jar -MKDIR : ${jetty.base}/resources -COPY : ${jetty.home}/modules/slf4j-simple-impl/resources/simplelogger.properties to ${jetty.base}/resources/simplelogger.properties -INFO : Base directory was modified - -[my-base]$ tree -. -├── lib -│   └── slf4j -│   ├── slf4j-api-1.7.21.jar -│   └── slf4j-simple-1.7.21.jar -├── resources -│   └── simplelogger.properties -└── start.d - ├── logging-slf4j.ini - └── slf4j-simple-impl.ini -.... - -Jetty is now configured to log using the SLF4J framework. -A standard SLF4J properties file is located in `${jetty.base}/resources/simplelogger.properties`. - -[[example-logging-log4j]] -==== Logging with Log4j and Log4j2 - -It is possible to have the Jetty Server logging configured so that Log4j or Log4j2 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]. -Implementation of Log4j can be done by enabling the `logging-log4j` module. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging-log4j - -ALERT: There are enabled module(s) with licenses. -The following 2 module(s): - + contains software not provided by the Eclipse Foundation! - + contains software not covered by the Eclipse Public License! - + has not been audited for compliance with its license - - Module: log4j-impl - + Log4j is released under the Apache 2.0 license. - + http://www.apache.org/licenses/LICENSE-2.0.html - - Module: slf4j-api - + SLF4J is distributed under the MIT License. - + Copyright (c) 2004-2013 QOS.ch - + All rights reserved. - + Permission is hereby granted, free of charge, to any person obtaining - + a copy of this software and associated documentation files (the - + "Software"), to deal in the Software without restriction, including - + without limitation the rights to use, copy, modify, merge, publish, - + distribute, sublicense, and/or sell copies of the Software, and to - + permit persons to whom the Software is furnished to do so, subject to - + the following conditions: - + The above copyright notice and this permission notice shall be - + included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Proceed (y/N)? y -INFO : slf4j-api transitively enabled -INFO : log4j-impl transitively enabled -INFO : resources transitively enabled -INFO : slf4j-log4j transitively enabled -INFO : logging-log4j initialized in ${jetty.base}/start.d/logging-log4j.ini -MKDIR : ${jetty.base}/lib/slf4j -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.21/slf4j-api-1.7.21.jar to ${jetty.base}/lib/slf4j/slf4j-api-1.7.21.jar -MKDIR : ${jetty.base}/lib/log4j -COPY : /Users/admin/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar to ${jetty.base}/lib/log4j/log4j-1.2.17.jar -MKDIR : ${jetty.base}/resources -COPY : ${jetty.home}/modules/log4j-impl/resources/log4j.xml to ${jetty.base}/resources/log4j.xml -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-log4j12/1.7.21/slf4j-log4j12-1.7.21.jar to ${jetty.base}/lib/slf4j/slf4j-log4j12-1.7.21.jar -INFO : Base directory was modified - -[my-base]$ tree -. -├── lib -│   ├── log4j -│   │   └── log4j-1.2.17.jar -│   └── slf4j -│   ├── slf4j-api-1.7.21.jar -│   └── slf4j-log4j12-1.7.21.jar -├── resources -│   └── log4j.xml -└── start.d - └── logging-log4j.ini -.... - -Jetty is now configured to log using the Log4j framework. -A standard Log4j configuration file is located in `${jetty.base}/resources/log4j.xml`. - -Or, to set up Log4j2, enable the `logging-log4j2` module. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging-log4j2 - -ALERT: There are enabled module(s) with licenses. -The following 2 module(s): - + contains software not provided by the Eclipse Foundation! - + contains software not covered by the Eclipse Public License! - + has not been audited for compliance with its license - - Module: log4j2-api - + Log4j is released under the Apache 2.0 license. - + http://www.apache.org/licenses/LICENSE-2.0.html - - Module: slf4j-api - + SLF4J is distributed under the MIT License. - + Copyright (c) 2004-2013 QOS.ch - + All rights reserved. - + Permission is hereby granted, free of charge, to any person obtaining - + a copy of this software and associated documentation files (the - + "Software"), to deal in the Software without restriction, including - + without limitation the rights to use, copy, modify, merge, publish, - + distribute, sublicense, and/or sell copies of the Software, and to - + permit persons to whom the Software is furnished to do so, subject to - + the following conditions: - + The above copyright notice and this permission notice shall be - + included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Proceed (y/N)? y -INFO : slf4j-api transitively enabled -INFO : logging-log4j2 initialized in ${jetty.base}/start.d/logging-log4j2.ini -INFO : log4j2-api transitively enabled -INFO : resources transitively enabled -INFO : slf4j-log4j2 transitively enabled -INFO : log4j2-impl transitively enabled -MKDIR : ${jetty.base}/lib/slf4j -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.21/slf4j-api-1.7.21.jar to ${jetty.base}/lib/slf4j/slf4j-api-1.7.21.jar -MKDIR : ${jetty.base}/lib/log4j2 -DOWNLD: https://repo1.maven.org/maven2/org/apache/logging/log4j/log4j-api/2.6.1/log4j-api-2.6.1.jar to ${jetty.base}/lib/log4j2/log4j-api-2.6.1.jar -MKDIR : ${jetty.base}/resources -DOWNLD: https://repo1.maven.org/maven2/org/apache/logging/log4j/log4j-slf4j-impl/2.6.1/log4j-slf4j-impl-2.6.1.jar to ${jetty.base}/lib/log4j2/log4j-slf4j-impl-2.6.1.jar -DOWNLD: https://repo1.maven.org/maven2/org/apache/logging/log4j/log4j-core/2.6.1/log4j-core-2.6.1.jar to ${jetty.base}/lib/log4j2/log4j-core-2.6.1.jar -COPY : ${jetty.home}/modules/log4j2-impl/resources/log4j2.xml to ${jetty.base}/resources/log4j2.xml -INFO : Base directory was modified - -[my-base]$ tree -. -├── lib -│   ├── log4j2 -│   │   ├── log4j-api-2.6.1.jar -│   │   ├── log4j-core-2.6.1.jar -│   │   └── log4j-slf4j-impl-2.6.1.jar -│   └── slf4j -│   └── slf4j-api-1.7.21.jar -├── resources -│   └── log4j2.xml -└── start.d - └── logging-log4j2.ini -.... - -At this point Jetty is configured so that the Jetty server itself will log using Log4j2, using the Log4j2 configuration found in `{$jetty.base}/resources/log4j2.xml`. - -[[example-logging-logback]] -==== 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]. - -To set up Jetty logging via Logback, enable the `logging-logback` module. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging-logback - -ALERT: There are enabled module(s) with licenses. -The following 2 module(s): - + contains software not provided by the Eclipse Foundation! - + contains software not covered by the Eclipse Public License! - + has not been audited for compliance with its license - - Module: logback-impl - + Logback: the reliable, generic, fast and flexible logging framework. - + Copyright (C) 1999-2012, QOS.ch. All rights reserved. - + This program and the accompanying materials are dual-licensed under - + either: - + the terms of the Eclipse Public License v1.0 - + as published by the Eclipse Foundation: - + http://www.eclipse.org/legal/epl-v10.html - + or (per the licensee's choosing) under - + the terms of the GNU Lesser General Public License version 2.1 - + as published by the Free Software Foundation: - + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html - - Module: slf4j-api - + SLF4J is distributed under the MIT License. - + Copyright (c) 2004-2013 QOS.ch - + All rights reserved. - + Permission is hereby granted, free of charge, to any person obtaining - + a copy of this software and associated documentation files (the - + "Software"), to deal in the Software without restriction, including - + without limitation the rights to use, copy, modify, merge, publish, - + distribute, sublicense, and/or sell copies of the Software, and to - + permit persons to whom the Software is furnished to do so, subject to - + the following conditions: - + The above copyright notice and this permission notice shall be - + included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Proceed (y/N)? y -INFO : slf4j-api transitively enabled -INFO : logback-impl transitively enabled -INFO : slf4j-logback transitively enabled -INFO : logging-logback initialized in ${jetty.base}/start.d/logging-logback.ini -INFO : resources transitively enabled -MKDIR : ${jetty.base}/lib/slf4j -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.21/slf4j-api-1.7.21.jar to ${jetty.base}/lib/slf4j/slf4j-api-1.7.21.jar -MKDIR : ${jetty.base}/lib/logback -DOWNLD: https://repo1.maven.org/maven2/ch/qos/logback/logback-core/1.1.7/logback-core-1.1.7.jar to ${jetty.base}/lib/logback/logback-core-1.1.7.jar -MKDIR : ${jetty.base}/resources -COPY : ${jetty.home}/modules/logback-impl/resources/logback.xml to ${jetty.base}/resources/logback.xml -DOWNLD: https://repo1.maven.org/maven2/ch/qos/logback/logback-classic/1.1.7/logback-classic-1.1.7.jar to ${jetty.base}/lib/logback/logback-classic-1.1.7.jar -INFO : Base directory was modified - -[my-base]$ tree -. -├── lib -│   ├── logback -│   │   ├── logback-classic-1.1.7.jar -│   │   └── logback-core-1.1.7.jar -│   └── slf4j -│   └── slf4j-api-1.7.21.jar -├── resources -│   └── logback.xml -└── start.d - └── logging-logback.ini -.... - -At this point Jetty is configured so that the Jetty server itself will log using Logback, using the Logback configuration found in `{$jetty.base}/resources/logback.xml`. - -==== Logging with Java Util Logging - -[[example-logging-java-util-logging]] -===== Java Util Logging with 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] as a binding layer. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging-jul - -ALERT: There are enabled module(s) with licenses. -The following 1 module(s): - + contains software not provided by the Eclipse Foundation! - + contains software not covered by the Eclipse Public License! - + has not been audited for compliance with its license - - Module: slf4j-api - + SLF4J is distributed under the MIT License. - + Copyright (c) 2004-2013 QOS.ch - + All rights reserved. - + Permission is hereby granted, free of charge, to any person obtaining - + a copy of this software and associated documentation files (the - + "Software"), to deal in the Software without restriction, including - + without limitation the rights to use, copy, modify, merge, publish, - + distribute, sublicense, and/or sell copies of the Software, and to - + permit persons to whom the Software is furnished to do so, subject to - + the following conditions: - + The above copyright notice and this permission notice shall be - + included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Proceed (y/N)? y -INFO : jul-impl transitively enabled -INFO : slf4j-api transitively enabled -INFO : slf4j-jul transitively enabled -INFO : logging-jul initialized in ${jetty.base}/start.d/logging-jul.ini -INFO : resources transitively enabled -MKDIR : ${jetty.base}/etc -COPY : ${jetty.home}/modules/jul-impl/etc/java-util-logging.properties to ${jetty.base}/etc/java-util-logging.properties -MKDIR : ${jetty.base}/lib/slf4j -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.21/slf4j-api-1.7.21.jar to ${jetty.base}/lib/slf4j/slf4j-api-1.7.21.jar -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-jdk14/1.7.21/slf4j-jdk14-1.7.21.jar to ${jetty.base}/lib/slf4j/slf4j-jdk14-1.7.21.jar -INFO : Base directory was modified - -[my-base]$ tree -. -├── etc -│   └── java-util-logging.properties -├── lib -│   └── slf4j -│   ├── slf4j-api-1.7.21.jar -│   └── slf4j-jdk14-1.7.21.jar -└── start.d - └── logging-jul.ini -.... - -Jetty is now configured to log using the JUL framework. -A standard JUL properties file is located in `${jetty.base}/etc/java-util-logging.properties`. - -==== Capturing Console Output - -By default, enabling the above modules will output log information to the console. -Included in the distribution is the `console-capture` module, which can be used in lieu of additional configuration to the selected logging module to capture this output to a `logs` directory in your `${jetty.base}`. -To enable this functionality, activate the `console-capture` module. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=console-capture -INFO : console-capture initialized in ${jetty.base}/start.d/console-capture.ini -MKDIR : ${jetty.base}/logs -INFO : Base directory was modified - -[my-base]$ tree -. -├── logs -└── start.d - └── console-capture.ini -.... - -As an example, here is the output from Logback before using the `console-capture` module: - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar -419 [main] INFO org.eclipse.jetty.util.log - Logging initialized @508ms to org.eclipse.jetty.util.log.Slf4jLog -540 [main] INFO org.eclipse.jetty.server.Server - jetty-{VERSION} -575 [main] INFO o.e.jetty.server.AbstractConnector - Started ServerConnector@3c0ecd4b{HTTP/1.1,[http/1.1]}{0.0.0.0:8080} -575 [main] INFO org.eclipse.jetty.server.Server - Started @668ms -.... - -After enabling `console-capture`, the output is as follows, which displays the location the log is being saved to: - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar -151 [main] INFO org.eclipse.jetty.util.log - Logging initialized @238ms to org.eclipse.jetty.util.log.Slf4jLog -196 [main] INFO org.eclipse.jetty.util.log - Console stderr/stdout captured to /installs/my-jetty-base/logs/2016_10_21.jetty.log -.... diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/default-logging-with-stderrlog.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/default-logging-with-stderrlog.adoc deleted file mode 100644 index 30175b3db0a6..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/default-logging-with-stderrlog.adoc +++ /dev/null @@ -1,156 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[default-logging-with-stderrlog]] -=== Default Logging with Jetty's StdErrLog - -[[stderrlog-configuration]] -==== StdErrLog Configuration - -If you do nothing to configure a separate logging framework, 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 `StdErrLog`-based logging is output to the console. - -Included in the Jetty distribution is a logging module named `console-capture` that is capable of performing simple capturing of all STDOUT (`System.out`) and STDERR (`System.err`) output to a file that is rotated daily. - -To enable this feature, simply activate the `console-capture` module on the command line: - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=console-capture -INFO : console-capture initialized in ${jetty.base}/start.d/console-capture.ini -MKDIR : ${jetty.base}/logs -INFO : Base directory was modified - -[my-base]$ tree -. -├── logs -└── start.d - └── console-capture.ini -.... - -The default configuration for logging output will create a file `${jetty.base}/logs/yyyy_mm_dd.stderrout.log` which allows configuration of the output directory by setting the `jetty.logs` property. - -____ -[NOTE] -By default, logs are not set to be appended, meaning a the log file is wiped clean upon sever restart. -You can change this setting by editing the `console-capture.ini` and un-commenting the line that reads `jetty.console-capture.append=true`. -____ - - -Just enabling the `console-capture` will simply output the values of STDERR and STDOUT to a log file. -To customize the log further, a module named `logging-jetty` is available to provides a default properties file to configure. -As with `console-capture`, you activate the `logging-jetty` on the command line. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging-jetty -INFO : logging-jetty initialized in ${jetty.base}/start.d/logging-jetty.ini -INFO : resources transitively enabled -MKDIR : ${jetty.base}/resources -COPY : ${jetty.home}/modules/logging-jetty/resources/jetty-logging.properties to ${jetty.base}/resources/jetty-logging.properties -INFO : Base directory was modified - -[my-base]$ tree -. -├── logs -├── resources -│   └── jetty-logging.properties -└── start.d - ├── console-capture.ini - └── logging-jetty.ini -.... - -Once activated, you can find the properties file at `${jetty.base}/resources/jetty-logging.properties`. -By default, the following parameters are defined. -To change them, un-comment the line and substitute your naming scheme and configuration choices. - -[source, properties, subs="{sub-order}"] -.... -## Force jetty logging implementation -#org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StdErrLog - -## Set logging levels from: ALL, DEBUG, INFO, WARN, OFF -#org.eclipse.jetty.LEVEL=INFO -#com.example.LEVEL=INFO - -## Hide stacks traces in logs? -#com.example.STACKS=false - -## Show the source file of a log location? -#com.example.SOURCE=false -.... - -There are a number of properties that can be defined in the configuration that will affect the behavior of StdErr logging with `console-capture`. - -`.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. -`.SOURCE=`:: -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. -`.STACKS=`:: -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=`:: -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=`:: -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: -+ -[source, screen, subs="{sub-order}"] -.... -2016-10-21 15:31:01.248:INFO::main: Logging initialized @332ms to org.eclipse.jetty.util.log.StdErrLog -2016-10-21 15:31:01.370:INFO:oejs.Server:main: jetty-{VERSION} -2016-10-21 15:31:01.400:INFO:oejs.AbstractConnector:main: Started ServerConnector@2c330fbc{HTTP/1.1,[http/1.1]}{0.0.0.0:8080} -2016-10-21 15:31:01.400:INFO:oejs.Server:main: Started @485ms -.... -+ -* Example when set to true: -+ -[source, screen, subs="{sub-order}"] -.... -2016-10-21 15:31:35.020:INFO::main: Logging initialized @340ms to org.eclipse.jetty.util.log.StdErrLog -2016-10-21 15:31:35.144:INFO:org.eclipse.jetty.server.Server:main: jetty-{VERSION} -2016-10-21 15:31:35.174:INFO:org.eclipse.jetty.server.AbstractConnector:main: Started ServerConnector@edf4efb{HTTP/1.1,[http/1.1]}{0.0.0.0:8080} -2016-10-21 15:31:35.175:INFO:org.eclipse.jetty.server.Server:main: Started @495ms -.... - -[[deprecated-parameters]] -==== 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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-apache-log4j.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-apache-log4j.adoc deleted file mode 100644 index ab7052b536ad..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-apache-log4j.adoc +++ /dev/null @@ -1,63 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -=== 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. - -[source,screen,subs="{sub-order}"] -.... -[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 .. - -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging -INFO: logging initialised in ${jetty.base}/start.ini (appended) -MKDIR: ${jetty.base}/logs -DOWNLOAD: https://repo1.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://repo1.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: https://repo1.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 - -[my-base]$ java -jar /path/to/jetty-home/start.jar -.... - -The replacement `logging.mod` performs a number of tasks. - -. `mybase` is a `${jetty.base}` directory. -. The jetty-home is unpacked (and untouched) into `/opt/jetty-home/` and becomes the `${jetty.home}` directory for this demonstration. -. The `curl` command downloads the replacement `logging.mod` and puts it into the `${jetty.base}/modules/` directory for use by mybase only. -. The `start.jar --add-to-start=logging` command performs a number of steps to make the logging module available to the `${jetty.base}` configuration. -.. The `--module=logging` command is added to the `${jetty.base}/start.ini` configuration. -.. Required `${jetty.base}` directories are created: `${jetty.base}/logs` and `${jetty.base}/resources` -.. 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. -.. Required configuration files are downloaded (if not present already): `jetty-logging.properties`, and `log4j.properties` -* The configuration files are placed in the `${jetty.base}/resources/` directory. - -At this point the Jetty `mybase` is configured so that the Jetty server itself will log using log4j, using the log4j configuration found in `mybase/resources/log4j.properties`. - -The server classpath can be verified 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...). diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-java-util-logging-native.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-java-util-logging-native.adoc deleted file mode 100644 index a58357a83f17..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-java-util-logging-native.adoc +++ /dev/null @@ -1,86 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -=== 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 native 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`. - -[source,screen,subs="{sub-order}"] -.... -[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 .. - -[my-base]$ java -jar /path/to/jetty-home/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} - -[my-base]$ java -jar /path/to/jetty-home/start.jar -.... - -The replacement `logging.mod` performs a number of tasks. - -. `mybase` is a `${jetty.base}` directory. -. The jetty-home is unpacked (and untouched) into `/opt/jetty-home/` and becomes the `${jetty.home}` directory for this demonstration. -. The `curl` command downloads the replacement `logging.mod` and puts it into the `${jetty.base}/modules/` directory for use by `mybase` only. -. The `start.jar --add-to-start=logging` command performs a number of steps to make the logging module available to the `${jetty.base}` -configuration. -.. The `--module=logging` command is added to the `${jetty.base}/start.ini` configuration. -.. Required `${jetty.base}` directories are created: `${jetty.base}/logs` and `${jetty.base}/resources`. -.. 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. -.. 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. - -At this point the Jetty `mybase` is 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`. - -The server classpath can be verified 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 and `java.util.logging` events emitted by the Jetty server go to `java.util.logging` for routing (to console, file, etc...). - -If there any custom `java.util.logging` handlers to be used, put the implementation jar in the `${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 official `java.util.logging.LogManager` javadoc http://docs.oracle.com/javase/7/docs/api/java/util/logging/LogManager.html[documentation from Oracle]. -____ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-java-util-logging.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-java-util-logging.adoc deleted file mode 100644 index bb970a3cd153..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-java-util-logging.adoc +++ /dev/null @@ -1,81 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -=== 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`. - -[source,screen,subs="{sub-order}"] -.... -[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 .. - -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging -INFO: logging initialised in ${jetty.base}/start.ini (appended) -MKDIR: ${jetty.base}/logs -DOWNLOAD: https://repo1.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: https://repo1.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 - -[my-base]$ java -jar /path/to/jetty-home/start.jar -.... - -The replacement `logging.mod` performs a number of tasks. - -. `mybase` is a `${jetty.base}` directory -. The jetty-home is unpacked (and untouched) into `/opt/jetty-home/` and becomes the `${jetty.home}` directory for this demonstration. -. The `curl` command downloads the replacement `logging.mod` and puts it into the `${jetty.base}/modules/` directory for use by `mybase` only. -. The `start.jar --add-to-start=logging` command performs a number of steps to make the logging module available to the `${jetty.base}` configuration. -.. The `--module=logging` command is added to the `${jetty.base}/start.ini` configuration. -.. Required `${jetty.base}` directories are created: `${jetty.base}/logs` and `${jetty.base}/resources`. -.. Required libraries are downloaded (if not present already): slf4j-api, and slf4j-jdk14. -* The libraries are put in the `${jetty.base}/lib/logging/` directory. -.. 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. -.. 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. - -At this point the Jetty `mybase` is 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`. - -The server classpath can be verified 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 there any custom `java.util.logging` handlers to be used, put the implementation jar in the `${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 official `java.util.logging.LogManager` javadoc http://docs.oracle.com/javase/7/docs/api/java/util/logging/LogManager.html[documentation from Oracle]. -____ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback-centralized-logging.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback-centralized-logging.adoc deleted file mode 100644 index 10441f011309..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback-centralized-logging.adoc +++ /dev/null @@ -1,139 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[example-logging-logback-centralized]] -=== Centralized Logging using 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#getSystemClasspathPattern()[WebAppContext.getSystemClasspathPattern().add(String)] for the common logging classes. -See https://github.com/jetty-project/jetty-webapp-logging/blob/master/jetty-webapp-logging/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. - -[source,screen,subs="{sub-order}"] -.... -[mybase]$ curl -O https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-webapp-logging/9.4.27/jetty-webapp-logging-9.4.27-config.jar - % Total % Received % Xferd Average Speed Time Time Time Current - Dload Upload Total Spent Left Speed -100 3402 100 3402 0 0 15823 0 --:--:-- --:--:-- --:--:-- 15750 - -[mybase]$ jar -xf jetty-webapp-logging-9.4.27-config.jar - -[my-base]$ java -jar /path/to/jetty-home/start.jar --create-startd --add-to-start=centralized-webapp-logging - -ALERT: There are enabled module(s) with licenses. -The following 2 module(s): - + contains software not provided by the Eclipse Foundation! - + contains software not covered by the Eclipse Public License! - + has not been audited for compliance with its license - - Module: logback-impl - + Logback: the reliable, generic, fast and flexible logging framework. - + Copyright (C) 1999-2012, QOS.ch. All rights reserved. - + This program and the accompanying materials are dual-licensed under - + either: - + the terms of the Eclipse Public License v1.0 - + as published by the Eclipse Foundation: - + http://www.eclipse.org/legal/epl-v10.html - + or (per the licensee's choosing) under - + the terms of the GNU Lesser General Public License version 2.1 - + as published by the Free Software Foundation: - + http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html - - Module: slf4j-api - + SLF4J is distributed under the MIT License. - + Copyright (c) 2004-2013 QOS.ch - + All rights reserved. - + Permission is hereby granted, free of charge, to any person obtaining - + a copy of this software and associated documentation files (the - + "Software"), to deal in the Software without restriction, including - + without limitation the rights to use, copy, modify, merge, publish, - + distribute, sublicense, and/or sell copies of the Software, and to - + permit persons to whom the Software is furnished to do so, subject to - + the following conditions: - + The above copyright notice and this permission notice shall be - + included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Proceed (y/N)? y -INFO : slf4j-api transitively enabled -INFO : log4j-over-slf4j transitively enabled -INFO : jcl-slf4j transitively enabled -INFO : logback-impl transitively enabled -INFO : jul-slf4j transitively enabled -INFO : slf4j-logback transitively enabled -INFO : centralized-webapp-logging initialized in ${jetty.base}/start.d/centralized-webapp-logging.ini -INFO : logging-logback transitively enabled -INFO : resources transitively enabled -MKDIR : ${jetty.base}/lib/slf4j -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar to ${jetty.base}/lib/slf4j/slf4j-api-1.7.25.jar -MKDIR : ${jetty.base}/lib/logging -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/log4j-over-slf4j/1.7.25/log4j-over-slf4j-1.7.25.jar to ${jetty.base}/lib/logging/log4j-over-slf4j-1.7.25.jar -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/jcl-over-slf4j/1.7.25/jcl-over-slf4j-1.7.25.jar to ${jetty.base}/lib/slf4j/jcl-over-slf4j-1.7.25.jar -MKDIR : ${jetty.base}/lib/logback -DOWNLD: https://repo1.maven.org/maven2/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar to ${jetty.base}/lib/logback/logback-core-1.2.3.jar -DOWNLD: https://repo1.maven.org/maven2/org/slf4j/jul-to-slf4j/1.7.25/jul-to-slf4j-1.7.25.jar to ${jetty.base}/lib/slf4j/jul-to-slf4j-1.7.25.jar -COPY : ${jetty.home}/modules/jul-slf4j/etc/java-util-logging.properties to ${jetty.base}/etc/java-util-logging.properties -DOWNLD: https://repo1.maven.org/maven2/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar to ${jetty.base}/lib/logback/logback-classic-1.2.3.jar -MKDIR : ${jetty.base}/logs -DOWNLD: https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-webapp-logging/9.4.27/jetty-webapp-logging-9.4.27.jar to ${jetty.base}/lib/logging/jetty-webapp-logging-9.4.27.jar -INFO : Base directory was modified - -$ -.... - -This replacement `centralized-webapp-logging.mod` performs a number of tasks. - -. `mybase` is a `${jetty.base}` directory. -. The jetty-home is unpacked (and untouched) into `/opt/jetty-home/` and becomes the `${jetty.home}` directory for this demonstration. -. The `curl` command downloads the replacement config overlay for the `${jetty.base}/modules/` directory to use. -. The `start.jar --add-to-start=centralized-webapp-logging` command performs a number of steps to make the centralized-webapp-logging module available to the `${jetty.base}` configuration. -.. A new `${jetty.base}/start.d/centralized-webapp-logging.ini` configuration was created. -.. Required `${jetty.base}` directories are created: `${jetty.base}/logs` and `${jetty.base}/resources`. -.. Required logging libraries are downloaded (if not present already) to the `${jetty.base}/lib/logging/` directory: -* `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. -.. Required webapp-logging library is downloaded (if not present already) to the `${jetty.base}/lib/webapp-logging/` directory: -* `jetty-webapp-logging.jar` - the Jetty side deployment manger app-lifecycle bindings for modifying the `WebAppClassloaders` of deployed webapps. - -At this point the Jetty `mybase` is 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. - -The server classpath can be verified 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 implementation) for routing (to console, file, etc...). diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback-sifting.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback-sifting.adoc deleted file mode 100644 index a821e19aeb76..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback-sifting.adoc +++ /dev/null @@ -1,36 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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. -This can be done 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. -|======================================================================= diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback.adoc deleted file mode 100644 index af00b0ab6d89..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-logback.adoc +++ /dev/null @@ -1,59 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -=== 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 the `${jetty.base}` directory for logging with logback. - -[source,screen,subs="{sub-order}"] -.... -[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 .. - -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging -INFO: logging initialised in ${jetty.base}/start.ini (appended) -MKDIR: ${jetty.base}/logs -DOWNLOAD: https://repo1.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://repo1.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: https://repo1.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 - -[my-base]$ java -jar /path/to/jetty-home/start.jar -.... - -The replacement `logging.mod` performs a number of tasks. - -. `mybase` is a `${jetty.base}` directory. -. The jetty-home is unpacked (and untouched) into `/opt/jetty-home/` and becomes the `${jetty.home}` directory for this demonstration. -. The `curl` command downloads the replacement `logging.mod` and puts it into the `${jetty.base}/modules/` directory for use by `mybase` only. -. The `start.jar --add-to-start=logging` command performs a number of steps to make the logging module available to the `${jetty.base}` configuration. -.. The `--module=logging` command is added to the `${jetty.base}/start.ini` configuration. -.. Required `${jetty.base}` directories are created: `${jetty.base}/logs` and `${jetty.base}/resources`. -.. Required libraries are downloaded (if not present already) to the `${jetty.base}/lib/logging/` directory: slf4j-api, logback-core, and logback-classic. -.. Required configuration files are downloaded (if not present already) to the `${jetty.base}/lib/resources/` directory.: `jetty-logging.properties`, and `logback.xml`. - -At this point the Jetty `mybase` is configured so that the Jetty server itself will log using Logback, using the Logback configuration found in `mybase/resources/logback.xml` - -The server classpath can be verified 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...). diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-slf4j-multiple-loggers.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-slf4j-multiple-loggers.adoc deleted file mode 100644 index 28de30353018..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/logging/example-slf4j-multiple-loggers.adoc +++ /dev/null @@ -1,137 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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. - -A single logging solution can be configured for the variety of logging libraries available in common use when using Slf4j.With careful setup, all of the following logging APIs can be supported at the same time, with a single configuration file to control the output of events produced. - -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 configuration a single underlying logging framework should first be chosen. -This decision guides the rest of the choices about jar files to place on the server classpath. - -____ -[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. -____ - -.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 the 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). - -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 the `${jetty.base}` directory for capturing all Jetty server logging from multiple logging frameworks into a single logging output file managed by logback. - -[source,screen,subs="{sub-order}"] -.... -[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 .. - -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=logging -INFO: logging initialised in ${jetty.base}/start.ini (appended) -MKDIR: ${jetty.base}/logs -DOWNLOAD: https://repo1.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://repo1.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: https://repo1.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: https://repo1.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: https://repo1.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: https://repo1.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 - -[my-base]$ java -jar /path/to/jetty-home/start.jar -.... - -The replacement `logging.mod` performs a number of tasks. - -. `mybase` is a `${jetty.base}` directory. -. The jetty-home is unpacked (and untouched) into `/opt/jetty-home/` and becomes the `${jetty.home}` directory for this demonstration. -. The `curl` command downloads the replacement `logging.mod` and puts it into the `${jetty.base}/modules/` directory for use by `mybase` only. -. The `start.jar --add-to-start=logging` command performs a number of steps to make the logging module available to the `${jetty.base}` configuration. -.. The `--module=logging` command is added to the `${jetty.base}/start.ini` configuration. -.. Required `${jetty.base}` directories are created: `${jetty.base}/logs` and `${jetty.base}/resources`. -.. Required libraries are downloaded (if not present already) to the the `${jetty.base}/lib/logging/` directory: -* `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. -.. Required configuration files are downloaded (if not present already) to the `${jetty.base}/resources/` directory: `jetty-logging.properties`, and `logback.xml` -.. Required `java.util.logging` initialization commands are downloaded (if not present already) to the `${jetty.base}/etc/` directory: `jetty-logging.xml` - -At this point the Jetty `mybase` is 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. - -The server classpath can be verified 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...). diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/maven/jetty-maven-scanning.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/maven/jetty-maven-scanning.adoc deleted file mode 100644 index 65dc523201ab..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/maven/jetty-maven-scanning.adoc +++ /dev/null @@ -1,47 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-maven-scanning]] -=== Files Scanned by the Jetty Maven Plugin - -If you set a non zero `scanIntervalSeconds` link:#jetty-maven-plugin[configuration parameter], the `jetty-maven-plugin` will scan certain files for changes, and redeploy the webapp if necessary. -The files that are scanned depend on the goal being executed. - -[[scanner-matrix]] -==== Scanner Matrix - -[width="100%",cols="1,2a",options="header"] -|======================================================================= -|Goal |Files -|link:#jetty-run-goal[jetty:run] -| -* pom.xml -* -* -* -* or src/main/webapp/WEB-INF/web.xml -* or src/main/webapp/WEB-INF/jetty-web.xml -* /WEB-INF/jetty-web.xml -* -* -* any link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setDefaultsDescriptor%28java.lang.String%29[defaultsDescriptor] for the webapp -* any link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setOverrideDescriptor%28java.lang.String%29[overrideDescriptor] for the webapp -* any dependencies that are wars or zips - -|link:#running-assembled-webapp-as-war[jetty:run-war] -| - -* pom.xml -* - -|======================================================================= diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/chapter.adoc deleted file mode 100644 index 7b0042eb038e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/chapter.adoc +++ /dev/null @@ -1,31 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[platforms]] -== Platforms, Stacks and Alternative Distributions - -=== Many many options... - -In addition to using Jetty in its distribution form and its multiple embedded forms, there are a number of alternative ways to use Jetty. -Many products and open source projects out there distribute Jetty themselves, in both distribution and embedded forms, not to mention different operating systems bundling Jetty in other installable forms. - -If your platform supports Jetty from a distribution or deployment perspective and want to be included on this list just fork the documentation and submit a pull request, or contact us. -Check out our list of https://jetty.org/powered[Powered By] page for software that makes use of Jetty, often in novel and exciting ways. - -include::jelastic.adoc[] -include::cloudfoundry.adoc[] -include::elastic-beanstalk.adoc[] -include::fedora.adoc[] -include::ubuntu.adoc[] - - diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/cloudfoundry.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/cloudfoundry.adoc deleted file mode 100644 index 60f36d599ffe..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/cloudfoundry.adoc +++ /dev/null @@ -1,138 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[cloudfoundry]] -=== CloudFoundry - -____ -[WARNING] -This is an increasingly aged integration, things like likely changed enough this is not directly useful but may serve as a useful starting point should someone want to look into it. -____ - -[[cloudfoundry-overview]] -==== Overview - -http://www.cloudfoundry.com[CloudFoundry] is an open platform intended as a place to deploy end user applications in a manner which is both simple and eminently scalable to fit the needs of the application. -With the release of their V2 framework the Jetty project has created a buildpack which allows you to deploy your java based web application onto Jetty and still make use of the remainder of the CloudFoundry platform. - -This buildpack itself is quite simple to use. -A collection of ruby scripting and the buildpack conventions will allow Jetty to be downloaded, configured and customized to your needs and then have your web application deployed onto it. -While the default buildpack we have created is useful to deploy a stock configuration of jetty, it is quite likely that you will want to fork the buildpack and tweak it to fit your immediate needs. -This process is made trivial since buildpacks install from a github repository. -For example, to change the jetty version simply fork it in GitHub and tweak the `JETTY_VERSION` string in the `jetty_web.rb` file. - -If you have additional modifications to make to the Jetty server, like perhaps configuring additional static contexts, setting up a proxy servlet, adding jar files to the jetty home/lib/ext directory, etc you can either adapt the ruby scripting directly or place them under the appropriate location in the `/resources` directory of this buildpack and they will be copied into the correct location. - -For the time being I'll leave this buildpack under my personal github account and should there be interest expressed I am more then happy to push it over to https://github.com/jetty-project down the road for proper contributions, etc. - -[[cloudfoundry-usage]] -==== Usage - -To show how incredibly easy it is to use the Jetty buildpack with cloudfoundry, this is all the more you need to do to deploy your application. -Refer to the CloudFoundry http://docs.cloudfoundry.com/[documentation] to get started, get the `cf` utilities installed and an environment configured. - -[source, screen, subs="{sub-order}"] -.... -$ cf push snifftest --buildpack=git://github.com/jmcc0nn3ll/jetty-buildpack.git - -.... - -____ -[TIP] -In this example the web application is uploaded from the *current* directory so make sure you have changed directory into the root of your web application. -The `snifftest` on the commandline refers to what you are calling the application, not the directory to deploy. -Also note that the webapplication is installed into the `ROOT` context of Jetty as is available at the root context of the server. -Any additional web applications will have to be configured within the buildpack as mentioned above. -____ - -You will be prompted to answer a series of questions describing the execution environment and any additional services you need enabled (databases, etc). - -[source, plain, subs="{sub-order}"] ----- - -Instances> 1 - -Custom startup command> none - -1: 64M -2: 128M -3: 256M -4: 512M -5: 1G -Memory Limit> 256M - -Creating snifftest... OK - -1: snifftest -2: none -Subdomain> snifftest - -1: a1-app.cf-app.com -2: none -Domain> a1-app.cf-app.com - -Binding snifftest.a1-app.cf-app.com to snifftest... OK - -Create services for application?> n - -Save configuration?> n - - ----- - -Once answered you will see the installation process of your application. - -[source, plain, subs="{sub-order}"] ----- - -Uploading snifftest... OK -Starting snifftest... OK --> Downloaded app package (4.0K) -Initialized empty Git repository in /tmp/buildpacks/jetty-buildpack.git/.git/ -Installing jetty-buildpack.git. -Downloading JDK... -Copying openjdk-1.7.0_21.tar.gz from the buildpack cache ... -Unpacking JDK to .jdk -Downloading Jetty: jetty-home-{VERSION}.tar.gz -Downloading jetty-home-{VERSION}.tar.gz from http://repo2.maven.org/maven2/org/eclipse/jetty/jetty-home/10.0.0.v202012xx/ ... -Unpacking Jetty to .jetty --> Uploading staged droplet (36M) --> Uploaded droplet -Checking snifftest... -Staging in progress... -Staging in progress... -Staging in progress... -Staging in progress... -Staging in progress... -Staging in progress... - 0/1 instances: 1 starting - 0/1 instances: 1 starting - 0/1 instances: 1 starting - 0/1 instances: 1 starting - 1/1 instances: 1 running -OK - ----- - -The application is now available at the configured location! Under the url `http://snifftest.a1-app.cf-app.com/` in this particular example. - -[[cloudfoundry-acknowledgements]] -==== Acknowledgements - -The Jetty buildpack was forked from the CloudFoundry Java buildpack. The Virgo Buildpack that Glyn worked on was used as a sanity check. - -* http://github.com/cloudfoundry/cloudfoundry-buildpack-java -* http://github.com/glyn/virgo-buildpack - -CloudFoundry buildpacks were modelled on Heroku buildpacks. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/elastic-beanstalk.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/elastic-beanstalk.adoc deleted file mode 100644 index 1698ed207b73..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/elastic-beanstalk.adoc +++ /dev/null @@ -1,83 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[elastic-beanstalk]] -=== Amazon Elastic Beanstalk - -____ -[WARNING] -This is an increasingly aged integration, things like likely changed enough this is not directly useful but may serve as a useful starting point should someone want to look into it. -____ - - -http://aws.amazon.com/elasticbeanstalk/[Elastic Beanstalk] is a component with the http://aws.amazon.com[Amazon Web Services] offering that allows you to configure an entire virtual machine based on one of several available baseline configurations and then customize it through a powerful configuration system. While the default offerings currently available are based on Tomcat for for the java community, we worked out the basics using that configuration system to enable the usage of Jetty instead. - -[[elastic-beanstalk-overview]] -==== Overview - -Elastic beanstalk has a very http://aws.amazon.com/about-aws/whats-new/2012/10/02/introducing-aws-elastic-beanstalk-configuration-files/[powerful configuration mechanism] so this integration taps into that to effectively rework the tomcat configuration and replace it with the bits required to make jetty run in its place. Below is a walk through of what the various configuration files are doing and how the general flow of configuration on beanstalk happens. - -There is an `.ebextensions` directory in your beanstalk application which contains all of the files requires to configure and customize your beanstalk and application combo. -Files that end in .config in this directory are processed in alphabetical order. - -00-java7.config:: - installs java 7 onto the beanstalk environment and makes it the default -10-tweak.config:: - not required, but changes the `/opt/elasticbeanstalk` directory to be readable making debugging easier -11-jetty.config:: - installs jetty9 into `/opt/jetty-9` and removes unneeded distribution files -12-beanstalk.config:: - handles replacing tomcat with jetty in many configuration files, configures logging and wires up system startup processes. - Some files in your `.ebextensions` directory are moved to replace files under /opt/elasticbeanstalk. - -If you look in the `.ebextensions` directory of your application you should also see other jetty specific xml and ini files. -The final config file handles these as they are largely customization for your application. - -20-testapp.config:: - layers application specific configuration files into the jetty installation - -The files in our example test webapp here enable various OPTIONS for libraries that need to be loaded, customize the root application being deployed and even deploy additional contexts like we do in our jetty distribution demo. -This is also the mechanism that you would use to wire up application specific things, for example if you needed additional software installed, customized directories made, etc. - -[[elastic-beanstalk-maven]] -==== Maven Bits - -Support for this feature leverages Maven to make things easy and is composed of three different modules. - -jetty-beanstalk-overlay:: - This is the collection of scripts that are required to wedge jetty into the normal beanstalk setup. - This module is intended to extract into an webapp to enable it for beanstalk usage with jetty. -jetty-beanstalk-resources:: - This generates an artifact of files that are downloaded by the configuration process and contains replacements for certain beanstalk files as well as various system level jetty configuration files like an updated `jetty.sh` script for the `/etc/init.d` setup. -jetty-beanstalk-testapp:: - An example webapp that shows both how to combine the war file from another maven module with the jetty-beanstalk-overlay to produce a beanstalk enabled application bundle. - Also included is examples of how to alter the jetty configuration for things like a customized - `start.ini` file. - -____ -[NOTE] -The test webapps needs access to a snapshot version of the test-jetty-webapp so it really serves as more of an example of how to layer your webapp with the bits required to customize your app for beanstalk and jetty. -____ - -To actually make use of these artifacts you currently must clone this git repository and build it locally. -Once you have the artifacts you simply need to copy the approach in the jetty-beanstalk-testapp to apply the configuration to your webapp. - -* https://github.com/jmcc0nn3ll/jetty-beanstalk - -____ -[IMPORTANT] -Bluepill is used to manage the start and stop process of the app server. -This seems to be a problematic bit of software with a colored history and the version in use at the time of this writing is old. -When starting and stopping (or restarting) the appserver you may see error messages show up that the Server timed out getting a response or things like that. -These are red herrings and my experience is that jetty has started and stopped just fine, the pid file required shows up in a very timely fashion (under `/var/run/jetty.pid`) so do check that the app server has started, but please be aware there is a strangeness here that hasn't been sorted out yet. -____ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/fedora.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/fedora.adoc deleted file mode 100644 index d65f5050734e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/fedora.adoc +++ /dev/null @@ -1,21 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[fedora]] -=== Fedora - -As of Fedora 19, Jetty 9 is the version of Jetty available. -This distribution of Jetty is not created or maintained by the Jetty project though we have had a fair amount of communication with the folks behind it and we are very pleased with how this Linux distribution has stayed current. -Releases are kept largely in sync with our releases as there is a wonderful automatic notification mechanism in place for Fedora that detects our releases and immediately opens an issue for them to update. - -* https://admin.fedoraproject.org/pkgdb/acls/name/jetty[Jetty on Fedora] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/jelastic.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/jelastic.adoc deleted file mode 100644 index 5e3ad175643a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/jelastic.adoc +++ /dev/null @@ -1,21 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jelastic]] -=== Jelastic - -Jelastic is a wonderful place to host your applications with solid support for Jetty. -As a cloud hosting platform they take the majority of configuration and installation details out of the picture and focus on letting you focus on your web application. - -* http://jelastic.com/why[Why Jelastic?] -* http://jelastic.com/jetty-hosting[Jetty Hosting] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/ubuntu.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/ubuntu.adoc deleted file mode 100644 index 36471bb9da6f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/platforms/ubuntu.adoc +++ /dev/null @@ -1,20 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[ubuntu]] -=== Ubuntu - -Currently there are no actual `.deb` files available for installing on Debian based Linux machines but there is a handy blog that as been largely been kept up to date on the steps involved through the comments. - -* http://pietervogelaar.nl/ubuntu-12-04-install-jetty-9/[Install Jetty9 -on Ubuntu] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/runner/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/runner/chapter.adoc deleted file mode 100644 index 53edb95aec6e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/runner/chapter.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/runner/jetty-runner.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/runner/jetty-runner.adoc deleted file mode 100644 index 59d57ab1876f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/runner/jetty-runner.adoc +++ /dev/null @@ -1,344 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 file and as much default configuration as possible. -Of course, if your webapp is not as 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. Download the `jetty-runner` jar available at https://repo1.maven.org/maven2/org/eclipse/jetty/jetty-runner/[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 performing the following: - -[source, screen, subs="{sub-order}"] -.... -> 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: - -[source, screen, subs="{sub-order}"] -.... -> 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: - -[source, screen, subs="{sub-order}"] -.... -> 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]. -____ - -By default, `jetty-runner` implements all Configuration Classes so that users can set up and deploy new instances with as little configuration as possible. -If you wish to only implement certain Configuration Classes, they will need to be defined in the context xml for the webapp/context. -The default Configuration Classes are: - -`org.eclipse.jetty.webapp.WebInfConfiguration` -`org.eclipse.jetty.webapp.WebXmlConfiguration` -`org.eclipse.jetty.webapp.MetaInfConfiguration` -`org.eclipse.jetty.webapp.FragmentConfiguration` -`org.eclipse.jetty.webapp.JettyWebXmlConfiguration` -`org.eclipse.jetty.plus.webapp.EnvConfiguration` -`org.eclipse.jetty.plus.webapp.PlusConfiguration` -`org.eclipse.jetty.annotations.AnnotationConfiguration` - -You can learn more about implementing specific Configuration Classes link:https://jetty.org/docs/[in the Jetty documentation.] - -==== 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): - -[source, screen, subs="{sub-order}"] -.... -> 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 won't need to use the command line switches. -Just provide the list of context files like so: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar my-first-context.xml my-second-context.xml my-third-context.xml -.... - -____ -[NOTE] -Switched used on the command line 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: - -[source, screen, subs="{sub-order}"] -.... -> 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: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --config jetty.xml --config jetty-https.xml simple.war -.... - -[[runner-configuration-reference]] -==== Full Configuration Reference - -You can see the fill set of configuration options using the `--help` switch: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --help -.... - -Here's what the output will look like: - -[source, plain, subs="{sub-order}"] ----- - -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 (or -DSTOP.PORT=n) - --stop-key n - security string for stop command (required if --stop-port is present) (or -DSTOP.KEY=n) - [--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. - -[source, screen, subs="{sub-order}"] -.... -> 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. - -[source, screen, subs="{sub-order}"] -.... -> 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. - -[source, screen, subs="{sub-order}"] -.... -> 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: - -[source, screen, subs="{sub-order}"] -.... -> 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. - -[source, screen, subs="{sub-order}"] -.... -> 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` (or `-DSTOP.PORT=` and `-DSTOP.KEY=`, respectively) parameters as arguments to the `jetty-runner`: - -[source, screen, subs="{sub-order}"] -.... -> 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 a custom class. -Here's how to use a Jetty installation to perform a stop: - -[source, screen, subs="{sub-order}"] -.... -> java -jar start.jar -DSTOP.PORT=8181 -DSTOP.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.base}/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: - -[source, screen, subs="{sub-order}"] -.... -> 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: - -[source, screen, subs="{sub-order}"] -.... -> 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: - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --classes /opt/stuff/classes my.war -.... - -____ -[NOTE] -When using the `--jar` and/or `--lib` arguments, by default these will *not* be inspected for `META-INF` information such as `META-INF/resources`, `META-INF/web-fragment.xml`, or `META-INF/taglib.tld`. -If you require these jar files inspected you will need to define the jar pattern in your context xml file. -Jetty-Runner automatically provides and appends a suitable pattern for jtsl taglibs (this pattern is different than the one in the standard Jetty distribution). -____ - - -===== 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: - -[source, screen, subs="{sub-order}"] -.... -> 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: - -[source, screen, subs="{sub-order}"] -.... -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 - -[source, screen, subs="{sub-order}"] -.... -> java -jar jetty-runner.jar --stats realm.properties my.war -.... - -After navigating to http://localhost:8080/ a few times, we can point 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 -.... diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/authentication.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/authentication.adoc deleted file mode 100644 index 8b9382b48e0d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/authentication.adoc +++ /dev/null @@ -1,529 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-security-authentication]] -=== Authentication and Authorization - -There are two aspects to securing a web application(or context) within the Jetty server: - -Authentication:: - The web application can be configured with a mechanism to determine the identity of the user. - This is configured by a mix of standard declarations and jetty specific mechanisms and is covered in this section. -Authorization:: - Once the identify of the user is known (or not known), the web application can be configured via standard descriptors with security constraints that declare what resources that user may access. - -==== Configuring an Authentication mechanism - -Jetty server supports several standard authentication mechanisms: http://en.wikipedia.org/wiki/Basic_access_authentication[BASIC]; http://en.wikipedia.org/wiki/Digest_authentication[DIGEST]; http://en.wikipedia.org/wiki/Form-based_authentication[FORM]; CLIENT-CERT; and other mechanisms can be plugged in using the extensible http://docs.oracle.com/cd/E19462-01/819-6717/gcszc/index.html[JASPI] or http://en.wikipedia.org/wiki/SPNEGO[SPNEGO] mechanisms. - -Internally, configuring an authentication mechanism is done by setting an instance of a the link:{JDURL}/org/eclipse/jetty/security/Authenticator.html[Authenticator] interface onto the link:{JDURL}/org/eclipse/jetty/security/SecurityHandler.html[SecurityHandler] of the context, but in most cases it is done by declaring a `` element in the standard web.xml descriptor or via annotations. - -Below is an example taken from the link:{GITBROWSEURL}/tests/test-webapps/test-jetty-webapp/src/main/webapp/WEB-INF/web.xml?h=release-9[jetty-test-webapp web.xml] that configures BASIC authentication: - -[source, xml, subs="{sub-order}"] ----- - - BASIC - Test Realm - - ----- - -The link:{GITBROWSEURL}/tests/test-webapps/test-jetty-webapp/src/main/webapp/WEB-INF/web.xml?h=release-9[jetty-test-webapp web.xml] also includes commented out examples of other DIGEST and FORM configuration: - -[source, xml, subs="{sub-order}"] ----- - - FORM - Test Realm - - /logon.html?param=test - /logonError.html?param=test - - - ----- - -With FORM Authentication, you must also configure URLs of pages to generate a login form and handle errors. -Below is a simple HTML form from the link:{GITBROWSEURL}/tests/test-webapps/test-jetty-webapp/src/main/webapp/logon.html?h=release-9[test webapp logon.html]: - -[source, xml, subs="{sub-order}"] ----- - -

FORM Authentication demo

-
- - - - - - - - - - - - -
Username:
Password:
- -
-
- - ----- - -The Authentication mechanism declared for a context / web application defines how the server obtain authentication credentials from the -client, but it does not define how the server checks if those credentials are valid. -To check credentials, the server and/or context also need to be configured with a link:{JDURL}/org/eclipse/jetty/security/LoginService.html[LoginService] instance, which may be matched by the declared realm-name. - -[[security-realms]] -==== Security Realms - -Security realms allow you to secure your web applications against unauthorized access. -Protection is based on authentication that identifies who is requesting access to the webapp and access control that restricts what can be accessed and how it is accessed within the webapp. - -A webapp statically declares its security requirements in its web.xml file. -Authentication is controlled by the `` element. -Access controls are specified by `` and `` elements. -When a request is received for a protected resource, the web container checks if the user performing the request is authenticated, and if the user has a role assignment that permits access to the requested resource. - -The Servlet Specification does not address how the static security information in the `WEB-INF/web.xml` file is mapped to the runtime environment of the container. -For Jetty, the link:{JDURL}/org/eclipse/jetty/security/LoginService.html[LoginService] performs this function. - -A `LoginService` has a unique name, and gives access to information about a set of users. -Each user has authentication information (e.g. a password) and a set of roles associated with him/herself. - -You may configure one or many different LoginServices depending on your needs. -A single realm would indicate that you wish to share common security information across all of your web applications. -Distinct realms allow you to partition your security information webapp by webapp. - -When a request to a web application requires authentication or authorization, Jetty will use the `` sub-element inside `` element in the web.xml file to perform an _exact match_ to a LoginService. - -==== Scoping Security Realms - -A `LoginService` has a unique name, and is composed of a set of users. -Each user has authentication information (for example, a password) and a set of roles associated with him/herself. -You can configure one or many different realms depending on your needs. - -* Configure a single LoginService to share common security information across all of your web applications. -* Configure distinct LoginServices to partition your security information webapp by webapp. - -===== Globally Scoped - -A LoginService is available to all web applications on a Server instance if you add it as a bean to the Server. -Such a definition would go into an xml file in your `${jetty.base}/etc` directory, e.g. `${jetty.base}/etc/my-realm.xml` and you would add this xml file to the execution path via `start.ini` or `start.d` (you may want to review the material in the link:#startup[Starting Jetty] chapter). -Here's an example of an xml file that defines an in-memory type of LoginService called the link:{JDURL}/org/eclipse/jetty/security/HashLoginService.html[HashLoginService]: - -[source, xml, subs="{sub-order}"] ----- - - - - - - Test Realm - /etc/realm.properties - true - - - - - - ----- - -If you define more than one `LoginService` on a Server, you will need to specify which one you want used for each context. -You can do that by telling the context the name of the `LoginService`, or passing it the `LoginService` instance. -Here's an example of doing both of these, using a link:#deployable-descriptor-file[context xml file]: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - Test Realm - - - - - Test Realm - - - - ----- - -===== Per-Webapp Scoped - -Alternatively, you can define a `LoginService` for just a single web application. -Here's how to define the same HashLoginService, but inside a link:#deployable-descriptor-file[context xml file]: - -[source, xml, subs="{sub-order}"] ----- - - - /test - /webapps/test - - - - Test Realm - /etc/realm.properties - - - - - - ----- - -Jetty provides a number of different `LoginService` types which can be seen in the next section. - -[[configuring-login-service]] -==== Configuring a LoginService - -A link:{JDURL}/org/eclipse/jetty/security/LoginService.html[`LoginService`] instance is required by each context/webapp that has a authentication mechanism, which is used to check the validity of the username and credentials collected by the authentication mechanism. Jetty provides the following implementations of `LoginService`: - -link:{JDURL}/org/eclipse/jetty/security/HashLoginService.html[HashLoginService]:: - A user realm that is backed by a hash map that is filled either programatically or from a Java properties file. -link:{JDURL}/org/eclipse/jetty/security/JDBCLoginService.html[JDBCLoginService]:: - Uses a JDBC connection to an SQL database for authentication -link:{JDURL}/org/eclipse/jetty/plus/security/DataSourceLoginService.html[DataSourceLoginService]:: - Uses a JNDI defined http://docs.oracle.com/javase/7/docs/api/javax/sql/DataSource.html[DataSource] for authentication -link:{JDURL}/org/eclipse/jetty/jaas/JAASLoginService.html[JAASLoginService]:: - Uses a http://en.wikipedia.org/wiki/Java_Authentication_and_Authorization_Service[JAAS] provider for authentication; see the section on - link:#jaas-support[JAAS support] for more information -link:{JDURL}/org/eclipse/jetty/security/SpnegoLoginService.html[SpnegoLoginService]:: - http://en.wikipedia.org/wiki/SPNEGO[SPNEGO] Authentication; see the section on link:#spnego-support[SPNEGO support] for more information. - -An instance of a `LoginService` can be matched to a context/webapp by: - -* A `LoginService` instance may be set directly on the `SecurityHandler` instance via embedded code or IoC XML -* Matching the realm-name defined in web.xml with the name of a `LoginService` instance that has been added to the Server instance as a dependent bean -* If only a single `LoginService` instance has been set on the Server then it is used as the login service for the context - -[[hash-login-service]] -===== HashLoginService - -The `HashLoginService` is a simple and efficient login service that loads usernames, credentials and roles from a Java properties file in the format: - -[source,properties] ----- - -username: password[,rolename ...] - ----- - -Where: - -username:: - is the user's unique identity -password:: - is the user's (possibly obfuscated or MD5 encrypted) password; -rolename:: - is a role of the user - -For example: - -[source,properties] ----- - -admin: CRYPT:ad1ks..kc.1Ug,server-administrator,content-administrator,admin -other: OBF:1xmk1w261u9r1w1c1xmq -guest: guest,read-only - ----- - -You configure the `HashLoginService` with a name and a reference to the location of the properties file: - -[source, xml, subs="{sub-order}"] ----- - - - - Test Realm - /etc/realm.properties - - - ----- - -You can also configure it to reload the configuration file when changes to it are detected. - -[source, xml, subs="{sub-order}"] ----- - - - Test Realm - /etc/realm.properties - true - - - ----- - -[[jdbc-login-service]] -===== JDBCLoginService - -In this implementation, authentication and role information is stored in a database accessed via JDBC. -A properties file defines the JDBC connection and database table information. -Here is an example of a properties file for this realm implementation: - -[source,properties] ----- - -jdbcdriver = org.gjt.mm.mysql.Driver -url = jdbc:mysql://localhost/jetty -username = jetty -password = jetty -usertable = users -usertablekey = id -usertableuserfield = username -usertablepasswordfield = pwd -roletable = roles -roletablekey = id -roletablerolefield = role -userroletable = user_roles -userroletableuserkey = user_id -userroletablerolekey = role_id -cachetime = 300 - ----- - -The format of the database tables is (pseudo-sql): - -[source,sql] ----- - -users -( - id integer PRIMARY KEY, - username varchar(100) NOT NULL UNIQUE KEY, - pwd varchar(50) NOT NULL -); -user_roles -( - user_id integer NOT NULL, - role_id integer NOT NULL, - UNIQUE KEY (user_id, role_id), - INDEX(user_id) -); -roles -( - id integer PRIMARY KEY, - role varchar(100) NOT NULL UNIQUE KEY -); - ----- - -Where: - -* *users* is a table containing one entry for every user consisting of: -+ -id:: - the unique identity of a user -user:: - the name of the user -pwd:: - the user's password (possibly obfuscated or MD5 encrypted) -* *user-roles* is a table containing one row for every role granted to a -user: -+ -user_id:: - the unique identity of the user -role_id:: - the role for a user -* *roles* is a a table containing one role for every role in the system: -+ -id:: - the unique identifier of a role -role:: - a human-readable name for a role - -If you want to use obfuscated, MD5 hashed or encrypted passwords the `pwd` column of the `users` table must be large enough to hold the obfuscated, hashed or encrypted password text plus the appropriate prefix. - -You define a `JDBCLoginService` with the name of the realm and the location of the properties file describing the database: - -[source, xml, subs="{sub-order}"] ----- - - Test JDBC Realm - etc/jdbcRealm.properties - ----- - -==== Authorization - -As far as the https://jcp.org/en/jsr/detail?id=340[Servlet Specification] is concerned, authorization is based on roles. -As we have seen, a `LoginService` associates a user with a set of roles. -When a user requests a resource that is access protected, the `LoginService` will be asked to authenticate the user if they are not already, and then asked to confirm if that user possesses one of the roles permitted access to the resource. - -Until Servlet 3.1, role-based authorization could define: - -* Access granted to a set of named roles: - -[source, xml, subs="{sub-order}"] ----- - - - Foo Admin Data - /foo/admin/* - - - admin - manager - - ----- - -* Access totally forbidden, regardless of role: - -[source, xml, subs="{sub-order}"] ----- - - - Foo Protected Data - /foo/protected/* - - - - ----- -* Access granted to a user in any of the roles defined in the effective `web.xml`. -This is indicated by the special value of `*` for the `` of a `` in the ``: - -[source, xml, subs="{sub-order}"] ----- - - - Foo Role Data - /foo/role/* - - - * - - ----- - -Servlet 3.1 introduced an additional authorization: - -* Access granted to any user who is authenticated, regardless of roles. -This is indicated by the special value of `**` for the `` of a `` in the ``: - -[source, xml, subs="{sub-order}"] ----- - - - Foo Authenticated Data - /foo/authenticated/* - - - ** - - ----- - -Additionally, when configuring your security constraints you can protect various HTTP methods as well, such as `PUT`, `GET`, `POST`, `HEAD` or `DELETE`. -This is done by adding the method you want to protect as a `` in the ``. -You can then define roles that should be able to perform these protected methods in an ``: - -[source, xml, subs="{sub-order}"] ----- - - - Foo Authenticated Data - /foo/authenticated/* - DELETE - POST - - - admin - - ----- - -In the above example, only users with an `admin` role will be able to perform `DELETE` or `POST` methods. - -===== Configuring Authorization with Context XML Files - -While the examples above show configuration of Authorization in a `web.xml` file, they can also be configured as part of the link#link:#deployable-descriptor-file[context xml file] for a web application. -This is especially helpful if authorization needs change over time and need updated without re-packaging the whole web app. - -To do this, we add a section for security constraints into the context xml file for our web app as part of the `securityHandler`. -In the example below, a `HashLoginService` is defined with authorization being granted too `foo/*` paths to users with the `admin` and `manager` roles. - -[source, xml, subs="{sub-order}"] ----- - - - Test Realm - BASIC - - - - /foo/* - - - Foo Auth - true - - - admin - manager - - - - - - - - - - Test Realm - /src/tmp/small-security-test/realm.properties - - - - ----- - -If roles changed in the future, administrators could easily change this context xml file without having to edit the contents of the web app at all. - -==== Authentication and Authorization with Embedded Jetty - -In addition to the distribution, security can be defined as part of an embedded implementation as well. -Below is an example which, like the one above, sets up a server with a `HashLoginService` and adds security constraints to restrict access based on roles. - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java[] ----- - -==== JSR 196: Java Authentication Service Provider Interface for Containers (JASPI) - -Jetty can utilize portable authentication modules that implements the Jakarta Authentication specification. This requires the jetty-jaspi module. - -Only modules conforming to the ServerAuthModule interface in the https://www.jcp.org/en/jsr/detail?id=196[JASPI Spec] are supported. These modules must be configured before start-up. - -The following illustrates a jetty module setting up HTTP Basic Authentication using an Authentication module that comes packaged with the jetty-jaspi module: `org.eclipse.jetty.security.jaspi.modules.BasicAuthenticationAuthModule` - -[source, xml, subs="{sub-order}"] ----- -include::{SRCDIR}/jetty-jaspi/src/main/config/etc/jaspi/jaspi-demo.xml[tags=documentation] ----- - -Given the portability goal of Jakarta Authentication, custom or 3rd party `ServerAuthModule` implementations may be configured instead here. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/chapter.adoc deleted file mode 100644 index 2ab85fac7334..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/chapter.adoc +++ /dev/null @@ -1,24 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-security]] -== Configuring Security - -include::authentication.adoc[] -include::configuring-form-size.adoc[] -include::serving-aliased-files.adoc[] -include::secure-passwords.adoc[] -include::setting-port80-access-for-non-root-user.adoc[] -include::jaas-support.adoc[] -include::spnego-support.adoc[] -include::openid-support.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/configuring-form-size.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/configuring-form-size.adoc deleted file mode 100644 index 0502eeb7549f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/configuring-form-size.adoc +++ /dev/null @@ -1,70 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-form-size]] -=== Limiting Form Content - -Form content sent to the server is processed by Jetty into a map of parameters to be used by the web application. -This can be vulnerable to denial of service (DOS) attacks since significant memory and CPU can be consumed if a malicious clients sends very large form content or large number of form keys. -Thus Jetty limits the amount of data and keys that can be in a form posted to Jetty. - -The default maximum size Jetty permits is 200000 bytes and 1000 keys. -You can change this default for a particular webapp or for all webapps on a particular Server instance. - -==== Configuring Form Limits for a Webapp - -To configure the form limits for a single web application, the context handler (or webappContext) instance must be configured using the following methods: - -[source, java, subs="{sub-order}"] ----- -ContextHandler.setMaxFormContentSize(int maxSizeInBytes); -ContextHandler.setMaxFormKeys(int formKeys); - ----- - -These methods may be called directly when embedding Jetty, but more commonly are configured from a context XML file or WEB-INF/jetty-web.xml file: - -[source, xml, subs="{sub-order}"] ----- - - - ... - - 200000 - 200 - - ----- - -==== Configuring Form Limits for the Server - -If a context does not have specific form limits configured, then the server attributes are inspected to see if a server wide limit has been set on the size or keys. -The following XML shows how these attributes can be set in `jetty.xml`: - -[source, xml, subs="{sub-order}"] ----- - - - ... - - - org.eclipse.jetty.server.Request.maxFormContentSize - 100000 - - - org.eclipse.jetty.server.Request.maxFormKeys - 2000 - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/jaas-support.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/jaas-support.adoc deleted file mode 100644 index ff801b6a270d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/jaas-support.adoc +++ /dev/null @@ -1,409 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jaas-support]] -=== JAAS Support - -JAAS implements a Java version of the standard Pluggable Authentication Module (PAM) framework. - -JAAS can be used for two purposes: - -* for authentication of users, to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet -* for authorization of users to ensure they have the access control rights (permissions) required to do the actions performed - -JAAS authentication is performed in a pluggable fashion. -This permits applications to remain independent from underlying authentication technologies. -New or updated authentication technologies can be plugged under an application without requiring modifications to the application itself. -Applications enable the authentication process by instantiating a `LoginContext` object, which in turn references a configuration to determine the authentication technology(ies), or `LoginModule`(s), to be used in performing the authentication. -Typical `LoginModules` may prompt for and verify a username and password. -Others may read and verify a voice or fingerprint sample. - -See Java Authentication and Authorization Service (JAAS) http://java.sun.com/javase/6/docs/technotes/guides/security/jaas/JAASRefGuide.html[Reference Guide] for more information about JAAS. - -[[jetty-jaas]] -==== Jetty and JAAS - -Many application servers support JAAS as a means of bringing greater flexibility to the declarative security models of the J2EE (now known as the JavaEE) http://java.sun.com/javaee/index.jsp[specification]. -Jetty support for JAAS provides greater alternatives for servlet security, and increases the portability of web applications. - -The JAAS support aims to dictate as little as possible whilst providing a sufficiently flexible infrastructure to allow users to drop in their -own custom http://java.sun.com/j2se/1.4.2/docs/guide/security/jaas/JAASLMDevGuide.html[LoginModules]. - -[[jaas-configuration]] -==== Configuration - -Using JAAS with Jetty is very simply a matter of declaring a `org.eclipse.jetty.jaas.JAASLoginService`, creating a JAAS login module configuration file and specifying it on the Jetty run line. -Let's look at an example. - -===== Step 1 - -Configure a Jetty `org.eclipse.jetty.jaas.JAASLoginService` to match the `` in your `web.xml` file. For example, if the `web.xml` contains a realm called "Test JAAS Realm" like so: - -[source, xml, subs="{sub-order}"] ----- - - FORM - Test JAAS Realm - - /login/login - /login/error - - ----- - -then you need to create a `JAASLoginService` with the matching realm name of "Test JAAS Realm": - -[source, xml, subs="{sub-order}"] ----- - - Test JAAS Realm - xyz - ----- - -The `LoginModuleName` must match the name of your LoginModule as declared in your login module configuration file (see <>). -____ -[CAUTION] -The name of the realm-name that you declare in `web.xml` must match *exactly* the `Name` field of your `JAASLoginService`. -____ - -You can declare your `JAASLoginService` in a couple of different ways: - -1. If you have more than one webapp that you would like to use the same security infrastructure, then you can declare your `JAASLoginService` in a top-level Jetty xml file as a bean that is added to the `org.eclipse.jetty.server.Server`. -An example: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - Test JAAS Realm - xyz - - - - - ----- -2. Alternatively, you can use a `JAASLoginService` with just a specific webapp by creating a link:#deployable-descriptor-file[context xml] file for the webapp, and specifying the `JAASLoginService` in it: -+ -[source, xml, subs="{sub-order}"] ----- - - - - - - - Test JAAS Realm - xyz - - - - - - ----- - -[[jaas-step-2]] -===== Step 2 - -Set up your `LoginModule` in a configuration file, following the https://docs.oracle.com/javase/7/docs/api/javax/security/auth/login/Configuration.html[syntax rules] : - -[source,ini] ----- -xyz { - com.acme.SomeLoginModule required debug=true; - }; ----- - -____ -[CAUTION] -It is imperative that the application name on the first line is *exactly* the same as the `LoginModuleName` of your `JAASLoginService`. -____ - -You may find it convenient to name this configuration file as `etc/login.conf` because, as we will see below, some of the wiring up for JAAS has been done for you. - -===== Step 3 - -You now need to invoke Jetty with support for JAAS. -There are 2 aspects to this: - -* adding JAAS-related jars to the Jetty container classpath -* setting the System property `java.security.auth.login.config` - -To accomplish the above, use the Jetty link:#startup-overview[startup] link:#startup-modules[modules mechanism] to add the JAAS link:#startup-modules[module]: - -[source, screen, subs="{sub-order}"] -.... -java -jar start.jar --add-to-start=jaas -.... - -____ -[NOTE] -The top level of the distribution does not have the JAAS module enabled by default. -However, there are several link:#demo-webapps-base[demo webapps] - including a JAAS webapp - available in the `demo-base` directory of the distribution which has pre-enabled the JAAS module. -____ - -Now you will have a file named `start.d/jaas.ini`, which contains: - -[source,ini] ----- ---module=jaas -jaas.login.conf=etc/login.conf ----- - -The `jaas.login.conf` property refers to the location of your `LoginModule` configuration file that you established in link:#jaas-step-2[Step 2]. -If you called it `etc/login.conf`, then your work is done. Otherwise, change the value of the `jaas.login.conf` property to be the location of your LoginModule configuration file. -Jetty will automatically use this property to set the value of the System property `java.security.auth.login.config.` - -==== A Closer Look at JAASLoginService - -To allow the greatest degree of flexibility in using JAAS with web applications, the `JAASLoginService` supports a couple of configuration options. -Note that you don't ordinarily need to set these explicitly, as Jetty has defaults which will work in 99% of cases. -However, should you need to, you can configure: - -* a CallbackHandler (Default: `org.eclipse.jetty.jaas.callback.DefaultCallbackHandler`) -* a list of classnames for the Principal implementation that equate to a user role (Default: `org.eclipse.jetty.jaas.JAASRole`) - -Here's an example of setting each of these (to their default values): - -[source, xml, subs="{sub-order}"] ----- - - Test JAAS Realm - xyz - - org.eclipse.jetty.jaas.callback.DefaultCallbackHandler - - - - org.eclipse.jetty.jaas.JAASRole - - - ----- - -===== CallbackHandler - -A CallbackHandler is responsible for interfacing with the user to obtain usernames and credentials to be authenticated. - -Jetty ships with the `org.eclipse.jetty.jaas.DefaultCallbackHandler` which interfaces the information contained in the request to the Callbacks that are requested by `LoginModules`. -You can replace this default with your own implementation if you have specific requirements not covered by the default. - -===== Role Principal Implementation Class - -When `LoginModules` authenticate a user, they usually also gather all of the roles that a user has and place them inside the JAAS Subject. -As `LoginModules` are free to use their own implementation of the JAAS Principal to put into the Subject, Jetty needs to know which Principals represent the user and which represent his/her roles when performing authorization checks on ``. The example `LoginModules` that ship with Jetty all use the `org.eclipse.jetty.jaas.JAASRole` class. However, if you have plugged in other `LoginModules`, you must configure the classnames of their role Principal implementations. - -===== Sample LoginModules - -* link:{JDURL}/org/eclipse/jetty/jaas/spi/JDBCLoginModule.html[`org.eclipse.jetty.jaas.spi.JDBCLoginModule`] -* link:{JDURL}/org/eclipse/jetty/jaas/spi/PropertyFileLoginModule.html[`org.eclipse.jetty.jaas.spi.PropertyFileLoginModule`] -* link:{JDURL}/org/eclipse/jetty/jaas/spi/DataSourceLoginModule.html[`org.eclipse.jetty.jaas.spi.DataSourceLoginModule`] -* link:{JDURL}/org/eclipse/jetty/jaas/spi/LdapLoginModule.html[`org.eclipse.jetty.jaas.ldap.LdapLoginModule`] - -____ -[NOTE] -Passwords can be stored in clear text, obfuscated or checksummed. -The class link:{JDURL}/org/eclipse/jetty/util/security/Password.html[`org.eclipse.jetty.util.security.Password`] should be used to generate all varieties of passwords,the output from which can be put in to property files or entered into database tables. -See more on this under the Configuration section on link:#configuring-security-secure-passwords[securing passwords]. -____ - -===== JDBCLoginModule - -The `JDBCLoginModule` stores user passwords and roles in a database that are accessed via JDBC calls. -You can configure the JDBC connection information, as well as the names of the table and columns storing the username and credential, and the names of the table and columns storing the roles. - -Here is an example login module configuration file entry for it using an HSQLDB driver: - -[source,ini] ----- - -jdbc { - org.eclipse.jetty.jaas.spi.JDBCLoginModule required - debug="true" - dbUrl="jdbc:hsqldb:." - dbUserName="sa" - dbDriver="org.hsqldb.jdbcDriver" - userTable="myusers" - userField="myuser" - credentialField="mypassword" - userRoleTable="myuserroles" - userRoleUserField="myuser" - userRoleRoleField="myrole"; - }; ----- - -There is no particular schema required for the database tables storing the authentication and role information. -The properties `userTable`, `userField`, `credentialField`, `userRoleTable`, `userRoleUserField`, `userRoleRoleField` configure the names of the tables and the columns within them that are used to format the following queries: - -[source,sql] ----- - select from - where =? - select from - where =? ----- - -Credential and role information is lazily read from the database when a previously unauthenticated user requests authentication. -Note that this information is _only_ cached for the length of the authenticated session. -When the user logs out or the session expires, the information is flushed from memory. - -Note that passwords can be stored in the database in plain text or encoded formats - see the note on "Passwords/Credentials" above. - -===== DataSourceLoginModule - -Similar to the `JDBCLoginModule`, but this `LoginModule` uses a `DataSource` to connect to the database instead of a JDBC driver. The `DataSource` is obtained by performing a JNDI lookup on `java:comp/env/${dnJNDIName}`. - -A sample login module configuration using this method: - -[source,ini] ----- - -ds { - org.eclipse.jetty.jaas.spi.DataSourceLoginModule required - debug="true" - dbJNDIName="ds" - userTable="myusers" - userField="myuser" - credentialField="mypassword" - userRoleTable="myuserroles" - userRoleUserField="myuser" - userRoleRoleField="myrole"; - }; ----- - -===== PropertyFileLoginModule - -With this login module implementation, the authentication and role information is read from a property file. - -[source,ini] ----- -props { - org.eclipse.jetty.jaas.spi.PropertyFileLoginModule required - debug="true" - file="/somewhere/somefile.props"; - }; ----- - -The file parameter is the location of a properties file of the same format as the `etc/realm.properties` example file. -The format is: - -[source,text] ----- -: [, ...] ----- - -Here's an example: - -[source,ini] ----- -fred: OBF:1xmk1w261u9r1w1c1xmq,user,admin -harry: changeme,user,developer -tom: MD5:164c88b302622e17050af52c89945d44,user -dick: CRYPT:adpexzg3FUZAk,admin ----- - -The contents of the file are fully read in and cached in memory the first time a user requests authentication. - -===== LdapLoginModule - -Here's an example: - -[source,ini] ----- - -ldaploginmodule { - org.eclipse.jetty.jaas.spi.LdapLoginModule required - debug="true" - contextFactory="com.sun.jndi.ldap.LdapCtxFactory" - hostname="ldap.example.com" - port="389" - bindDn="cn=Directory Manager" - bindPassword="directory" - authenticationMethod="simple" - forceBindingLogin="false" - userBaseDn="ou=people,dc=alcatel" - userRdnAttribute="uid" - userIdAttribute="uid" - userPasswordAttribute="userPassword" - userObjectClass="inetOrgPerson" - roleBaseDn="ou=groups,dc=example,dc=com" - roleNameAttribute="cn" - roleMemberAttribute="uniqueMember" - roleObjectClass="groupOfUniqueNames"; - }; ----- - -==== Writing your Own LoginModule - -If you want to implement your own custom `LoginModule`, there are two classes to be familiar with: `org.eclipse.jetty.jaas.spi.AbstractLoginModule` and `org.eclipse.jetty.jaas.spi.UserInfo`. - -The `org.eclipse.jetty.jaas.spi.AbstractLoginModule` implements all of the `javax.security.auth.spi.LoginModule` methods. -All you need to do is to implement the `getUserInfo` method to return a `org.eclipse.jetty.jaas.UserInfo` instance which encapsulates the username, password and role names (note: as `java.lang.Strings`) for a user. - -The `AbstractLoginModule` does not support any caching, so if you want to cache UserInfo (eg as does the `org.eclipse.jetty.jaas.spi.PropertyFileLoginModule`) then you must provide this yourself. - -==== Other Goodies - -===== ServletRequestCallback - -This callback gives you access to the ServletRequest that is involved in the authentication, and thus to other features like the current Session. This callback can be configured in your custom LoginModule implementation. Note that none of the LoginModule implementations provided with Jetty currently use this callback. - -===== RequestParameterCallback - -As all servlet containers intercept and process a form submission with action `j_security_check`, it is usually not possible to insert any extra input fields onto a login form with which to perform authentication: you may only pass `j_username` and `j_password`. -For those rare occasions when this is not good enough, and you require more information from the user in order to authenticate them, you can use the JAAS callback handler `org.eclipse.jetty.jaas.callback.RequestParameterCallback`. -This callback gives you access to all parameters that were passed in the form submission. -To use it, in the `login()` method of your custom login module, add the `RequestParameterCallback` to the list of callback handlers the login module uses, tell it which params you are interested in, and then get the value of the parameter back. -Here is an example: - -[source, java, subs="{sub-order}"] ----- - -public class FooLoginModule extends AbstractLoginModule -{ - public boolean login() - throws LoginException - { - - Callback[] callbacks = new Callback[3]; - callbacks[0] = new NameCallback(); - callbacks[1] = new ObjectCallback(); - - //as an example, look for a param named "extrainfo" in the request - //use one RequestParameterCallback() instance for each param you want to access - callbacks[2] = new RequestParameterCallback (); - ((RequestParameterCallback)callbacks[2]).setParameterName ("extrainfo"); - - - callbackHandler.handle(callbacks); - String userName = ((NameCallback)callbacks[0]).getName(); - Object pwd = ((ObjectCallback)callbacks[1]).getObject(); - List paramValues = ((RequestParameterCallback)callbacks[2]).getParameterValues(); - - //use the userName, pwd and the value(s) of the parameter named "extrainfo" to - //authenticate the user - - } -} ----- - -===== Example JAAS WebApp - -An example webapp using JAAS can be found in the Jetty GitHub repository: - -* link:{GITBROWSEURL}/tests/test-webapps/test-jaas-webapp[https://github.com/jetty/jetty.project/tree/jetty-10.0.x/tests/test-webapps/test-jaas-webapp] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/jetty-home-and-jetty-base.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/jetty-home-and-jetty-base.adoc deleted file mode 100644 index a8b83a220ca7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/jetty-home-and-jetty-base.adoc +++ /dev/null @@ -1,517 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-home-and-jetty-base]] -=== Using the $\{jetty.home} and $\{jetty.base} Concepts to Configure -Security - -Jetty 9.1 introduced `${jetty.base}` and `${jetty.home}`. - -* `${jetty.home}` is the directory location for the jetty distribution (the binaries). -* `${jetty.base}` is the directory location for your customizations to the distribution. - -This separation: - -* Allows you to manage multiple Jetty installations. -* Makes it simple to retain your current configuration when you upgrade your Jetty distribution. - -For more information, see xref:startup-base-and-home[]. - -Further, Jetty 9.1 parameterized all of the standard configuration XMLs. -For SSL, parameters are now properties in the `start.ini` or `start.d\ssl.ini`, reducing to eliminating the need to edit XML files. - -Instead of explicitly listing all the libraries, properties, and XML files for a feature, Jetty 9.1 introduced a new module system. -A module is defined 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 use their dependencies to control the ordering of libraries and XML files. -For more information, see xref:startup-modules[]. - -[[configuring-security-jetty91]] -==== Configuring SSL in with modules - -This page describes how to configure SSL in Jetty with modules. -It provides an example of using the `${jetty.home}` and `${jetty.base}` to maximum effect. -It also includes a detailed explanation of how modules work. - -This example assumes you have the jetty-home unpacked in `/home/user/jetty-home-{VERSION}`. -It also assumes you are using `start.ini` to configure your server features. - -1. Create a base directory anywhere. -+ -[source, screen, subs="{sub-order}"] -.... -[/home/user]$ mkdir my-base -[/home/user]$ cd my-base -.... -2. Add the modules for SSL, HTTP, and webapp deployment. -Adding modules in this way will append the associated module properties to the `${jetty.base}/start.ini` file. -+ -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --add-to-start=http,https,deploy - -INFO : webapp transitively enabled, ini template available with --add-to-start=webapp -INFO : server transitively enabled, ini template available with --add-to-start=server -INFO : security transitively enabled -INFO : servlet transitively enabled -INFO : http initialized in ${jetty.base}/start.ini -INFO : https initialized in ${jetty.base}/start.ini -INFO : threadpool transitively enabled, ini template available with --add-to-start=threadpool -INFO : ssl transitively enabled, ini template available with --add-to-start=ssl -INFO : bytebufferpool transitively enabled, ini template available with --add-to-start=bytebufferpool -INFO : deploy initialized in ${jetty.base}/start.ini -MKDIR : ${jetty.base}/etc -COPY : ${jetty.home}/modules/ssl/keystore to ${jetty.base}/etc/keystore -MKDIR : ${jetty.base}/webapps -INFO : Base directory was modified -.... -3. Look at your directory. -+ -[source, screen, subs="{sub-order}"] -.... -[my-base]$ ls -la -total 20 -drwxrwxr-x 4 user group 4096 Oct 8 06:55 ./ -drwxr-xr-x 103 user group 4096 Oct 8 06:53 ../ -drwxrwxr-x 2 user group 4096 Oct 8 06:55 etc/ --rw-rw-r-- 1 user group 815 Oct 8 06:55 start.ini -drwxrwxr-x 2 user group 4096 Oct 8 06:55 webapps/ -.... -4. Copy your WAR files into webapps. -+ -[source, screen, subs="{sub-order}"] -.... -[my-base]$ ls -la -[my-base]$ cp ~/code/project/target/gadget.war webapps/ -.... -5. Copy your keystore into place. -+ -[source, screen, subs="{sub-order}"] -.... -[my-base]$ cp ~/code/project/keystore etc/keystore -.... -6. Edit the `start.ini` to configure your SSL settings. -+ -[source, screen, subs="{sub-order}"] -.... -[my-base]$ cat start.ini -.... -7. Initialize module ssl. -+ -.... ---module=ssl -.... -8. Define the port to use for secure redirection. -+ -.... -jetty.secure.port=8443 -.... -9. Set up a demonstration keystore and truststore. -+ -.... -jetty.keystore=etc/keystore -jetty.truststore=etc/keystore -.... -10. Set the demonstration passwords. -+ -.... -jetty.keystore.password=OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4 -jetty.keymanager.password=OBF:1u2u1wml1z7s1z7a1wnl1u2g -jetty.truststore.password=OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4 -.... -11. Initialize the module server. -+ -.... ---module=server -threads.min=10 -threads.max=200 -threads.timeout=60000 -#jetty.host=myhost.com -jetty.dump.start=false -jetty.dump.stop=false -.... -12. Initialize module http. -+ -.... ---module=http -jetty.http.port=8080 -http.timeout=30000 -.... -13. Initialize module deploy. -+ -.... ---module=deploy -.... - -Look at the configuration you have at this point. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/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-home-{VERSION} - jetty.base=/home/user/my-base - jetty.version={VERSION} - -JVM Arguments: --------------- - (no jvm args specified) - -System Properties: ------------------- - jetty.base = /home/user/my-base - jetty.home = /home/user/jetty-home-{VERSION} - -Properties: ------------ - http.timeout = 30000 - 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 - threads.max = 200 - threads.min = 10 - threads.timeout = 60000 - -Jetty Server Classpath: ------------------------ -Version Information on 11 entries in the classpath. -: order presented here is how they would appear on the classpath. - changes to the --module=name command line options will be reflected here. - 0: 4.0.2 | ${jetty.home}/lib/jetty-servlet-api-4.0.2.jar - 2: {VERSION} | ${jetty.home}/lib/jetty-http-{VERSION}.jar - 3: {VERSION} | ${jetty.home}/lib/jetty-continuation-{VERSION}.jar - 4: {VERSION} | ${jetty.home}/lib/jetty-server-{VERSION}.jar - 5: {VERSION} | ${jetty.home}/lib/jetty-xml-{VERSION}.jar - 6: {VERSION} | ${jetty.home}/lib/jetty-util-{VERSION}.jar - 7: {VERSION} | ${jetty.home}/lib/jetty-io-{VERSION}.jar - 8: {VERSION} | ${jetty.home}/lib/jetty-servlet-{VERSION}.jar - 9: {VERSION} | ${jetty.home}/lib/jetty-webapp-{VERSION}.jar -10: {VERSION} | ${jetty.home}/lib/jetty-deploy-{VERSION}.jar - -Jetty Active XMLs: ------------------- - ${jetty.home}/etc/jetty.xml - ${jetty.home}/etc/jetty-http.xml - ${jetty.home}/etc/jetty-ssl.xml - ${jetty.home}/etc/jetty-deploy.xml -.... - -Now start Jetty. - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar -2013-10-08 07:06:55.837:INFO:oejs.Server:main: jetty-{VERSION} -2013-10-08 07:06:55.853:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/user/my-base/webapps/] at interval 1 -2013-10-08 07:06:55.872:INFO:oejs.ServerConnector:main: Started ServerConnector@72974691{HTTP/1.1}{0.0.0.0:8080} -.... - -[[reviewing-ssl-config]] -==== Reviewing the Configuration - -The following sections review this configuration. - -[[jetty-base-jetty-home]] -===== $\{jetty.base} and $\{jetty.home} - -First notice the separation of `${jetty.base}` and `${jetty.home}`. - -* `${jetty.home}` is where your distribution lies, unchanged, unedited. -* `${jetty.base}` is where your customizations are. - -[[modules]] -===== Modules - -Notice that you have `--module=` here and there; you have wrapped up the goal of a module (libs, configuration XMLs, and properties) into a single unit, with dependencies on other modules. - -You can see the list of modules: - -[source,screen,subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --list-modules - -Jetty All Available Modules: ----------------------------- - -Module: annotations - LIB: lib/jetty-annotations-${jetty.version}.jar - LIB: lib/annotations/*.jar - XML: etc/jetty-annotations.xml - depends: [plus] - -Module: client - LIB: lib/jetty-client-${jetty.version}.jar - depends: [] - -Module: debug - XML: etc/jetty-debug.xml - depends: [server] - -Module: deploy - LIB: lib/jetty-deploy-${jetty.version}.jar - XML: etc/jetty-deploy.xml - depends: [webapp] - enabled: ${jetty.base}/start.ini - -Module: ext - LIB: lib/ext/*.jar - depends: [] - -Module: http - XML: etc/jetty-http.xml - depends: [server] - enabled: ${jetty.base}/start.ini - -Module: http2 - LIB: lib/http2/*.jar - XML: etc/jetty-http2.xml - depends: [ssl, alpn] - -Module: http2c - LIB: lib/http2/*.jar - XML: etc/jetty-http2c.xml - depends: [http] - -Module: https - XML: etc/jetty-https.xml - depends: [ssl] - -Module: ipaccess - XML: etc/jetty-ipaccess.xml - depends: [server] - -Module: jaas - LIB: lib/jetty-jaas-${jetty.version}.jar - XML: etc/jetty-jaas.xml - depends: [server] - -Module: jaspi - LIB: lib/jetty-jaspi-${jetty.version}.jar - LIB: lib/jaspi/*.jar - depends: [security] - -Module: jmx - LIB: lib/jetty-jmx-${jetty.version}.jar - XML: etc/jetty-jmx.xml - depends: [] - -Module: jndi - LIB: lib/jetty-jndi-${jetty.version}.jar - LIB: lib/jndi/*.jar - depends: [server] - -Module: jsp - LIB: lib/jsp/*.jar - depends: [servlet] - -Module: jvm - depends: [] - -Module: logging - XML: etc/jetty-logging.xml - depends: [] - -Module: lowresources - XML: etc/jetty-lowresources.xml - depends: [server] - -Module: monitor - LIB: lib/jetty-monitor-${jetty.version}.jar - XML: etc/jetty-monitor.xml - depends: [client, server] - -Module: npn - depends: [] - -Module: plus - LIB: lib/jetty-plus-${jetty.version}.jar - XML: etc/jetty-plus.xml - depends: [server, security, jndi] - -Module: proxy - LIB: lib/jetty-proxy-${jetty.version}.jar - XML: etc/jetty-proxy.xml - depends: [client, server] - -Module: requestlog - XML: etc/jetty-requestlog.xml - depends: [server] - -Module: resources - LIB: resources - depends: [] - -Module: rewrite - LIB: lib/jetty-rewrite-${jetty.version}.jar - XML: etc/jetty-rewrite.xml - depends: [server] - -Module: security - LIB: lib/jetty-security-${jetty.version}.jar - depends: [server] - -Module: server - LIB: lib/jetty-servlet-api-4.0.2.jar - LIB: lib/jetty-http-${jetty.version}.jar - LIB: lib/jetty-continuation-${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 - depends: [] - enabled: ${jetty.base}/start.ini - -Module: servlet - LIB: lib/jetty-servlet-${jetty.version}.jar - depends: [server] - -Module: servlets - LIB: lib/jetty-servlets-${jetty.version}.jar - depends: [servlet] - -Module: setuid - LIB: lib/setuid/jetty-setuid-java-1.0.1.jar - XML: etc/jetty-setuid.xml - depends: [server] - -Module: ssl - XML: etc/jetty-ssl.xml - depends: [server] - enabled: ${jetty.base}/start.ini - -Module: stats - XML: etc/jetty-stats.xml - depends: [server] - -Module: webapp - LIB: lib/jetty-webapp-${jetty.version}.jar - depends: [servlet] - -Module: websocket - LIB: lib/websocket/*.jar - depends: [annotations] - -Module: xinetd - XML: etc/jetty-xinetd.xml - depends: [server] - -Jetty Active Module Tree: -------------------------- - + Module: server [enabled] - + Module: http [enabled] - + Module: servlet [transitive] - + Module: ssl [enabled] - + Module: webapp [transitive] - + Module: deploy [enabled] -.... - -These are the modules by name, the libraries they bring in, the XML configurations they use, the other modules they depend on (even optional ones), and if the module is in use, where it was enabled. - -While you can manage the list of active modules yourself, it is much easier to edit the `${jetty.base}/start.ini`. - -If you want to start using a new module: - -[source, screen, subs="{sub-order}"] -.... -[my-base] $ java -jar ../jetty-home-{VERSION}/start.jar --add-to-start=https -.... - -This adds the `--module=` lines and associated properties (the parameterized values mentioned above), to your `start.ini`. - -____ -[IMPORTANT] -Do not edit the modules and XML files in the `${jetty.home}` directory; there is no need to be moving or copying them unless you want to make your own modules or override the behavior of an existing module. -____ - -Notice that your `${jetty.base}/start.ini` has no references to the XML files. -That's because the module system and its graph of dependencies now dictate all of the XML files, and their load order. - -[[parameterizing]] -===== Parameters - -Next is parameterizing all of the standard configuration XMLs. -In this example all of the SSL parameters are now just properties in the `start.ini`, reducing or eliminating the need to edit XML files. - -[[override-jetty.home]] -===== Overriding $\{jetty.home} in $\{jetty.base} - -Finally, you can override anything you see in `${jetty.home}` in `${jetty.base}`, even XML configurations and libraries. - -For more information on the `start.jar` in 9.1, see xref:start-jar[]. - -[[summary-configuring-SSL-Jetty]] -==== Summary of Configuring SSL - -1. Download and unpack Jetty into `/home/user/jetty-home-{VERSION}`. -2. Go to your base directory and just use the distribution, no editing. -+ -[source, screen, subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar -.... -* The Jetty distribution provides, out of the box, the XML configuration files, in this case `jetty-http.xml` and `jetty-ssl.xml`. -These can be found in the `${jetty.home}/etc/` directory. -* We have parameterized all of the configurable values in those XMLs. -You can now set the values using simple properties, either on the command line, or within the `${jetty.base}/start.ini`. -* When you activate the module for HTTP or HTTPs, Jetty automatically adds the appropriate libraries and XML to start Jetty. -Unless you have a highly custom setup (such as listening on two different ports, using SSL on each, each with its own keystore and configuration), there is no need to muck around in XML files. -3. Use modules to configure HTTPS: -* http -> server -* https -> ssl -> server -+ -You can find the details about the modules in `${jetty.home}/modules/`. -For SSL they include `modules/http.mod`, `modules/https.mod`, `modules/ssl.mod`, and `modules/server.mod`. -+ -Ideally, this level of detail is not important to you. -What is important is that you want to use HTTPS and want to configure it. -You accomplish that by adding the `--module=https` to your `start.ini`. -By default, the module system keeps things sane, and transitively includes all dependent modules as well. - -You can see what the configuration looks like, after all of the modules are resolved, without starting Jetty via: - -[source, screen, subs="{sub-order}"] -.... -[my-base] $ java -jar ../jetty-home-{VERSION}/start.jar --list-config -.... - -Just because the JARs exist on disk does not mean that they are in use. -The configuration controls what is used. - -Use the `--list-config` to see the configuration. -Notice that only a subset of the JARs from the distribution are in use. -The modules you have enabled determine that subset. - -[source, screen, subs="{sub-order}"] -.... -[my-base]$ java -jar /path/to/jetty-home/start.jar --list-config -.... diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/openid-support.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/openid-support.adoc deleted file mode 100644 index 82efc614e61d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/openid-support.adoc +++ /dev/null @@ -1,134 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[openid-support]] -=== OpenID Support - -==== External Setup - -===== Registering an App with OpenID Provider -You must register the app with an OpenID Provider such as link:https://developers.google.com/identity/protocols/OpenIDConnect#authenticatingtheuser[Google] or link:https://images-na.ssl-images-amazon.com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf[Amazon.] -This will give you a Client ID and Client Secret. -Once set up you must also register all the possible URI's for your webapp with the path `/j_security_check` so that the OpenId Provider will allow redirection back to the webapp. - -These may look like - - * `http://localhost:8080/openid-webapp/j_security_check` - - * `https://example.com/j_security_check` - -==== Distribution Configuration - -===== OpenID Provider Configuration -To enable OpenID support, you first need to activate the `openid` module in your implementation. - -[source, screen, subs="{sub-order}"] ----- -$ java -jar $JETTY_HOME/start.jar --add-to-start=openid ----- - -To configure OpenID Authentication with Jetty you will need to specify the OpenID Provider's issuer identifier (case sensitive URL using the `https` scheme) and the OAuth 2.0 Client ID and Client Secret. -If the OpenID Provider does not allow metadata discovery you will also need to specify the token endpoint and authorization endpoint of the OpenID Provider. -These can be set as properties in the `start.ini` or `start.d/openid.ini` files. - -===== WebApp Specific Configuration in web.xml - -The `web.xml` file needs some specific configuration to use OpenID. -There must be a `login-config` element with an `auth-method` value of `OPENID`, and a `realm-name` value of the exact URL string used to set the OpenID Provider. - -To set the error page, an init param is set at `"org.eclipse.jetty.security.openid.error_page"`, its value should be a path relative to the webapp where authentication errors should be redirected. - -Example: - -[source, xml, subs="{sub-order}"] ----- - - OPENID - https://accounts.google.com - - - org.eclipse.jetty.security.openid.error_page - /error - ----- - -==== Embedded Configuration - -===== Define the `OpenIdConfiguration` for a specific OpenID Provider. - -If the OpenID Provider allows metadata discovery then you can use. - -[source, java, subs="{sub-order}"] ----- -OpenIdConfiguration openIdConfig = new OpenIdConfiguration(ISSUER, CLIENT_ID, CLIENT_SECRET); ----- - -Otherwise you can manually enter the necessary information: - -[source, java, subs="{sub-order}"] ----- -OpenIdConfiguration openIdConfig = new OpenIdConfiguration(ISSUER, TOKEN_ENDPOINT, AUTH_ENDPOINT, CLIENT_ID, CLIENT_SECRET); ----- - -===== Configuring an `OpenIdLoginService` -[source, java, subs="{sub-order}"] ----- -LoginService loginService = new OpenIdLoginService(openIdConfig); -securityHandler.setLoginService(loginService); ----- - -===== Configuring an `OpenIdAuthenticator` with `OpenIdConfiguration` and Error Page Redirect -[source, java, subs="{sub-order}"] ----- -Authenticator authenticator = new OpenIdAuthenticator(openIdConfig, "/error"); -securityHandler.setAuthenticator(authenticator); -servletContextHandler.setSecurityHandler(securityHandler); ----- - -===== Usage - -====== Claims and Access Token -Claims about the user can be found using attributes on the session attribute `"org.eclipse.jetty.security.openid.claims"`, and the full response containing the OAuth 2.0 Access Token can be found with the session attribute `"org.eclipse.jetty.security.openid.response"`. - -Example: -[source, java, subs="{sub-order}"] ----- -Map claims = (Map)request.getSession().getAttribute("org.eclipse.jetty.security.openid.claims"); -String userId = claims.get("sub"); - -Map response = (Map)request.getSession().getAttribute("org.eclipse.jetty.security.openid.response"); -String accessToken = response.get("access_token"); ----- - -==== Scopes -The OpenID scope is always used but additional scopes can be requested which can give you additional resources or privileges. -For the Google OpenID Provider it can be useful to request the scopes `profile` and `email` which will give you additional user claims. - -Additional scopes can be requested through the `start.ini` or `start.d/openid.ini` files, or with `OpenIdConfiguration.addScopes(...);` in embedded code. - -==== Roles - -If security roles are required they can be configured through a wrapped `LoginService` which is deferred to for role information by the `OpenIdLoginService`. - -This can be configured in XML through `etc/openid-baseloginservice.xml` in the Distribution, or in embedded code using the constructor for the `OpenIdLoginService`. - -[source, java, subs="{sub-order}"] ----- -LoginService wrappedLoginService = ...; // Optional LoginService for Roles -LoginService loginService = new OpenIdLoginService(openIdConfig, wrappedLoginService); ----- - -When using authorization roles, the setting `authenticateNewUsers` becomes significant. -If set to `true` users not found by the wrapped `LoginService` will still be authenticated but will have no roles. -If set to `false` those users will be not be allowed to authenticate and are redirected to the error page. -This setting is configured through the property `jetty.openid.authenticateNewUsers` in the `start.ini` or `start.d/openid.ini` file, or with `OpenIdLoginService.setAuthenticateNewUsers(...);` in embedded code. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/secure-passwords.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/secure-passwords.adoc deleted file mode 100644 index 79f243ea685b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/secure-passwords.adoc +++ /dev/null @@ -1,128 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[configuring-security-secure-passwords]] -=== Secure Password Obfuscation - -There are many places where you might want to use and store a password, for example for the SSL connectors and user passwords in realms. - -Passwords can be stored in clear text, obfuscated, checksummed or encrypted in order of increasing security. -The choice of method to secure a password depends on where you are using the password. -In some cases, such as keystore passwords and `DIGEST` authentication, the system must retrieve the original password, which requires the obfuscation method. -The drawback of the obfuscation algorithm is that it protects passwords *from casual viewing only.* - -When the stored password is compared to one a user enters, the handling code can apply the same algorithm that secures the stored password to the user input and compare results, making password authentication more secure. - -The class `org.eclipse.jetty.util.security.Password` can be used to generate all varieties of passwords. - -Run it without arguments to see usage instructions: - -[source, screen, subs="{sub-order}"] -.... -$ java -cp lib/jetty-util-{VERSION}.jar org.eclipse.jetty.util.security.Password - -Usage - java org.eclipse.jetty.util.security.Password [] -If the password is ?, the user will be prompted for the password -.... - -For example, to generate a secured version of the password `password` for the user `username`: - -[source, screen, subs="{sub-order}"] -.... -$ java -cp ../lib/jetty-util-{VERSION}.jar org.eclipse.jetty.util.security.Password username password -2017-12-13 11:19:27.928:INFO::main: Logging initialized @95ms to org.eclipse.jetty.util.log.StdErrLog -password -OBF:1v2j1uum1xtv1zej1zer1xtn1uvk1v1v -MD5:5f4dcc3b5aa765d61d8327deb882cf99 -CRYPT:usjRS48E8ZADM -.... - -If using a external tool to create/verify the MD5 hash (such as `md5sum` or `md5`), be sure to verify a carriage return (CR) or new line is not added. -For example: - -[source, screen, subs="{sub-order}"] -.... -//With a CR included -$ echo password | md5sum -286755fad04869ca523320acce0dc6a4 *- - -//Using the `-n` option to exclude a new line from being added. -$ echo -n password | md5sum -5f4dcc3b5aa765d61d8327deb882cf99 *- -.... - -____ -[IMPORTANT] -When using the `DIGEST` method in tandem with an MD5 hash, you must hash the entire `user:realm:password` string or you will encounter issues with authenticating. -____ - -[source, screen, subs="{sub-order}"] -.... -$ java -cp ../lib/jetty-util-{VERSION}.jar org.eclipse.jetty.util.security.Password username username:realm:password -2017-12-13 11:34:33.263:INFO::main: Logging initialized @97ms to org.eclipse.jetty.util.log.StdErrLog -username:realm:password -OBF:1w281yf41v1x1z7e1xmi1v1p1tvv1v901c3j1x8k1ugo1ri71uh21x8a1c3j1v9m1tv71v2p1xms1z7o1v2h1yf21w1a -MD5:66999343281b2624585fd58cc9d36dfc -CRYPT:usulxZfApLefk - -$ echo -n username:realm:password | md5sum -66999343281b2624585fd58cc9d36dfc *- -.... - -You can now cut and paste whichever secure version you choose into your configuration file or Java code. - -For example, the last line below shows how you would implement the encrypted password generated above into the properties file for a `LoginService`: - -[source,bash] ----- - -admin: CRYPT:ad1ks..kc.1Ug,server-administrator,content-administrator,admin -other: OBF:1xmk1w261u9r1w1c1xmq -guest: guest,read-only -me:CRYPT:me/ks90E221EY - ----- - -____ -[TIP] -Don't forget to also copy the OBF:, MD5: or CRYPT: prefix on the generated password. It will not be usable by Jetty without it. -____ - -You can also use obfuscated passwords in Jetty xml files where a plain text password is required. -Here's an example setting the password for a JDBC Datasource with obfuscation: - -[source, xml, subs="{sub-order}"] ----- - - - - jdbc/DSTest - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/foo - dbuser - - - OBF:1ri71v1r1v2n1ri71shq1ri71shs1ri71v1r1v2n1ri7 - - - 5 - 50 - 5 - 30 - - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/serving-aliased-files.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/serving-aliased-files.adoc deleted file mode 100644 index 17738ac53c31..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/serving-aliased-files.adoc +++ /dev/null @@ -1,85 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[serving-aliased-files]] -=== Aliased Files and Symbolic links - -Web applications will often serve static content from the file system provided by the operating system running underneath the JVM. -However, because file systems often implement multiple aliased names for the same file, then security constraints and other servlet URI space mappings may inadvertently be bypassed by aliases. - -A key example of this is case insensitivity and 8.3 filenames implemented by the Windows file system. -If a file within a web application called `/mysecretfile.txt` is protected by a security constraint on the URI `/mysecretfile.txt`, then a request to `/MySecretFile.TXT` will not match the URI constraint because URIs are case sensitive, but the Windows file system will report that a file does exist at that name and it will be served despite the security constraint. -Less well known than case insensitivity is that Windows files systems also support http://en.wikipedia.org/wiki/8.3_filename[8.3 filenames] for compatibility with legacy programs. -Thus a request to a URI like `/MYSECR~1.TXT` will again not match the security constraint, but will be reported as an existing file by the file system and served. - -There are many examples of aliases, not just on Windows: - -* NTFS Alternate stream names like `c:\test\file.txt::$DATA:name` -* OpenVMS support file versionig so that `/mysecret.txt;N` refers to version N of `/mysecret.txt` and is essentially an alias. -* The clearcase software configuration management system provides a file system where `@@` in a file name is an alias to a specific version. -* The Unix files system supports `/./foo.txt` as and alias for `/foo.txt` -* Many JVM implementations incorrectly assume the null character is a string terminator, so that a file name resulting from `/foobar.txt%00` is an alias for `/foobar.txt` -* Unix symbolic links and hard links are a form of aliases that allow the same file or directory to have multiple names. - -In addition, it is not just URI security constraints that can be bypassed. For example the mapping of the URI pattern `*.jsp` to the JSP -Servlet may be bypassed by an a request to an alias like `/foobar.jsp%00`, thus rather than execute the JSP, the source code of the JSP is returned by the file system. - -==== Good Security Practise - -Part of the problem with aliases is that the standard web application security model is to allow all requests except the ones that are specifically denied by security constraints. -A best practice for security is to deny all requests and to permit only those that are specifically identified as allowable. -While it is possible to design web application security constraints in this style, it can be difficult in all circumstances and it is not the default. T -hus it is important for Jetty to be able to detect and deny requests to aliased static content. - -[[file-alias-detection]] -==== Alias detection - -It is impossible for Jetty to know of all the aliases that may be implemented by the file system running beneath it, thus it does not attempt to make any specific checks for any know aliases. -Instead Jetty detects aliases by using the canonical path of a file. -If a file resource handled by jetty has a canonical name that differs from the name used to request the resource, then Jetty determines that the resource is an aliased request and it will not be returned by the `ServletContext.getResource(String)` method (or similar) and thus will not be served as static content nor used as the basis of a JSP. - -This if Jetty is running on a Windows operating system, then a file called `/MySecret.TXT` will have a canonical name that exactly matches that case. -So while a request to `/mysecret.txt` or `/MYSECR~1.TXT` will result in a File Resource that matches the file, the different canonical name will indicate that those requests are aliases and they will not be served as static content and instead a 404 response returned. - -Unfortunately this approach denies all aliases, including symbolic links, which can be useful in assembling complex web applications. - -[[file-alias-serving]] -==== Serving Aliases and Symbolic Links - -Not all aliases are bad nor should be seen as attempts to subvert security constraints. -Specifically, symbolic links can be very useful when assembling complex web applications. -As such, Jetty contexts support an extensible `AliasCheck` mechanism to allow aliases resources to be inspected and conditionally served. -In this way, "good" aliases can be detected and served. -Jetty provides several utility implementations of the `AliasCheck` interface as nested classes with `ContextHandler`: - -ApproveAliases:: - Approve all aliases (*Use with caution!*). -AllowSymLinkAliasChecker:: - Approve Aliases using the java-7 `Files.readSymbolicLink(path)` and `Path.toRealPath(...)` APIs to check that aliases are valid symbolic links. - -____ -[NOTE] -By default, Jetty serves aliased files for implementations running on UNIX as Contexts are created with both the {JDURL}/org/eclipse/jetty/server/handler/AllowSymLinkAliasChecker.html[`AllowSymLinkAliasChecker`] and {JDURL}/org/eclipse/jetty/server/handler/ContextHandler.ApproveNonExistentDirectoryAliases.html[`ApproveNonExistentDirectoryAliases`] alias checkers. -____ - -An application is free to implement its own Alias checking. -Alias Checkers can be installed in a context via the following XML used in a context deployer file or `WEB-INF/jetty-web.xml`: - -[source, xml, subs="{sub-order}"] ----- - - - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/setting-port80-access-for-non-root-user.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/setting-port80-access-for-non-root-user.adoc deleted file mode 100644 index 85c8d10c925e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/setting-port80-access-for-non-root-user.adoc +++ /dev/null @@ -1,134 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 `iptables` usually is): - -[source, screen, subs="{sub-order}"] ----- -# /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: - -[source, screen, subs="{sub-order}"] ----- -# /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 outside of the server itself. -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 rights 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: - -. 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. -. 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). -. Enable the `setuid.mod` module: -+ -[source, screen, subs="{sub-order}"] ----- -# 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 for a single execution. -For more information on the alternatives see the section on link:#startup-modules[Managing Startup Modules]. -____ - -. Edit the configuration for the `setuid` module to substitute the `userid` and `groupid` of the user to switch to after starting. -If your server instance has a `${jetty.base/start.d}` directory, this configuration is in the `start.d/setuid.ini` file instead. -Otherwise. this configuration is in the `${jetty.base}start.ini` file. - - Below are the lines to configure: -+ -[source, text, subs="{sub-order}"]] ----- -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. -____ - -. A native code library is required to perform user switching. -This code is hosted as part of the https://github.com/eclipse/jetty.toolchain[Jetty ToolChain] project and is released independently from Jetty itself. -You can find the source code in the https://github.com/eclipse/jetty.toolchain/tree/master/jetty-setuid[eclipse/jetty.toolchain/jetty-setuid] project. -Build it locally, which will produce a native library appropriate for the operating system: -+ -[source, screen, subs="{sub-order}"] ----- -# 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 may want copy this file into your Jetty distribution's lib directory. - -. Start Jetty as the `root` user in your base directory, providing the location of the native library to Java. -Below is an example of how to do it from the command line, assuming you are in the link:#demo-webapps-base[demo-base] directory: -+ -[source, screen, subs="{sub-order}"] ----- -# 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: - -[source, screen, subs="{sub-order}"] ----- -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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/spnego-support.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/spnego-support.adoc deleted file mode 100644 index 9f3814d06c82..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/security/spnego-support.adoc +++ /dev/null @@ -1,133 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[spnego-support]] -=== SPNEGO Support - -Simple and Protected GSSAPI Negotiation Mechanism (SPNEGO) is a way for users -to be seamlessly authenticated when running on systems that rely on Kerberos -for authentication, such as Windows Active Directory based networks. - -Jetty supports this type of authentication and authorization through the JDK -(which has been enabled since the later versions of Java 6 and 7). - -==== Configuring Jetty and SPNEGO - -To run with SPNEGO enabled the following command line options are required: - -[source,screen, subs="{sub-order}"] ----- --Djava.security.krb5.conf=/path/to/krb5.ini ----- - -For debugging the SPNEGO authentication the following options are helpful: - -[source,screen, subs="{sub-order}"] ----- --Dorg.eclipse.jetty.LEVEL=debug --Dsun.security.spnego.debug=true --Dsun.security.jgss.debug=true --Dsun.security.krb5.debug=true ----- - -SPNEGO authentication must be enabled in the webapp in the following way. -The name of the role will be different for your network. - -[source, xml, subs="{sub-order}"] ----- - - - Secure Area - /secure/me/* - - - - MORTBAY.ORG - - - - SPNEGO - Test Realm - - - /loginError.html?param=foo - - ----- - -A corresponding `UserRealm` needs to be created either programmatically if -embedded, via the `jetty.xml` or in a context file for the webapp. - -This is what the configuration within a context XML file would look like: - -[source, xml, subs="{sub-order}"] ----- - - - - Test Realm - - - - - ----- - -On the Windows Active Domain Controller run: - -[source, screen, subs="{sub-order}"] ----- -$ setspn -A HTTP/linux.mortbay.org ADUser ----- - -To create the keyTab file use the following process: - -[source, screen, subs="{sub-order}"] ----- -$ ktpass -out c:\dir\krb5.keytab -princ HTTP/linux.mortbay.org@MORTBAY.ORG -mapUser ADUser -mapOp set -pass ADUserPWD -crypto RC4-HMAC-NT -pType KRB5_NT_PRINCIPAL ----- - -This step will give you the keyTab file which should then be copied to the -machine running the http server and referenced from the configuration files. - -==== Configuring Firefox - -The follows steps have been required to inform Firefox that it should use a negotiation dialog to authenticate. - -1. Browse to about:config and agree to the warnings -2. Search through to find the 'network' settings -3. Set `network.negotiate-auth.delegation-uris` to http://,https:// -4. Set `network.negotiate-auth.trusted-uris` to http://,https:// - -==== Configuring Internet Explorer - -The follows steps have been required to inform Internet Explorer that it should use a negotiation dialog to authenticate. - -1. Tools -> Options -> Security -> Local Intranet -> Sites (everything should be checked here) -2. Tools -> Options -> Security -> Local Intranet -> Sites -> Advanced (add url to server (`http://` and/or `https://` -- use the hostname, not the IP) -3. Tools -> Options -> Security -> Local Intranet -> Sites -> Advanced -> Close -4. Tools -> Options -> Security -> Local Intranet -> Sites -> Ok -5. Tools -> Options -> Advanced -> Security (in the checkbox list) -6. Locate and select `Enable Integrated Windows Authentication` -7. Tools -> Options -> Advanced -> Security -> Ok -8. Close IE then reopen and browse to your SPNEGO protected resource - -You *must* use hostname and not the IP. -If you use the IP it will default to NTLM authentication. -The following conditions must be true for SPNEGO authentication to work: - -* You must be within the Intranet Zone of the network -* Access the server using a Hostname rather than IP -* Integrated Windows Authentication in IE is enabled and/or the host is trusted in Firefox -* The server is not local to the browser; it can't be running on localhost -* The client's Kerberos system is authenticated to a domain controller diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/chapter.adoc deleted file mode 100644 index 121a6ba0bdcb..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/chapter.adoc +++ /dev/null @@ -1,18 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[startup]] -== Starting Jetty - -include::startup-unix-service.adoc[] -include::startup-windows-service.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/startup-unix-service.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/startup-unix-service.adoc deleted file mode 100644 index 207f66c8ece2..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/startup-unix-service.adoc +++ /dev/null @@ -1,271 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 distros (including OSX) to manage Jetty as a startup service. - -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 include: - -[source, screen, subs="{sub-order}"] -.... -[/opt/jetty]# tar -zxf /home/user/downloads/jetty-home-{VERSION}.tar.gz -[/opt/jetty]# cd jetty-home-{VERSION}/ -[/opt/jetty/jetty-home-{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-home-{VERSION}]# cp bin/jetty.sh /etc/init.d/jetty -[/opt/jetty/jetty-home-{VERSION}]# echo JETTY_HOME=`pwd` > /etc/default/jetty -[/opt/jetty/jetty-home-{VERSION}]# cat /etc/default/jetty -JETTY_HOME=/opt/jetty/jetty-home-{VERSION} - -[/opt/jetty/jetty-home-{VERSION}]# service jetty start -Starting Jetty: OK Wed Nov 20 10:26:53 MST 2013 -.... - -From this demonstration we can see that Jetty started successfully as a Unix Service from the `/opt/jetty/jetty-home-{VERSION}` directory. - -This configuration works well but it is running Jetty as the root user. - -==== 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. - -[source, screen, subs="{sub-order}"] -.... -# 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 9.3 requires Java 8 (or greater) to run. -Make sure you have it installed. - -[source, screen, subs="{sub-order}"] -.... -# apt-get install openjdk-8-jdk -.... - -Or download Java 8 from: http://www.oracle.com/technetwork/java/javase/downloads/index.html - -[source, screen, subs="{sub-order}"] -.... -# 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. - -[source, screen, subs="{sub-order}"] -.... -# 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`. - -Download a copy of the Jetty distribution from the link:#jetty-downloading[Official Eclipse Download Site] - -Unpack it into place. - -[source, screen, subs="{sub-order}"] -.... -[/opt/jetty]# tar -zxf /home/user/Downloads/jetty-home-{VERSION}.tar.gz -[/opt/jetty]# ls -F -jetty-home-{VERSION}/ -[/opt/jetty]# mkdir /opt/jetty/temp -.... - -It might seem strange or undesirable to unpack the first portion of the jetty-home directory name too. -But starting with Jetty 9 the split between `${jetty.home}` and `${jetty.base}` allows for easier upgrades of Jetty itself while isolating your webapp specific configuration. -For more information on the Jetty home and base concepts see the section on managing a Jetty installation link:#startup-base-and-home[earlier in this Chapter.] - -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-home` 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-home` upgrades in the future. --- - -[source, screen, subs="{sub-order}"] -.... -# cd /opt/web/mybase/ -[/opt/web/mybase]# ls -[/opt/web/mybase]# java -jar /opt/jetty/jetty-home-{VERSION}/start.jar \ - --add-to-start=deploy,http,console-capture - INFO : webapp transitively enabled, ini template available with --add-to-start=webapp - INFO : server transitively enabled, ini template available with --add-to-start=server - INFO : security transitively enabled - INFO : servlet transitively enabled - INFO : console-capture initialized in ${jetty.base}/start.ini - INFO : http initialized in ${jetty.base}/start.ini - INFO : deploy initialized in ${jetty.base}/start.ini - MKDIR : ${jetty.base}/logs - MKDIR : ${jetty.base}/webapps - INFO : Base directory was modified -[/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. -console-capture:: -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. - -Additionally, the `webapp`, `server`, `security` and `servlet` modules were enabled as they are dependencies for other modules. - -See xref:start-jar[] for more details and options on setting up and configuring a `${jetty.base}` directory. - -Copy your war file into place. - -[source, screen, subs="{sub-order}"] -.... -# cp /home/user/projects/mywebsite.war /opt/web/mybase/webapps/ -.... - -Most service installations will want Jetty to run on port 80, now is the 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. - -[source, screen, subs="{sub-order}"] -.... -# grep jetty.http.port /opt/web/mybase/start.ini -jetty.port=80 -.... - -Change the permissions on the Jetty distribution and webapp directories so that the user you created can access it. - -[source, screen, subs="{sub-order}"] -.... -# 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. - -[source, screen, subs="{sub-order}"] -.... -# cp /opt/jetty/jetty-home-{VERSION}/bin/jetty.sh /etc/init.d/jetty -# echo "JETTY_HOME=/opt/jetty/jetty-home-{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: - -[source, screen, subs="{sub-order}"] -.... -# service jetty status -Checking arguments to Jetty: -START_INI = /opt/web/mybase/start.ini -JETTY_HOME = /opt/jetty/jetty-home-{VERSION} -JETTY_BASE = /opt/web/mybase -JETTY_CONF = /opt/jetty/jetty-home-{VERSION}/etc/jetty.conf -JETTY_PID = /var/run/jetty.pid -JETTY_START = /opt/jetty/jetty-home-{VERSION}/start.jar -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-home-{VERSION} - -Djetty.base=/opt/web/mybase - -Djava.io.tmpdir=/opt/jetty/temp -JETTY_ARGS = console-capture.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-home-{VERSION} - -Djetty.base=/opt/web/mybase - -Djava.io.tmpdir=/opt/jetty/temp - -jar /opt/jetty/jetty-home-{VERSION}/start.jar - console-capture.xml - jetty-started.xml -.... - -You now have a configured `${jetty.base}` in `/opt/web/mybase` and a `${jetty.home}` in `/opt/jetty/jetty-home-{VERSION}`, along with the service level files necessary to start the service. - -Test the service to make sure it starts up and runs successfully. - -[source, screen, subs="{sub-order}"] -.... -# 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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/startup-windows-service.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/startup-windows-service.adoc deleted file mode 100644 index 098d0eafb701..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/startup/startup-windows-service.adoc +++ /dev/null @@ -1,293 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 8 (64-bit), running on an Intel i7 architecture machine. - -Prepare some empty directories to work with. - -[source, screen, subs="{sub-order}"] -.... -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 . -11/21/2013 04:06 PM .. -11/21/2013 04:06 PM jetty -11/21/2013 04:06 PM logs -11/21/2013 04:06 PM myappbase -11/21/2013 04:06 PM 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 8 from: http://www.oracle.com/technetwork/java/javase/downloads/index.html - -[source, screen, subs="{sub-order}"] -.... -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) -.... - -Download a copy of the ZIP distribution from the link:#jetty-downloading[Official Eclipse Download Site] - -Extract the contents of the `jetty-home-{VERSION}` directory to `C:\opt\jetty` - -Once complete, the contents of the `C:\opt\jetty` directory should look like this: - -[source, screen, subs="{sub-order}"] -.... -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 . -11/21/2013 12:13 PM .. -11/21/2013 12:13 PM bin -11/21/2013 12:13 PM demo-base -11/21/2013 12:13 PM etc -11/21/2013 12:13 PM lib -11/21/2013 12:13 PM 30,012 license-eplv10-aslv20.html -11/21/2013 12:13 PM logs -11/21/2013 12:13 PM 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 resources -11/21/2013 12:13 PM 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 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[Apache ProcRun] native binaries. - -You should have downloaded a file named `commons-daemon-1.0.15-bin-windows.zip` (the version might be different). -Open the ZIP file and extract the `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: - -[source, screen, subs="{sub-order}"] -.... -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 . -11/21/2013 04:06 PM .. -11/21/2013 04:06 PM jetty -11/21/2013 04:06 PM logs -11/21/2013 04:06 PM myappbase -11/21/2013 04:06 PM 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) - -[source, screen, subs="{sub-order}"] -.... -C:\opt\myappbase>java -jar ..\jetty\start.jar --add-to-start=deploy,http,console-capture - -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 . -11/21/2013 12:49 PM .. -11/21/2013 12:49 PM logs -11/21/2013 12:49 PM 1,355 start.ini -11/21/2013 12:49 PM 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 the section on 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 `{$jetty.base}/webapps` directory. - -[source, screen, subs="{sub-order}"] -.... -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/` (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:windows-service-jetty.png[image,width=576] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/chapter.adoc deleted file mode 100644 index 338839cccd18..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/chapter.adoc +++ /dev/null @@ -1,24 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[troubleshooting]] -== Troubleshooting - -This is a collection of helpful tricks and tips that we have come across to address odd issues that might arise. - -include::troubleshooting-zip-exceptions.adoc[] -include::troubleshooting-locked-files.adoc[] -include::preventing-memory-leaks.adoc[] -include::slow-deployment.adoc[] -include::security-reports.adoc[] -include::watchservice.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/preventing-memory-leaks.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/preventing-memory-leaks.adoc deleted file mode 100644 index 78e890a6d77f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/preventing-memory-leaks.adoc +++ /dev/null @@ -1,158 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[preventing-memory-leaks]] -=== Preventing Memory Leaks - -If you have memory leaks, and you have thoroughly investigated tools like jconsole, yourkit, jprofiler, jvisualvm or any of the other profiling and analysis tools, and you can eliminate your code as the source of the problem, read the following sections about how to prevent memory leaks in your application. - -[[preventing-webapp-classloader-pinning]] -==== Preventing WebApp Classloader Pinning - -____ -[NOTE] -This feature is available for Jetty 7.6.6 and later. -____ - -Code that keeps references to a webapp classloader can cause memory leaks. -These leaks fall generally into two categories: static fields and daemon threads. - -* A static field is initialized with the value of the classloader, which happens to be a webapp classloader; as Jetty undeploys and redeploys the webapp, the static reference lives on, meaning garbage collecting cannot occur for the webapp classloader. -* When Jetty starts as a daemon thread and is outside the lifecycle of the webapp, threads have references to the context classloader that created them, leading to a memory leak if that classloader belongs to a webapp. -For a good discussion of the issue see http://cdivilly.wordpress.com/tag/sun-awt-appcontext/[Anatomy of a PermGen Memory Leak.] - -We provide a number of link:{JDURL}//org/eclipse/jetty/util/preventers/package-summary.html[workaround classes] that preemptively invoke the problematic code with the Jetty classloader, thereby ensuring the webapp classloader is not pinned. -Be aware that since some of the problematic code creates threads, you should be selective about which preventers you enable, and use only those that are specific to your application. - -[[preventers-table]] -===== Preventers - -Jetty includes the following preventers. - -[cols=",",options="header",] -|======================================================================= -|Preventer Name |Problem Addressed -|AppContextLeakPreventer |The call to `AppContext.getAppContext()` keeps a static reference to the context classloader. The JRE can invoke AppContext in many different places. - -|AWTLeakPreventer |The `java.awt.Toolkit` class has a static field that is the default toolkit. -Creating the default toolkit causes the creation of an `EventQueue`, which has a classloader field initialized with the thread context class loader. -See https://issues.jboss.org/browse/AS7-3733[JBoss bug AS7-3733.] - -|DOMLeakPreventer |DOM parsing can cause the webapp classloader to be pinned, due to the static field ` RuntimeException` of `com.sun.org.apache.xerces.internal.parsers.AbstractDOMParser.` http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6916498[Oracle bug 6916498] specifically mentions that a heap dump might not identify the GCRoot as the uncollected loader, making it difficult to identify the cause of the leak. - -|DriverManagerLeakPreventer |The number of threads dedicated to accepting incoming connections. - -|GCThreadLeakPreventer |Calls to `sun.misc.GC.requestLatency` create a daemon thread that keeps a reference to the context classloader. -A known caller of this method is the RMI impl. See http://stackoverflow.com/questions/6626680/does-java-garbage-collection-log-entry-full-gc-system-mean-some-class-called[Stackoverflow: Does java garbage collection log entry 'Full GC system' mean some class -called System.gc()?] - -|Java2DLeakPreventer |`sun.java2d.Disposer` keeps a reference to the classloader. -See https://issues.apache.org/bugzilla/show_bug.cgi?id=51687[ASF bug 51687.] - -|LDAPLeakPreventer |If `com.sun.jndi.LdapPoolManager` class is loaded and the system property ` com.sun.jndi.ldap.connect.pool.timeout` is set to a nonzero value, a daemon thread starts and keeps a reference to the context classloader. - -|LoginConfigurationLeakPreventer |The `javax.security.auth.login.Configuration` class keeps a static reference to the thread context classloader. - -|SecurityProviderLeakPreventer |Some security providers, such as `sun.security.pkcs11.SunPKCS11` start a deamon thread that traps the thread context classloader. -|======================================================================= - -[[configuring-preventers]] -===== Configuring Preventers - -You can individually enable each preventer by adding an instance to a Server with the ` addBean(Object)` call. Here's an example of how to do it in code with the `org.eclipse.jetty.util.preventers.AppContextLeakPreventer`: - -[source, java, subs="{sub-order}"] ----- - -Server server = new Server(); -server.addBean(new AppContextLeakPreventer()); - - ----- - -You can add the equivalent in code to the `$JETTY_HOME/etc/jetty.xml` file or any jetty xml file that is configuring a Server instance. -Be aware that if you have more than one Server instance in your JVM, you should configure these preventers on just _one_ of them. -Here's the example from code put into xml: - -[source, xml, subs="{sub-order}"] ----- - - - - - - - - - - - - ----- - -[[jsp-bugs]] -==== JSP Bugs: Permgen Problems - -The JSP engine in Jetty is Jasper. -This was originally developed under the Apache Tomcat project, but over time many different project have forked it. -All Jetty versions up to 6 used Apache-based Jasper exclusively, with Jetty 6 using Apache Jasper only for JSP 2.0. -With the advent of JSP 2.1, Jetty 6 switched to using Jasper from Sun's https://glassfish.java.net/[Glassfish] project, which is now the reference implementation. - -All forks of Jasper suffer from a problem whereby using JSP tag files puts the permgen space under pressure. -This is because of the classloading architecture of the JSP implementation. -Each JSP file is effectively compiled and its class loaded in its own classloader to allow for hot replacement. -Each JSP that contains references to a tag file compiles the tag if necessary and then loads it using its own classloader. -If you have many JSPs that refer to the same tag file, the tag's class is loaded over and over again into permgen space, once for each JSP. -See http://java.net/jira/browse/GLASSFISH-3963[Glassfish bug 3963] and https://issues.apache.org/bugzilla/show_bug.cgi?id=43878[Apache bug 43878.] -The Apache Tomcat project has already closed this bug with status WON'T FIX, however the Glassfish folks still have the bug open and have scheduled it to be fixed. -When the fix becomes available, the Jetty project will pick it up and incorporate into our release program. - -[[jvm-bugs]] -==== JVM Bugs - -This section describes garbage collection and direct ByteBuffer problems. - -[[jvm-garbage-collection-problems]] -===== Garbage Collection Problems - -One symptom of a cluster of JVM related memory issues is the OOM exception accompanied by a message such as `java.lang.OutOfMemoryError: requested xxxx bytes for xxx. -Out of swap space?` - -http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4697804[Oracle bug 4697804] describes how this can happen in the scenario when the garbage collector needs to allocate a bit more space during its run and tries to resize the heap, but fails because the machine is out of swap space. -One suggested work around is to ensure that the JVM never tries to resize the heap, by setting min heap size to max heap size: - -[source,text] ----- - -java -Xmx1024m -Xms1024m - - ----- - -Another workaround is to ensure you have configured sufficient swap space on your device to accommodate all programs you are running concurrently. - -[[direct-byte-buffers]] -===== Direct ByteBuffers - -Exhausting native memory is another issue related to JVM bugs. -The symptoms to look out for are the process size growing, but heap use remaining relatively constant. -Both the JIT compiler and nio ByteBuffers can consume native memory. -http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6210541[Oracle bug 6210541] discusses a still-unsolved problem whereby the JVM itself allocates a direct ByteBuffer in some circumstances while the system never garbage collects, effectively eating native memory. -Guy Korland's blog discusses this problem http://www.jroller.com/gkorland/entry/java_s_memory_isn_t[here] and http://www.jroller.com/gkorland/entry/java_s_memory_managment_is[here.] -As the JIT compiler consumes native memory, the lack of available memory may manifest itself in the JIT as OutOfMemory exceptions such as `Exception in thread "CompilerThread0" java.lang.OutOfMemoryError: requested xxx bytes for ChunkPool::allocate. Out of swap - space?` - -By default, Jetty allocates and manages its own pool of direct ByteBuffers for io if you configure the nio SelectChannelConnector. -It also allocates MappedByteBuffers to memory-map static files via the DefaultServlet settings. -However, you could be vulnerable to this JVM ByteBuffer allocation problem if you have disabled either of these options. -For example, if you're on Windows, you may have disabled the use of memory-mapped buffers for the static file cache on the DefaultServlet to avoid the file-locking problem. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/security-reports.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/security-reports.adoc deleted file mode 100644 index 10add18b096f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/security-reports.adoc +++ /dev/null @@ -1,34 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[security-reports]] -=== Jetty Security Reports - -==== List of Security Reports - -A current list of Jetty security reports can be viewed on the link:https://jetty.org/security-reports.php[Project Home Page.] - -==== Reporting Security Issues - -There are a number of avenues for reporting security issues to the Jetty project available. - -If the issue is directly related to Jetty itself then reporting to the Jetty developers is encouraged. -The most direct method is to mail _security@webtide.com_. -Since Webtide is comprised of the active committers of the Jetty project this is our preferred reporting method. -We are generally flexible in how we work with reporters of security issues but we reserve the right to act in the interests of the Jetty project in all circumstances. - -If the issue is related to Eclipse or its Jetty integration then we encourage you to reach out to _security@eclipse.org_. - -If the issue is related to integrations with Jetty we are happy to work with you to identify the proper entity and either of the approaches above is fine. - -We prefer that security issues are reported directly to Jetty developers as opposed through GitHub Issues since it currently has *no* facility to tag issues as _private_. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/slow-deployment.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/slow-deployment.adoc deleted file mode 100644 index 8c9ac6ab1c9d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/slow-deployment.adoc +++ /dev/null @@ -1,46 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[troubleshooting-slow-deployment]] -=== Troubleshooting Slow Deployment - -After upgrading to a version of Jetty that supports Servlet Spec 3.0 or above, enabling some new modules, or introducing some new jars to your webapp, you notice that your deployment time is increased. -This could be due to scanning for classes caused by a ServletContainerInitializer. - -As documented in the section on link:#using-annotations[Using Annotations], even if your webapp has set `metadata-complete=true` in web.xml, all jars within your webapp may still be scanned due to one or more ServletContainerInitializers that have a http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/HandlesTypes.html[@HandlesTypes] annotation listing the names of classes in which it is interested. - -There are 3 ways to speed up deployment time: - -* limit which ServletContainerInitializers to include -* limit which jars to scan -* limit the scan to the first deployment only - -==== Remedies - -===== Limit Which ServletContainerInitializers to Execute - -As documented in the section link:#excluding-scis[Excluding ServletContainerInitializers], you can provide a context attribute that defines a pattern of ServletContainerInitializer (SCI) class names to ignore. -These SCIs will not be examined for http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/HandlesTypes.html[@HandlesTypes] and will not be executed. -This is useful if you have included a 3rd party jar that has a SCI on which your code does not rely. - -===== Limit Which Jars to Scan - -As documented in the section link:#jars-scanned-for-annotations[Jars Scanned for Annotations], you can explicitly define which jars to include in the scanning process. -This is helpful if you have a lot of jars in your webapp, and you know that they do not contain any classes referenced by an @HandlesTypes annotation on a ServletContainerInitializer that will be executed. - -===== Limit Scanning to First Deployment Only (Quickstart) - -The link:#quickstart-webapp[quickstart mechanism] will do a normal deployment - obeying any limits on SCIs and jars to scan as documented here - the first time the webapp is deployed only. -Subsequent deployments will re-use the information discovered during the first deployment. -This is useful if you cannot limit the scan significantly by using any of the mechanisms described here, but you don't want to incur the cost of scanning on every redeployment. -The link:#quickstart-webapp[quickstart mechanism] and how to use it is described link:#quickstart-webapp[here]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/troubleshooting-locked-files.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/troubleshooting-locked-files.adoc deleted file mode 100644 index 7a8546913e7a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/troubleshooting-locked-files.adoc +++ /dev/null @@ -1,92 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[troubleshooting-locked-files-on-windows]] -=== Troubleshooting Locked Files on Windows - -Jetty buffers static content for webapps such as HTML files, CSS files, images, etc. -If you are using NIO connectors, Jetty uses memory-mapped files to do this. -The problem is that on Windows, memory mapping a file causes the file to lock, so that you cannot update or replace the file. -Effectively this means that you have to stop Jetty to update a file. - -==== Remedy - -Jetty provides a configuration switch for the `DefaultServlet` that enables or disables the use of memory-mapped files. -If you are running on Windows and are having file-locking problems, you should set this switch to disable memory-mapped file buffers. -Use one of the following options to configure the switch. - -===== Using override-web.xml - -An <> file can be placed in your webapp's `WEB-INF` directory to change the default setting of the `DefaultServlet` for memory-mapped file buffers. -Create an `override-web.xml` file with appropriate headers for your version of the servlet specification, and place the following inside the `` element: - -[source, xml, subs="{sub-order}"] ----- - - default - - useFileMappedBuffer - false - - ----- - -===== Using a Context XML File - -You can create or update a context xml file that configures your webapp to apply the setting to disable memory-mapped file buffers. -Add the following to your context xml file: - -[source, xml, subs="{sub-order}"] ----- - - org.eclipse.jetty.servlet.Default.useFileMappedBuffer - false - ----- - - -===== Using the Jetty Maven Plugin - -If you don't want to use either of the other two solutions, you can configure the plugin directly to disable memory-mapped file buffers. -Add the following to the plugin's configuration under the `` element: - -[source, xml, subs="{sub-order}"] ----- - <_initParams> - false - ----- - - - -==== Alternate Remedy - -You can force a `WebAppContext` to always copy a web app directory on deployment. -The base directory of your web app (i.e. the root directory where your static content exists) will be copied to the link:#ref-temporary-directories[temp directory]. -Configure this in an xml file like so: - -[source, xml, subs="{sub-order}"] ----- - - / - ./webapps/fredapp - true - . - . - ----- - -____ -[NOTE] -Be careful with this option when using an explicitly setlink:#ref-temp-directories[temp directory] name - as the name of the temp directory will not unique across redeployments, copying the static content into the same directory name each time may not avoid the locking problem. -____ diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/troubleshooting-zip-exceptions.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/troubleshooting-zip-exceptions.adoc deleted file mode 100644 index 2b680f931eb4..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/troubleshooting-zip-exceptions.adoc +++ /dev/null @@ -1,39 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[troubleshooting-zip-exceptions]] -=== Troubleshooting Zip Exceptions - -A Zip exception occurs when Jetty rereads a Jar or WAR file. - -The JVM maintains a cache of zip file indexes, and does not support hot replacement of zip files. -Thus if you redeploy a web application using the same WAR or Jar files, exceptions occur when Jetty rereads the jars. -See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4774421[Oracle Bug 4774421] for more information. - -[[remedy]] -==== Remedy - -The remedy is to avoid hot replacing Jar or WAR files, which can be difficult if you are using the -link:#configuring-specific-webapp-deployment[Webapp Provider]. -You can use the following techniques to reduce exposure to this issue: - -* Deploy unpacked classes in the `WEB-INF/classes` directory rather than as a Jar file under `WEB-INF/lib`. -* Deploy all WAR and Jar files with a version number in their filename or path. -If the code changes, a new version number applies, avoiding the cache problem. -* Deploy a packed WAR file with the link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setExtractWAR(boolean)[setExtractWAR] option set to true. -This causes the WAR to be extracted to a link:#ref-temporary-directories[temporary directory] and thus to a new location. -This might not be sufficient if you want to hot-replace and re-extract the WAR, so you might also need to use link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setCopyWebInf(boolean)[WebAppContext.setCopyWebInf(true)], which (re)copies just the WEB-INF directory to a different location. -* Deploy an unpacked WAR file with the link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setCopyWebDir(boolean)[setCopyWebDir] option set to true. -This causes the directory to be extracted to a new location. - -If you have problems with link:#troubleshooting-locked-files-on-windows[Windows file-locking] preventing static file editing (such as JSP or HTML), use the link:{JDURL}/org/eclipse/jetty/webapp/WebAppContext.html#setCopyWebDir(boolean)[WebAppContext .setCopyWebDir(true)] option. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/watchservice.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/watchservice.adoc deleted file mode 100644 index 9407b98d5a44..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/troubleshooting/watchservice.adoc +++ /dev/null @@ -1,32 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[watchservice]] -=== Java WatchService - -The JVM link:https://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html[`WatchService`] is in place to monitor objects like a directory for changes, and then update it's contents and notify the application of those changes. -This service is useful for features like link:#hot-deployment[Hot Deployment]. -When a change is detected, the `WatchService` will enter a "quiet time" where it is waiting for the change (or changes) to be made and completed before notifying the application of the change. - -Example: -A new war file is copied into `/webapps`. -The `WatchService` can (depending on implementation) see that the file was created (which is registered as an event!, and that its growing in size (another event). -With the quiet time, each of the events are gated behind that timeout before the aggregated events are sent to the application. - -While some operating systems such as Windows have a native value for this quiet time, not all do, notably OSX. -At the core this is a limitation of the JVM's FileSystem-specific implementation, but one that has been raised to the link:https://bugs.openjdk.java.net/browse/JDK-7133447[attention of the project.] - -==== Remedy - -To help offset the delay in systems like OSX, Jetty defaults the value for non-native implementations to a link:{GITBROWSEURL}/jetty-util/src/main/java/org/eclipse/jetty/util/PathWatcher.java#L1431[time of 5000ms.] -Using values lower than 5000ms is not recommended and has shown to frequently fail. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/chapter.adoc deleted file mode 100644 index 40c80a597197..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/chapter.adoc +++ /dev/null @@ -1,25 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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? -This chapter examines a few of the many different ways to optimize Jetty. - -include::garbage-collection.adoc[] -include::high-load.adoc[] -include::limit-load.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/garbage-collection.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/garbage-collection.adoc deleted file mode 100644 index 1bd0944d6d97..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/garbage-collection.adoc +++ /dev/null @@ -1,52 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[garbage-collection]] -=== Garbage Collection - -Tuning the JVM garbage collection (GC) can greatly improve the performance of the JVM where Jetty and your application are running. -Optimal tuning of the GC depends on the behavior of the application(s) and requires detailed analysis, but there are general recommendations to follow to at least obtain comprehensive GC logs that can be later analyzed. - -See official https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/[Java 8] and https://docs.oracle.com/javase/9/gctuning/introduction-garbage-collection-tuning.htm[Java 9] Garbage Collection documentation for further assistance. - -[[garbage-collection-logging-configuration]] -==== Garbage Collection Logging Configuration - -These options are general to OpenJDK (and therefore also for the Oracle JVM). -They provide good information about the GC activity of your JVM, producing logs that can later be analyzed to perform finer tuning. - -.JDK 8 Garbage Collection Logging Configuration -[source,screen, subs="{sub-order}"] -.... --Xloggc:/path/to/myjettybase/logs/gc.log --XX:+PrintGCDateStamps --XX:+PrintGCDetails --XX:+ParallelRefProcEnabled --XX:+PrintReferenceGC --XX:+PrintTenuringDistribution --XX:+PrintAdaptiveSizePolicy -.... - -.JDK 9 Garbage Collection Logging Configuration -[source,screen, subs="{sub-order}"] -.... -Xlog:gc*,ergo*=trace,ref*=debug,age*=trace:file=/path/to/myjettybase/logs/gc.log:time,level,tags -.... - -There are not many recommended options for GC that can apply to 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). - -[source,screen, subs="{sub-order}"] -.... --XX:+DisableExplicitGC -.... diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/high-load.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/high-load.adoc deleted file mode 100644 index a09f86787726..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/high-load.adoc +++ /dev/null @@ -1,154 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 - -Machines handling load generation 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. -Avoid the following pitfalls: - -* 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 asynchronously 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 these 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 (keep in mind that you need to consider buffer bloat). - -[source, screen, subs="{sub-order}"] -.... -$ 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 value. -This setting can take a bit of finesse to get correct: 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. - -[source, screen, subs="{sub-order}"] -.... - $ 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 adjusted with: - -[source, screen, subs="{sub-order}"] -.... -$ 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`: - -[source, screen, subs="{sub-order}"] -.... -$ 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: - -[source, screen, subs="{sub-order}"] -.... -$ 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: - -[source, screen, subs="{sub-order}"] -.... -$ 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:#tuning-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 this is >50 and <500 diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/limit-load.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/limit-load.adoc deleted file mode 100644 index 3a02ed1b3092..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/tuning/limit-load.adoc +++ /dev/null @@ -1,38 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[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 enable the the `lowresources.mod` on the command line, which has the effect of including the following XML configuration: - -[source, xml, subs="{sub-order}"] ----- -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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/chapter.adoc deleted file mode 100644 index b92509731fab..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/chapter.adoc +++ /dev/null @@ -1,18 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[websocket-java]] -== Java Websocket API - -JSR-356 These pages are works in progress that have not been moved to -their respective sections yet. diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/java-websocket-client-api.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/java-websocket-client-api.adoc deleted file mode 100644 index ca701448c066..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/java-websocket-client-api.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[java-websocket-client-api]] -= Java WebSocket Client API Usage - -== Java WebSocket Client API - -The simpler way to perform a websocket request is the following: diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/java-websocket-server-api.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/java-websocket-server-api.adoc deleted file mode 100644 index 5cb0b89c4dcf..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/java/java-websocket-server-api.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[java-websocket-server-api]] -= Java WebSocket Server API - -== Java WebSocket Server API - -The simpler way to perform a websocket request is the following: diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/jetty/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/jetty/chapter.adoc deleted file mode 100644 index b364527d8e4f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/jetty/chapter.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[websocket-jetty]] -== Jetty Websocket API - -These pages are works in progress that have not been moved to their respective sections yet. - -include::jetty-websocket-server-api.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/jetty/jetty-websocket-server-api.adoc b/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/jetty/jetty-websocket-server-api.adoc deleted file mode 100644 index d69b7541c482..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/old_docs/websockets/jetty/jetty-websocket-server-api.adoc +++ /dev/null @@ -1,76 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[websocket-jetty-server-api]] -=== Jetty WebSocket Server API - -Jetty provides the ability to wire up WebSocket endpoints to Servlet Path Specs via the use of a `JettyWebSocketServlet` bridge servlet. - -Internally, Jetty manages the HTTP Upgrade to WebSocket and migration from a HTTP Connection to a WebSocket Connection. - -This will only work when running within the Jetty Container (unlike past Jetty technologies, you cannot get Jetty WebSocket server functionality running Jetty within other containers like JBoss, Tomcat, or WebLogic). - -==== The Jetty WebSocketServlet - -To wire up your WebSocket to a specific path via the `JettyWebSocketServlet`, you will need to extend `org.eclipse.jetty.websocket.servlet.JettyWebSocketServlet` and specify what `WebSocket` object should be created with incoming Upgrade requests. - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/examples/MyEchoServlet.java[] ----- - -This example will create a Servlet mapped via the http://docs.oracle.com/javaee/6/api/javax/servlet/annotation/WebServlet.html[@WebServlet] annotation to the Servlet path spec of `"/echo"` (or you can do this manually in the `WEB-INF/web.xml` of your web application) which will create MyEchoSocket instances when encountering HTTP Upgrade requests. - -The link:{JDURL}/org/eclipse/jetty/websocket/servlet/JettyWebSocketServlet.html#configure(org.eclipse.jetty.websocket.servlet.JettyWebSocketServletFactory)[`JettyWebSocketServlet.configure(JettyWebSocketServletFactory factory)`] is where you put your specific configuration for your WebSocket. -In the example we specify a 10 second idle timeout and register MyEchoSocket with the default JettyWebSocketCreator the WebSocket class we want to be created on Upgrade. - -____ -[NOTE] -It is important that you take in account any firewall or router timeouts -when configuring websockets. Be sure the websocket configuration is -lower than your firewall or router. -____ - -==== Using the JettyWebSocketCreator - -All WebSocket's are created via whatever link:{JDURL}/org/eclipse/jetty/websocket/servlet/JettyWebSocketCreator.html[JettyWebSocketCreator] you have registered with the link:{JDURL}/org/eclipse/jetty/websocket/servlet/JettyWebSocketServletFactory.html[JettyWebSocketServletFactory]. - -By default, the `JettyWebSocketServletFactory` is a simple `JettyWebSocketCreator` capable of creating a single WebSocket object. -Use link:{JDURL}/org/eclipse/jetty/websocket/servlet/JettyWebSocketServletFactory.html#register(java.lang.Class)[`JettyWebSocketCreator.register(Class websocket)`] to tell the `JettyWebSocketServletFactory` which class it should instantiate (make sure it has a default constructor). - -If you have a more complicated creation scenario, you might want to provide your own `JettyWebSocketCreator` that bases the WebSocket it creates off of information present in the `UpgradeRequest` object. - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/examples/MyAdvancedEchoCreator.java[] ----- - -Here we show a `JettyWebSocketCreator` that will utilize the http://tools.ietf.org/html/rfc6455#section-1.9[WebSocket subprotocol] information from request to determine what WebSocket type should be -created. - -[source, java, subs="{sub-order}"] ----- -include::{SRCDIR}/jetty-websocket/websocket-jetty-tests/src/test/java/org/eclipse/jetty/websocket/tests/examples/MyAdvancedEchoServlet.java[] ----- - -When you want a custom `JettyWebSocketCreator`, use link:{JDURL}/org/eclipse/jetty/websocket/servlet/JettyWebSocketServletFactory.html#setCreator(org.eclipse.jetty.websocket.servlet.JettyWebSocketCreator)[`JettyWebSocketServletFactory.setCreator(JettyWebSocketCreator creator)`] and the `JettyWebSocketServletFactory` will use your creator for all incoming Upgrade requests on this servlet. - -Other uses for a `JettyWebSocketCreator`: - -* Controlling the selection of WebSocket subprotocol -* Performing any WebSocket origin you deem important. -* Obtaining the HTTP headers from incoming request -* Obtaining the Servlet HttpSession object (if it exists) -* Specifying a response status code and reason - -If you don't want to accept the upgrade, simply return null from the link:{JDURL}/org/eclipse/jetty/websocket/servlet/JettyWebSocketCreator.html#createWebSocket(org.eclipse.jetty.websocket.api.UpgradeRequest,org.eclipse.jetty.websocket.api.UpgradeResponse)[`JettyWebSocketCreator.createWebSocket(UpgradeRequest req, UpgradeResponse resp)`] method. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/.asciidoctorconfig b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/.asciidoctorconfig deleted file mode 100644 index 308cdcf2991d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/.asciidoctorconfig +++ /dev/null @@ -1,5 +0,0 @@ -// Asciidoctor IDE configuration file. -// See https://github.com/asciidoctor/asciidoctor-intellij-plugin/wiki/Support-project-specific-configurations -:experimental: -:imagesdir: images -:JETTY_HOME: ../../../../../../../jetty-home/target/jetty-home diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/annotations/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/annotations/chapter.adoc deleted file mode 100644 index c4989bfe928a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/annotations/chapter.adoc +++ /dev/null @@ -1,221 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-annotations]] -=== Annotations - -Enable the `annotations` module if your webapp - or any of its third party libraries - uses any of the following: - -* Annotations: -** @Resource -** @Resources -** @PostConstruct -** @PreDestroy -** @DeclaredRoles -** @RunAs -** @MultipartConfig -** @WebServlet -** @WebFilter -** @WebListener -** @WebInitParam -** @ServletSecurity, @HttpConstraint, @HttpMethodConstraint -** @HandlesTypes -* javax.servlet.ServletContainerInitializers -* JSP - - -[[og-annotations-scanning]] -==== Annotation Scanning - -According to more recent versions of the Servlet Specification, the web.xml file can contain the attribute `metadata-complete`. -If this is set to `true`, then _no_ annotation scanning takes place, and your descriptor must contain the equivalent xml statements of any annotations. - -If it is `metadata-complete=false`, or your web.xml predates the inclusion of this attribute, annotation scanning is required to take place. - -To prevent annotation scanning you can use the `WebAppContext.setConfigurationDiscovered(false)` method. -Here's an example context xml file that calls this method: - -[source,xml,subs=verbatim] ----- - - - - <1> - false <2> - ----- -<1> Configures a link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`], which is the Jetty component that represents a standard Servlet web application. -<2> Specifies that scanning should not take place. - -However, despite `metadata-complete=true`, 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. - -We will now look at ways to limit the jars that are scanned. - -[[og-container-include-jar-pattern]] -===== The container classpath - -By default, Jetty will _not_ scan any classes that are on the container's classpath. - -Sometimes, you may have third party libraries on the container's classpath that you need to be scanned. -In this case, use the `org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern` context attribute to define which container jars and class directories to scan. -The value of this attribute is a regular expression. - -Here's an example from a context xml file that includes any jar whose name starts with "foo-" or "bar-", or a directory named "classes": - -[source,xml,subs=verbatim] ----- - - - - <1> - <2> - org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern <3> - .*/foo-[^/]*\.jar$|.*/bar-[^/]*\.jar$|.*/classes/.* <4> - - ----- -<1> Configures a link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`], which is the Jetty component that represents a standard Servlet web application. -<2> Specifies a context attribute. -<3> Specifies the name of the context attribute. -<4> Specifies the value of the context attribute. - -Note that the order of the patterns defines the ordering of the scanning of the jars or class directories. - -[[og-web-inf-include-jar-pattern]] -===== The webapp classpath - -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 jar files that you know do not contain any annotations, you can significantly speed up deployment by omitting them from scanning. -However, be careful if your webapp uses a `ServletContainerInitializer` with an `@HandlesTypes` annotation that you don't exclude jars that contain classes matching the annotation. - -Use the `org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern` context attribute to define a regular expression for jars and class directories to select for scanning. - -Here's an example of a context xml file that sets a pattern that matches any jar on the webapp's classpath that starts with `spring-`: - -[source,xml,subs=verbatim] ----- - - - - <1> - <2> - org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern <3> - .*/spring-[^/]*\.jar$ <4> - - ----- -<1> Configures a link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`], which is the Jetty component that represents a standard Servlet web application. -<2> Specifies a context attribute. -<3> Specifies the name of the context attribute. -<4> Specifies the value of the context attribute. - -===== Multi-threading - -By default Jetty performs annotation scanning in a multi-threaded manner in order to complete it in the minimum amount of time. - -If you don't want multi-threaded scanning, you can configure Jetty to revert to single-threaded scanning. -There are several options to configure this: - -1. Set the context attribute `org.eclipse.jetty.annotations.multiThreaded` to `false` -2. Set the `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 context attribute `org.eclipse.jetty.annotations.maxWait` -2. Set the `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. - -[[og-annotations-scis]] -==== ServletContainerInitializers - -The http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContainerInitializer.html[javax.servlet.ServletContainerInitializer] class can exist in: the container's classpath, the webapp's `WEB-INF/classes` directory, the webapp's `WEB-INF/lib` jars, or any external extraClasspath that you have configured on the webapp. - -The Servlet Specification does not define any order in which a `ServletContainerInitializer` must be called when the webapp starts. -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. - -===== Exclusions - -By default, as according to the Servlet Specification, all `ServletContainerInitializer` that are discovered are invoked. - -Sometimes, depending on your requirements, you may need to prevent some being called at all. - -In this case, you can define the `org.eclipse.jetty.containerInitializerExclusionPattern` 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 of setting the context attribute in a context xml file: - -[source,xml,subs=verbatim] ----- - - - - <1> - <2> - org.eclipse.jetty.containerInitializerExclusionPattern <3> - com.acme.*|com.corp.SlowContainerInitializer <4> - - ----- -<1> Configures a link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`], which is the Jetty component that represents a standard Servlet web application. -<2> Specifies a context attribute. -<3> Specifies the name of the context attribute. -<4> Specifies the value of the context attribute. - -In this example we exclude *all* `ServletContainerInitializer` instances in the `com.acme package`, and the specific class `com.corp.SlowContainerInitializer`. - -It is possible to use exclusion and ordering together to control `ServletContainerInitializer` invocation - the exclusions will be applied before the ordering. - -===== Ordering - -If you need `ServletContainerInitializer` classes called in a specific order, you can use the 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 `ServletContainerInitializer` classes not explicitly named in the list. - -Here is an example context xml file that ensures the `com.example.PrioritySCI` will be called first, followed by the `com.acme.FooSCI`, then all other SCIs: - -[source,xml,subs=verbatim] ----- - - - - <1> - <2> - org.eclipse.jetty.containerInitializerOrder <3> - org.eclipse.jetty.websocket.javax.server.JavaxWebSocketServletContainerInitializer, com.acme.FooSCI, * <4> - - ----- -<1> Configures a link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`], which is the Jetty component that represents a standard Servlet web application. -<2> Specifies a context attribute. -<3> Specifies the name of the context attribute. -<4> Specifies the value of the context attribute. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/architecture/architecture.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/architecture/architecture.adoc deleted file mode 100644 index c0de72a7b787..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/architecture/architecture.adoc +++ /dev/null @@ -1,162 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-arch]] -=== Architecture Overview - -[[og-arch-concepts]] -==== Main Concepts - -Jetty is an HTTP server and Servlet Container, and supports deployments of web applications. - -The xref:og-server[Jetty server] listens on one or more network ports using one or more xref:og-protocols[protocol connectors]. - -Clients send HTTP requests for specific URIs, such as `+https://host/store/cart+`. - -The HTTP requests arrive to the connectors through the network; the Jetty server processes the requests and, based on their URIs, forwards them to the appropriate xref:og-deploy[deployed web application]. - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam roundCorner 10 - -scale 1.25 - -cloud Internet as internet -rectangle "Jetty Server" as server -rectangle "HTTP/1.1 Connector" as http -rectangle "HTTP/2 Connector" as http2 -rectangle "WebApp "Store"" as store -rectangle "WebApp "Catalog"" as catalog - -internet -- http -internet -- http2 -http -- server -http2 -- server -server -- store -server -- catalog ----- - -There are three main concepts on which the Jetty standalone server is based: - -* The xref:og-arch-modules[Jetty _module_ system], where Jetty modules provides Jetty features. -* The xref:og-arch-jetty-base[`$JETTY_BASE` directory], that provides a place where you configure which Jetty modules you want to enable, configure the properties of each enabled module, and therefore configure the features you need for your web applications. -* The xref:og-arch-start[Jetty start mechanism], that starts a JVM that runs Jetty with the configuration you specified. - -After installing Jetty, you will want to set up a xref:og-arch-jetty-base[`$JETTY_BASE` directory] where you configure xref:og-arch-modules[Jetty modules]. - -[[og-arch-modules]] -==== Jetty Modules - -The Jetty standalone server is made of Java components that are assembled together, configured and started to provide different features. - -A Jetty _module_ provides one or more components that work together to provide typically one feature, although they may provide more than one feature. - -A Jetty module is nothing more than Jetty components assembled together like you would do using Java APIs, just done in a declarative way using configuration files. -What you can do in Java code to assemble Jetty components can be done using Jetty modules. - -A Jetty module may be dependent on other Jetty modules: for example, the `http` Jetty module depends on the `server` Jetty module which in turn depends on the `threadpool` and `logging` Jetty modules. - -Every feature in a Jetty server is enabled by enabling the corresponding Jetty module(s). - -For example, if you enable only the `http` Jetty module, then your Jetty standalone server will only be able to listen to a network port for clear-text HTTP requests. -It will not be able to process secure HTTP (i.e. `https`) requests, it will not be able to process WebSocket, or HTTP/2, or HTTP/3 or any other protocol because the correspondent modules have not been enabled. - -You can even start a Jetty server _without_ listening on a network port -- for example because you have enabled a custom module you wrote that provides the features you need. - -This allows the Jetty standalone server to be as small as necessary: modules that are not enabled are not loaded, don't waste memory, and you don't risk a client using a module that you did not know was even there. - -For more detailed information about the Jetty module system, see xref:og-modules[this section]. - -[[og-arch-jetty-base]] -==== `$JETTY_HOME` and `$JETTY_BASE` - -Instead of managing multiple Jetty distributions out of many locations, it is possible to maintain a separation between the binary installation of the standalone Jetty, known as `$JETTY_HOME`, and the customizations for your specific environment(s), known as `$JETTY_BASE`. - -This separation between the binary installation directory and the specific configuration directory allows managing multiple, different, server configurations, and allows for quick, drop-in upgrades of Jetty. - -There should always only be *one* `$JETTY_HOME` (per version of Jetty), but there can be many `$JETTY_BASE` directories that reference it. - -This separation between `$JETTY_HOME` and `$JETTY_BASE` allows Jetty upgrades without affecting your web applications. -`$JETTY_HOME` contains the Jetty runtime and libraries and the default configuration, while a `$JETTY_BASE` contains your web applications and any override of the default configuration. - -For example, with the `$JETTY_HOME` installation the default value for the network port for clear-text HTTP is `8080`. -However, you may want that port to be `6060`, because xref:og-protocols-proxy[Jetty is behind a load balancer] that is configured to forward to the backend on port `6060`. -In this case, you configure the clear-text HTTP port in `$JETTY_BASE`, not in `$JETTY_HOME`. -When you upgrade Jetty, you will upgrade only the files in `$JETTY_HOME`, and all the configuration in `$JETTY_BASE` will remain unchanged, keeping your clear-text HTTP port at `6060`. - -Installing the Jetty runtime and libraries in `$JETTY_HOME` also allows you to leverage file system permissions: `$JETTY_HOME` may be owned by an administrator user (so that only administrators can upgrade it), while `$JETTY_BASE` directories may be owned by a less privileged user. - -If you had changed the default configuration in `$JETTY_HOME`, when you upgrade Jetty, say from version `10.0.0` to version `10.0.1`, your changes would be lost. -Maintaining all the changes in `$JETTY_HOME`, and having to reconfigure these with each upgrade results in a massive commitment of time and effort. - -To recap: - -`$JETTY_HOME`:: -This is the location for the Jetty binaries. -`$JETTY_BASE`:: -This is the location for your configurations and customizations to the Jetty binaries. - -[[og-arch-start]] -==== Start Mechanism - -The Jetty start mechanism provides two features: - -* The mean to configure your `$JETTY_BASE` by enabling the desired modules, and to display the configuration of your `$JETTY_BASE`. -* The mean to start Jetty itself, by starting a JVM that reads the Jetty configuration in `$JETTY_BASE`, which is then executed to assemble and start the Jetty components. - -The Jetty start mechanism is invoked by executing `$JETTY_HOME/start.jar` from within your `$JETTY_BASE`, and you can think of it as the Jetty command line program, similar to many Unix/Windows command line programs. - -For example, you can ask for help: - ----- -$ java -jar $JETTY_HOME/start.jar --help ----- - -Or you can list all available modules (or only those with a specific tag): - ----- -# List all the modules. -$ java -jar $JETTY_HOME/start.jar --list-modules=* - -# List all the modules tagged as "demo". -$ java -jar $JETTY_HOME/start.jar --list-modules=demo ----- - -You can enable a module, for example the `http` module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=http ----- - -Once you have one or more module enabled, you can display the current configuration, to verify that the configuration is correct: - ----- -$ java -jar $JETTY_HOME/start.jar --list-config ----- - -You can enable a Jetty demo module, which will deploy a demo web application: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=demo-simple ----- - -Finally, you can start Jetty: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -Read more information at the xref:og-start[Jetty start mechanism section]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/architecture/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/architecture/chapter.adoc deleted file mode 100644 index 31953fcbf64c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/architecture/chapter.adoc +++ /dev/null @@ -1,14 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -include::architecture.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/chapter.adoc deleted file mode 100644 index 77689cd01696..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/chapter.adoc +++ /dev/null @@ -1,28 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-begin]] -=== Getting Started - -If you are new to Eclipse Jetty, read on to download, install, start and deploy web applications to Jetty. - -include::../../../../../../../jetty-home/src/main/resources/README.adoc[tags=quick] - -The following sections will guide you in details about xref:og-begin-download[downloading], xref:og-begin-install[installing] and xref:og-begin-start[starting] Jetty, and xref:og-begin-deploy[deploying] your web applications to Jetty. - -Read the xref:og-arch[Jetty architecture section] for more information about Jetty modules, `$JETTY_HOME`, `$JETTY_BASE` and how to customize and start Jetty. - -include::download.adoc[] -include::install.adoc[] -include::start.adoc[] -include::deploy.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/deploy.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/deploy.adoc deleted file mode 100644 index 63e5977e3154..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/deploy.adoc +++ /dev/null @@ -1,107 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-begin-deploy]] -==== Deploying Web Applications - -For the purpose of deploying web applications to Jetty, there are two types of resources that can be deployed: - -* Standard Web Application Archives, in the form of `+*.war+` files or web application directories, defined by the Servlet specification. -Their deployment is described in xref:og-begin-deploy-war[this section]. -* Jetty context XML files, that allow you to customize the deployment of standard web applications, and also allow you use Jetty components, and possibly custom components written by you, to assemble your web applications. -Their deployment is described in xref:og-deploy[this section]. - -[[og-begin-deploy-war]] -===== Deploying +*.war+ Files - -A standard Servlet web application is packaged in either a `+*.war+` file or in a directory with the structure of a `+*.war+` file. - -[NOTE] -==== -Recall that the structure of a `+*.war+` file is as follows: - -[source,subs=verbatim] ----- -mywebapp.war -├── index.html <1> -└── WEB-INF <2> - ├── classes/ <3> - ├── lib/ <4> - └── web.xml <5> ----- -<1> Publicly accessible resources such as `+*.html+`, `+*.jsp+`, `+*.css+`, `+*.js+` files, etc. are placed in `+*.war+` or in sub-directories of the `+*.war+`. -<2> `WEB-INF` is a special directory used to store anything related to the web application that must not be publicly accessible, but may be accessed by other resources. -<3> `WEB-INF/classes` stores the web application compiled `+*.class+` files -<4> `WEB-INF/lib` stores the web application `+*.jar+` files -<5> `WEB-INF/web.xml` is the web application deployment descriptor defines the components and the configuration of your web application. -==== - -To deploy a standard web application, you need to enable the `deploy` module (see the `deploy` module complete definition xref:og-module-deploy[here]). - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=deploy ----- - -[source,options=nowrap] ----- -include::jetty[setupArgs="--add-module=http",args="--add-module=deploy"] ----- - -The `deploy` module creates the `$JETTY_BASE/webapps` directory, the directory where `+*.war+` files or web application directories should be copied so that Jetty can deploy them. - -[NOTE] -==== -The `deploy` module only provides the feature of deploying web applications. - -Whether these web applications are served via clear-text HTTP/1.1, or secure HTTP/1.1, or secure HTTP/2, or HTTP/3 (or even all of these protocols) depends on whether the correspondent Jetty modules have been enabled. -Refer to the xref:og-protocols[section about protocols] for further information. -==== - -Now you need to copy a web application to the `$JETTY_BASE/webapps` directory, and you can use one of the demos shipped with Jetty: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=demo-simple ----- - -The `$JETTY_BASE` directory is now: - ----- -$JETTY_BASE -├── resources -│ └── jetty-logging.properties -├── start.d -│ ├── deploy.ini -│ └── http.ini -└── webapps - └── demo-simple.war ----- - -Now start Jetty: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=http,deploy,demo-simple",highlight="WebAppContext"] ----- - -Note the highlighted line that logs the deployment of `demo-simple.war`. - -Now you can access the web application by pointing your browser to `+http://localhost:8080/demo-simple+`. - -[[og-begin-deploy-war-advanced]] -===== Advanced Deployment - -If you want to customize the deployment of your web application, for example by specifying a `contextPath` different from the file/directory name, or by specifying JNDI entries, or by specifying virtual hosts, etc. read xref:og-deploy[this section]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/download.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/download.adoc deleted file mode 100644 index 33d56a7c20f5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/download.adoc +++ /dev/null @@ -1,20 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-begin-download]] -==== Downloading Jetty - -The Eclipse Jetty distribution is available for download from link:https://jetty.org/download.html[] - -The Eclipse Jetty distribution is available in both `zip` and `gzip` formats; download the one most appropriate for your system, typically `zip` for Windows and `gzip` for other operating systems. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/install.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/install.adoc deleted file mode 100644 index cc7f14417e81..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/install.adoc +++ /dev/null @@ -1,29 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-begin-install]] -==== Installing Jetty - -After the download, unpacking Eclipse Jetty will extract the files into a directory called `jetty-home-VERSION`, where `VERSION` is the version that you downloaded, for example `{version}`, so that the directory is called `jetty-home-{version}`. - -Unpack Eclipse Jetty compressed file in a convenient location, for example under `/opt`. - -CAUTION: For Windows users, you should unpack Jetty to a path that does not contain spaces. - -The rest of the instructions in this documentation will refer to this location as `$JETTY_HOME`, or `${jetty.home}`. - -IMPORTANT: It is important that *only* stable release versions are used in production environments. -Versions that have been deprecated or are released as Milestones (M), Alpha, Beta or Release Candidates (RC) are *not* suitable for production as they may contain security flaws or incomplete/non-functioning feature sets. - -If you are new to Jetty, you should read the xref:og-arch[Jetty architecture section] to become familiar with the terms used in this documentation. -Otherwise, you can jump to the xref:og-begin-start[section on starting Jetty]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/start.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/start.adoc deleted file mode 100644 index 97717d956700..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/begin/start.adoc +++ /dev/null @@ -1,134 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-begin-start]] -==== Starting Jetty - -Eclipse Jetty as a standalone server has no graphical user interface, so configuring and running the server is done from the command line. - -Recall from the xref:og-arch[architecture section] that Jetty is based on xref:og-modules[modules], that provides features, and on xref:og-arch-jetty-base[`$JETTY_BASE`], the place where you configure which module (and therefore which feature) you want to enable, and where you configure module parameters. - -Jetty is started by executing `$JETTY_HOME/start.jar` from within a `$JETTY_BASE` directory, so first we need to create a `$JETTY_BASE`: - ----- -$ JETTY_BASE=/path/to/jetty.base -$ cd $JETTY_BASE ----- - -If you try to start Jetty from an empty `$JETTY_BASE` you get: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,options=nowrap] ----- -include::jetty[] ----- - -Jetty exited complaining that there are no modules enabled, since the `$JETTY_BASE` you just created is empty and therefore there is no configuration to read to assemble the Jetty server. - -However, it shows that `start.jar` takes parameters, whose details can be found in xref:og-start[this section]. - -You can explore what modules are available out of the box via: - ----- -$ java -jar $JETTY_HOME/start.jar --list-modules=* ----- - -Let's try to enable the `http` module (see also xref:og-protocols-http[this section] for additional information): - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=http ----- - -[source,options=nowrap] ----- -include::jetty[args="--add-module=http"] ----- - -Now you can start Jetty: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[args="--module=http",highlight="(\{.*:8080})"] ----- - -Note how Jetty is listening on port `8080` for clear-text HTTP/1.1 connections. - -After having enabled the `http` module, the `$JETTY_BASE` directory looks like this: - -[source,subs=verbatim] ----- -JETTY_BASE -├── resources -│ └── jetty-logging.properties <1> -└── start.d <2> - └── http.ini <3> ----- - -<1> The `resources/jetty-logging.properties` file has been created because the `http` modules depends on the `server` module, which in turn depends on the `logging` module; the `logging` module created this file that can be configured to control the server logging level. -<2> The `start.d/` directory contains the configuration files for the modules. -<3> The `start.d/http.ini` file is the `http` module configuration file, where you can specify values for the `http` module properties. - -In the `http.ini` file you can find the following content (among other content): - -.http.ini -[source,subs=verbatim] ----- ---module=http <1> -# jetty.http.port=8080 <2> -... ----- - -<1> This line enables the `http` module and should not be modified. -<2> This line is commented out and specifies the default value for the module property `jetty.http.port`, which is the network port that listens for clear-text HTTP connections. - -You can change the module property `jetty.http.port` value directly from the command line: - ----- -$ java -jar $JETTY_HOME/start.jar jetty.http.port=9999 ----- - -To make this change persistent, you can edit the `http.ini` file, uncomment the module property `jetty.http.port` and change its value to `9999`: - -.http.ini ----- ---module=http -jetty.http.port=9999 -... ----- - -If you restart Jetty, the new value will be used: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[args="--module=http jetty.http.port=9999",highlight="(\{.*:9999})"] ----- - -Note how Jetty is now listening on port `9999` for clear-text HTTP/1.1 connections. - -NOTE: If you want to enable support for different protocols such as secure HTTP/1.1 or HTTP/2 or HTTP/3, or configure Jetty behind a load balancer, read xref:og-protocols[this section]. - -The Jetty server is now up and running, but it has no web applications deployed, so it just replies with `404 Not Found` to every request. -It is time to xref:og-begin-deploy[deploy your web applications] to Jetty. - -For more detailed information about the Jetty start mechanism, you can read the xref:og-arch-start[Jetty start mechanism] section. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/contexts/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/contexts/chapter.adoc deleted file mode 100644 index d19f827e6295..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/contexts/chapter.adoc +++ /dev/null @@ -1,18 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-contexts]] -=== Configuring Jetty Context XML Files - -TODO -// TODO: add here from old_docs/contexts and old_docs/extras diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/chapter.adoc deleted file mode 100644 index 62e25a9890c0..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/chapter.adoc +++ /dev/null @@ -1,39 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-deploy]] -=== Web Application Deployment - -Most of the times you want to be able to customize the deployment of your web applications, for example by changing the `contextPath`, or by adding JNDI entries, or by configuring virtual hosts, etc. - -The customization is performed by the xref:og-module-deploy[`deploy` module] by processing xref:og-deploy-jetty[Jetty context XML files]. - -The `deploy` module contains the `DeploymentManager` component that scans the `$JETTY_BASE/webapps` directory for changes, following the deployment rules described in xref:og-deploy-rules[this section]. - -include::deploy-hot-static.adoc[] -include::deploy-rules.adoc[] -include::deploy-jetty.adoc[] -include::deploy-jndi.adoc[] -include::deploy-virtual-hosts.adoc[] -include::deploy-extract-war.adoc[] -include::deploy-override-webxml.adoc[] - -// TODO: move this section to its own file -// TODO: configuring from the Jetty context XML file happens before web.xml -// What about jetty-web.xml? Can this be specified externally, e.g. WebAppContext.setJettyWebXml() ? -[[og-deploy-init-params]] -==== Configuring ``init-param``s - -TODO - -// TODO: see old_docs/deploying diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-extract-war.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-extract-war.adoc deleted file mode 100644 index d2d656298b93..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-extract-war.adoc +++ /dev/null @@ -1,34 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-deploy-extract-war]] -==== Configuring `+*.war+` File Extraction - -By default, `+*.war+` files are uncompressed and its content extracted in a temporary directory. -// TODO: reference the `work` module and how it works, perhaps in a section about the `deploy` module? -The web application resources are served by Jetty from the files extracted in the temporary directory, not from the files within the `+*.war+` file, for performance reasons. - -If you do not want Jetty to extract the `+*.war+` files, you can disable this feature, for example: - -.mywebapp.xml -[source,xml,highlight=8] ----- - - - - - /mywebapp - /opt/webapps/mywebapp.war - false - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-hot-static.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-hot-static.adoc deleted file mode 100644 index 1d83494f87f7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-hot-static.adoc +++ /dev/null @@ -1,38 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-deploy-hot-static]] -==== Hot vs Static Deployment - -The `DeploymentManager` scans the `$JETTY_BASE/webapps` directory for changes every `N` seconds, where `N` is configured via the `jetty.deploy.scanInterval` property. - -By default, the scan interval is `1` second, which means that _hot_ deployment is enabled: if a file is added/changed/removed from the `$JETTY_BASE/webapps` directory, the `DeploymentManager` will notice the change and respectively deploy/redeploy/undeploy the web application. - -Setting the scan interval to `0` means that _static_ deployment is enabled, and the `DeploymentManager` will not scan the `$JETTY_BASE/webapps` directory for changes. -This means that to deploy/redeploy/undeploy a web application you will need to stop and restart Jetty. - -The following command line disables _hot_ deployment by specifying the `jetty.deploy.scanInterval` property on the command line, and therefore only for this particular run: - ----- -$ java -jar $JETTY_HOME/start.jar jetty.deploy.scanInterval=0 ----- - -To make _static_ deployment persistent, you need to edit the `deploy` module configuration file, `$JETTY_BASE/start.d/deploy.ini`, uncomment the module property `jetty.deploy.scanInterval` and change its value to `0`: - -.deploy.ini -[source,subs=quotes] ----- ---module=deploy -#jetty.deploy.scanInterval=0# -... ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-jetty.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-jetty.adoc deleted file mode 100644 index b0401e2aeb12..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-jetty.adoc +++ /dev/null @@ -1,75 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-deploy-jetty]] -==== Deploying Jetty Context XML Files - -A Jetty context XML file is a xref:og-xml[Jetty XML file] that allows you to customize the deployment of web applications. - -NOTE: Recall that the `DeploymentManager` component of the Jetty `deploy` module xref:og-deploy-rules[gives priority] to Jetty context XML files over `+*.war+` files or directories. - -To deploy a web application using a Jetty context XML file, simply place the file in the `$JETTY_BASE/webapps` directory. - -A simple Jetty context XML file, for example named `wiki.xml` is the following: - -.wiki.xml -[source,xml,subs=verbatim] ----- - - - - <1> - /wiki <2> - /opt/myapps/myapp.war <3> - ----- -<1> Configures a link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`], which is the Jetty component that represents a standard Servlet web application. -<2> Specifies the web application `contextPath`, which may be different from the `+*.war+` file name. -<3> Specifies the file system path of the `+*.war+` file. - -The `$JETTY_BASE` directory would look like this: - ----- -$JETTY_BASE -├── resources -│ └── jetty-logging.properties -├── start.d -│ ├── deploy.ini -│ └── http.ini -└── webapps - └── wiki.xml ----- - -TIP: The `+*.war+` file may be placed anywhere in the file system and does not need to be placed in the `$JETTY_BASE/webapps` directory. - -IMPORTANT: If you place both the Jetty context XML file _and_ the `+*.war+` file in the `$JETTY_BASE/webapps` directory, remember that they must have the same file name, for example `wiki.xml` and `wiki.war`, so that the `DeploymentManager` deploys the web application only once using the Jetty context XML file (and not the `+*.war+` file). - -You can use the features of xref:og-xml[Jetty XML files] to avoid to hard-code file system paths or other configurations in your Jetty context XML files, for example by using system properties: - -.wiki.xml -[source,xml] ----- - - - - - /wiki - /myapp.war - ----- - -Note how the `+*.war+` file path is now obtained by resolving the system property `myapps.dir` that you can specify on the command line when you start Jetty: - ----- -$ java -jar $JETTY_HOME/start.jar -Dmyapps.dir=/opt/myapps ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-jndi.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-jndi.adoc deleted file mode 100644 index 7bbf84aefee5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-jndi.adoc +++ /dev/null @@ -1,54 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-deploy-jndi]] -==== Configuring JNDI Entries - -A web application may _reference_ a JNDI entry, such as a JDBC `DataSource` from the web application `web.xml` file. -The JNDI entry must be _defined_ in a xref:og-jndi-xml[Jetty XML file], for example a context XML like so: - -.mywebapp.xml -[source,xml,subs=normal] ----- - - - - - /mywebapp - /opt/webapps/mywebapp.war -#   - - jdbc/myds - - - jdbc:mysql://localhost:3306/databasename - user - password - - - # - ----- - -For more information and examples on how to use JNDI in Jetty, refer to the xref:og-jndi[JNDI] feature section. - -[IMPORTANT] -==== -Class `com.mysql.cj.jdbc.MysqlConnectionPoolDataSource` is present in the MySQL JDBC driver file, `mysql-connector-java-.jar`, which must be available on the server's classpath . - -If the class is instead present _within_ the web application, then the JNDI entry must be declared in a `WEB-INF/jetty-env.xml` file - see the xref:og-jndi[JNDI] feature section for more information and examples. - -==== -// TODO: add a link to reference the section about how -// to add a JDBC driver jar to the server classpath. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-override-webxml.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-override-webxml.adoc deleted file mode 100644 index 2e125cb976cc..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-override-webxml.adoc +++ /dev/null @@ -1,55 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-deploy-jetty-override-web-xml]] -==== Overriding `web.xml` - -You can configure an additional `web.xml` that complements the `web.xml` file that is present in the web application `+*.war+` file. -This additional `web.xml` is processed _after_ the `+*.war+` file `web.xml`. -This allows you to add host specific configuration or server specific configuration without having to extract the web application `web.xml`, modify it, and repackage it in the `+*.war+` file. - -.mywebapp.xml -[source,xml,highlight=8] ----- - - - - - /mywebapp - /opt/webapps/mywebapp.war - /opt/webapps/mywebapp-web.xml - ----- - -The format of the additional `web.xml` is exactly the same as a standard `web.xml` file, for example: - -.mywebapp-web.xml -[source,xml,linenums,highlight=10-11] ----- - - - - my-servlet - - host - 192.168.0.13 - - - ----- - -In the example above, you configured the `my-servlet` Servlet (defined in the web application `web.xml`), adding a host specific `init-param` with the IP address of the host. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-rules.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-rules.adoc deleted file mode 100644 index 3c4d2e4d8c27..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-rules.adoc +++ /dev/null @@ -1,38 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-deploy-rules]] -==== Deployment Rules - -_Adding_ a `+*.war+` file, a `+*.war+` directory, a Jetty context XML file or a normal directory to `$JETTY_BASE/webapps` causes the `DeploymentManager` to deploy the new web application. - -_Updating_ a `+*.war+` file or a Jetty context XML file causes the `DeploymentManager` to redeploy the web application, which means that the Jetty context component representing the web application is stopped, then reconfigured, and then restarted. - -_Removing_ a `+*.war+` file, a `+*.war+` directory, a Jetty context XML file or a normal directory from `$JETTY_BASE/webapps` causes the `DeploymentManager` to undeploy the web application, which means that the Jetty context component representing the web application is stopped and removed from the Jetty server. - -When a file or directory is added to `$JETTY_BASE/webapps`, the `DeploymentManager` derives the web application `contextPath` from the file or directory name, with the following rules: - -* If the directory name is, for example, `mywebapp/`, it is deployed as a standard web application if it contains a `WEB-INF/` subdirectory, otherwise it is deployed as a web application of static content. -The `contextPath` would be `/mywebapp` (that is, the web application is reachable at `+http://localhost:8080/mywebapp/+`). -* If the directory name is `ROOT`, case insensitive, the `contextPath` is `/` (that is, the web application is reachable at `+http://localhost:8080/+`). -* If the directory name ends with `.d`, for example `config.d/`, it is ignored, although it may be referenced to configure other web applications (for example to store common files). -* If the `+*.war+` file name is, for example, `mywebapp.war`, it is deployed as a standard web application with the context path `/mywebapp` (that is, the web application is reachable at `+http://localhost:8080/mywebapp/+`). -* If the file name is `ROOT.war`, case insensitive, the `contextPath` is `/` (that is, the web application is reachable at `+http://localhost:8080/+`). -* If both the `mywebapp.war` file and the `mywebapp/` directory exist, only the file is deployed. -This allows the directory with the same name to be the `+*.war+` file unpack location and avoid that the web application is deployed twice. -* A xref:og-deploy-jetty[Jetty context XML file] named `mywebapp.xml` is deployed as a web application by processing the directives contained in the XML file itself, which must set the `contextPath`. -* If both `mywebapp.xml` and `mywebapp.war` exist, only the XML file is deployed. -This allows the XML file to reference the `+*.war+` file and avoid that the web application is deployed twice. - -// TODO: add section about the work directory from -// old_docs/contexts/temporary-directories.adoc diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-virtual-hosts.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-virtual-hosts.adoc deleted file mode 100644 index b561a6ac2811..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/deploy/deploy-virtual-hosts.adoc +++ /dev/null @@ -1,186 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-deploy-virtual-hosts]] -==== Configuring Virtual Hosts - -A _virtual host_ is an internet domain name, registered in the Domain Name Server (DNS), for an IP address such that multiple virtual hosts will resolve to the same IP address of a single server instance. - -If you have multiple web applications deployed on the same Jetty server, by using virtual hosts you will be able to target a specific web application. - -For example, you may have a web application for your business and a web application for your hobbies , both deployed in the same Jetty server. -By using virtual hosts, you will be able to have the first web application available at `+http://domain.biz/+`, and the second web application available at `+http://hobby.net/+`. - -Another typical case is when you want to use different subdomains for different web application, for example a project website is at `+http://project.org/+` and the project documentation is at `+http://docs.project.org+`. - -Virtual hosts can be used with any context that is a subclass of link:{javadoc-url}/org/eclipse/jetty/server/handler/ContextHandler.html[ContextHandler]. - -[[og-deploy-virtual-hosts-names]] -===== Virtual Host Names - -Jetty supports the following variants to be specified as virtual host names: - -`www.hostname.com`:: -A fully qualified domain name. It is important to list all variants as a site may receive traffic for both `www.hostname.com` and `hostname.com`. - -`*.hostname.com`:: -A wildcard domain name which will match only one level of arbitrary subdomains. -*.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 set as a virtual host to indicate that a web application should handle requests received on the network interface with that IP address for protocols that do not indicate a host name such as HTTP/0.9 or HTTP/1.0. - -`@ConnectorName`:: -A Jetty server `Connector` name to indicate that a web application should handle requests received on the server `Connector` with that name, and therefore received on a specific socket address (either an IP port for `ServerConnector`, or a Unix-Domain path for `UnixDomainServerConnector`). -A server `Connector` name can be set via link:{javadoc-url}/org/eclipse/jetty/server/AbstractConnector.html#setName(java.lang.String)[]. - -`www.√integral.com`:: -Non-ASCII and https://en.wikipedia.org/wiki/Internationalized_domain_name[IDN] domain names can be set as virtual hosts using https://en.wikipedia.org/wiki/Punycode[Puny Code] equivalents that may be obtained from a https://www.punycoder.com/[Punycode/IDN converters]. -For example if the non-ASCII domain name `www.√integral.com` is given to a browser, then the browser 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. - -[[og-deploy-virtual-hosts-config]] -===== Virtual Hosts Configuration - -If you have a web application `mywebapp.war` you can configure its virtual hosts in this way: - -[source,xml] ----- - - - - - /mywebapp - /opt/webapps/mywebapp.war - - - mywebapp.com - www.mywebapp.com - mywebapp.net - www.mywebapp.net - - - ----- - -Your web application will be available at: - -* `+http://mywebapp.com/mywebapp+` -* `+http://www.mywebapp.com/mywebapp+` -* `+http://mywebapp.net/mywebapp+` -* `+http://www.mywebapp.net/mywebapp+` - -[NOTE] -==== -You configured the `contextPath` of your web application to `/mywebapp`. - -As such, a request to `+http://mywebapp.com/other+` will not match your web application because the `contextPath` does not match. - -Likewise, a request to `+http://other.com/mywebapp+` will not match your web application because the virtual host does not match. -==== - -[[og-deploy-virtual-hosts-same-context]] -===== Same Context Path, Different Virtual Hosts - -If you want to deploy different web applications to the same context path, typically the root context path `/`, you must use virtual hosts to differentiate among web applications. - -You have `domain.war` that you want to deploy at `+http://domain.biz/+` and `hobby.war` that you want to deploy at `+http://hobby.net+`. - -To achieve this, you simply use the same context path of `/` for each of your webapps, while specifying different virtual hosts for each of your webapps: - -.domain.xml -[source,xml] ----- - - - - - / - /opt/webapps/domain.war - - - domain.biz - - - ----- - -.hobby.xml -[source,xml] ----- - - - - - / - /opt/webapps/hobby.war - - - hobby.net - - - ----- - -[[og-deploy-virtual-hosts-port]] -===== Different Port, Different Web Application - -Sometimes it is required to serve different web applications from different socket addresses (either different IP ports, or different Unix-Domain paths), and therefore from different server ``Connector``s. - -For example, you want requests to `+http://localhost:8080/+` to be served by one web application, but requests to `+http://localhost:9090/+` to be served by another web application. - -This configuration may be useful when Jetty sits behind a load balancer. - -In this case, you want to xref:og-protocols[configure multiple connectors], each with a different name, and then reference the connector name in the web application virtual host configuration: - -.domain.xml -[source,xml,highlight=10] ----- - - - - - / - /opt/webapps/domain.war - - - @port8080 - - - ----- - -.hobby.xml -[source,xml,highlight=10] ----- - - - - - / - /opt/webapps/hobby.war - - - @port9090 - - - ----- - -[NOTE] -==== -Web application `domain.war` has a virtual host of `@port8080`, where `port8080` is the name of a Jetty connector. - -Likewise, web application `hobby.war` has a virtual host of `@port9090`, where `port9090` is the name of another Jetty connector. - -See xref:og-protocols[this section] for further information about how to configure connectors. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/features.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/features.adoc deleted file mode 100644 index a44ca872f212..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/features.adoc +++ /dev/null @@ -1,37 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-features]] -=== Eclipse Jetty Features - -If you know Eclipse Jetty already, jump to a feature: - -Protocols:: -* xref:og-protocols-http[HTTP/1.1 Support] -* xref:og-protocols-http2[HTTP/2 Support] -* xref:og-protocols-http3[HTTP/3 Support] -* xref:og-protocols-websocket[WebSocket Support] - -Technologies:: -* xref:og-annotations[Servlet Annotations] -* xref:og-jaas[JAAS] -* xref:og-jndi[JNDI] -* xref:og-jsp[JSP] -* xref:og-jmx[JMX Monitoring & Management] - -Clustering:: -* xref:og-sessions[HTTP Session Caching and Clustering] - -Performance:: -* xref:og-server-threadpool-virtual[Virtual Threads] -* xref:og-quickstart[Faster Web Application Deployment] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/howtos.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/howtos.adoc deleted file mode 100644 index 2af1d4482849..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/howtos.adoc +++ /dev/null @@ -1,25 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-howtos]] -=== Eclipse Jetty How-Tos - -* xref:og-protocols-http[Configure Clear-Text HTTP/1.1] -* xref:og-protocols-https[Configure Secure HTTP/1.1 (https)] -* xref:og-protocols-http2c[Configure Clear-Text HTTP/2] -* xref:og-protocols-http2s[Configure Secure HTTP/2] -* xref:og-protocols-http3[Configure HTTP/3] -* xref:og-protocols-proxy[Configure Jetty Behind a Load Balancer or Reverse Proxy] -* xref:og-server-logging[Configure Jetty Logging] -* xref:og-server-threadpool[Configure Jetty Thread Pool and Virtual Threads] -* xref:og-troubleshooting[Troubleshooting] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/images/jmc-server-dump.png b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/images/jmc-server-dump.png deleted file mode 100644 index 33cd92938cbe..000000000000 Binary files a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/images/jmc-server-dump.png and /dev/null differ diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/index-docinfo.html b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/index-docinfo.html deleted file mode 100644 index 006245974c73..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/index-docinfo.html +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/index.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/index.adoc deleted file mode 100644 index f85f21ad49d2..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/index.adoc +++ /dev/null @@ -1,41 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -:doctitle: link:https://jetty.org[Eclipse Jetty]: Operations Guide -:toc-title: Operations Guide -:idprefix: og- -:docinfo: private-head - -include::../config.adoc[] -include::.asciidoctorconfig[] -include::introduction.adoc[] -include::begin/chapter.adoc[] -include::features.adoc[] -include::howtos.adoc[] -include::architecture/chapter.adoc[] -include::start/chapter.adoc[] -include::modules/chapter.adoc[] -include::deploy/chapter.adoc[] -include::server/chapter.adoc[] -include::protocols/chapter.adoc[] -include::keystore/chapter.adoc[] -include::sessions/chapter.adoc[] -include::quickstart/chapter.adoc[] -include::annotations/chapter.adoc[] -include::jsp/chapter.adoc[] -include::jndi/chapter.adoc[] -include::jaas/chapter.adoc[] -include::jaspi/chapter.adoc[] -include::jmx/chapter.adoc[] -include::troubleshooting/chapter.adoc[] -include::xml/chapter.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/introduction.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/introduction.adoc deleted file mode 100644 index 961e133278fe..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/introduction.adoc +++ /dev/null @@ -1,17 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-intro]] -== Eclipse Jetty Operations Guide - -The Eclipse Jetty Operations Guide targets sysops, devops, and developers who want to install Eclipse Jetty as a standalone server to deploy web applications. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jaas/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jaas/chapter.adoc deleted file mode 100644 index 5e134b3fe699..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jaas/chapter.adoc +++ /dev/null @@ -1,334 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-jaas]] -=== JAAS - -JAAS implements a Java version of the standard Pluggable Authentication Module (PAM) framework. - -JAAS can be used for two purposes: - -* for authentication of users, to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet -* for authorization of users to ensure they have the access control rights (permissions) required to do the actions performed - -JAAS authentication is performed in a pluggable fashion. -This permits applications to remain independent from underlying authentication technologies. -New or updated authentication technologies can be plugged under an application without requiring modifications to the application itself. - -See Java Authentication and Authorization Service (JAAS) link:http://java.sun.com/javase/7/docs/technotes/guides/security/jaas/JAASRefGuide.html[Reference Guide] for more information about JAAS. - -The Jetty JAAS support aims to dictate as little as possible whilst providing a sufficiently flexible infrastructure to allow users to drop either one of the xref:og-jaas-loginmodules[JAAS Login Modules that ships with Jetty], or their -own custom link:https://docs.oracle.com/javase/7/docs/api/javax/security/auth/spi/LoginModule.html[LoginModule]s. - -[[og-jaas-configuration]] -==== Configuration - -[[og-jaas-module]] -===== The `jaas` module - -Enable the `jaas` module: - ----- -include::{JETTY_HOME}/modules/jaas.mod[] ----- - -The configurable items in the resulting `$jetty.base/start.d/jaas.ini` file are: - -jetty.jaas.login.conf:: -This is the location of the file that will be referenced by the system property `java.security.auth.login.config`: Jetty sets this system property for you based on the value of this property. -The value of this property is assumed to be _relative to ``$JETTY_BASE``_. -The default value is `etc/login.conf`, which resolves to `$JETTY_BASE/etc/login.conf`. -If you don't want to put your login module configuration file here, you can change this property to point to where it is. - -See more about the contents of this file in the xref:og-jaas-loginconf[Configuring JAAS] section. - -[[og-jaas-webapp]] -===== Configure the webapp for JAAS - -The `` in `web.xml` will be used to identify the `org.eclipse.jetty.jaas.JAASLoginService` declaration that integrates JAAS with Jetty. - -For example, this `web.xml` contains a realm called `Test JAAS Realm`: - -[source,xml,subs=verbatim] ----- - - FORM - Test JAAS Realm - - /login/login - /login/error - - ----- -<1> The name of the realm, which must be _identical_ to the name of an `org.eclipse.jetty.jaas.JAASLoginService` declaration. - -We now need to declare an `org.eclipse.jetty.jaas.JAASLoginService` that references the realm name of `Test JAAS Realm`. -Here's an example of a suitable XML snippet: - -[source,xml,subs=verbatim] ----- - - Test JAAS Realm - xyz - ----- -<1> The name is the _same_ as that declared in the `` in `web.xml`. -<2> The name that identifies a set of `javax.security.auth.spi.LoginModule` configurations that comprise the xref:og-jaas-loginconf[JAAS config file] identified in the `jetty.jaas.login.conf` property of the xref:og-jaas-module[`jaas` module]. - -The `org.eclipse.jetty.jaas.JAASLoginService` can be declared in a couple of different places, pick whichever suits your purposes best: - -* If you have more than one webapp that you would like to use the same security infrastructure, then you can declare your `org.eclipse.jetty.jaas.JAASLoginService` as a bean that is added to the `org.eclipse.jetty.server.Server`. -The file in which you declare this needs to be on Jetty's execution path. -The recommended procedure is to create a file in your `$jetty.base/etc` directory and then ensure it is on the classpath either by adding it to the Jetty xref:og-start[start command line], or more conveniently to a xref:og-modules-custom[custom module]. -+ -Here's an example of this type of XML file: -+ -[source,xml] ----- - - - - - - - Test JAAS Realm - xyz - - - - ----- - -* Alternatively, if you want to use JAAS with a specific webapp only, you declare your `org.eclipse.jetty.jaas.JAASLoginService` in a context XLM file specific to that webapp: -+ -[source,xml] ----- - - - - - - - - Test JAAS Realm - xyz - - - - - ----- - -[[og-jaas-loginconf]] -===== Configure JAAS - -We now need to setup the contents of the file we specified as the `jetty.jaas.login.conf` property when we xref:og-jaas-module[configured the `jaas` module]. -Refer to the link:https://docs.oracle.com/javase/7/docs/api/javax/security/auth/login/Configuration.html[syntax rules] of this file for a full description. - -Remembering the example we set up xref:og-jaas-webapp[previously], the contents of the `$jetty.base/etc/login.conf` file could look as follows: - -[source,subs=verbatim] ----- -xyz { <1> - com.acme.SomeLoginModule required debug=true; <2> - com.other.OtherLoginModule optional; <3> -}; ----- -<1> The name of the configuration _exactly_ as specified in your `org.eclipse.jetty.jaas.JAASLoginService` declaration. -<2> The first `LoginModule` declaration, containing the classname of the `LoginModule` and its configuration properties. -<3> A second `LoginModule` declaration. -You can provide as many `LoginModule` alternatives as you like, with a minimum of one. -Refer to the link:https://docs.oracle.com/javase/7/docs/api/javax/security/auth/login/Configuration.html[JAAS documentation] for more information on the standard configuration properties, and how JAAS interprets this file. - -[[og-jaas-loginmodules]] -==== Provided LoginModules - -* link:{javadoc-url}/org/eclipse/jetty/jaas/spi/JDBCLoginModule.html[`org.eclipse.jetty.jaas.spi.JDBCLoginModule`] -* link:{javadoc-url}/org/eclipse/jetty/jaas/spi/PropertyFileLoginModule.html[`org.eclipse.jetty.jaas.spi.PropertyFileLoginModule`] -* link:{javadoc-url}/org/eclipse/jetty/jaas/spi/DataSourceLoginModule.html[`org.eclipse.jetty.jaas.spi.DataSourceLoginModule`] -* link:{javadoc-url}/org/eclipse/jetty/jaas/spi/LdapLoginModule.html[`org.eclipse.jetty.jaas.ldap.LdapLoginModule`] - -[[og-password]] -[NOTE] -==== -Passwords can be stored in clear text, obfuscated or checksummed. -The class link:{javadoc-url}/org/eclipse/jetty/util/security/Password.html[`org.eclipse.jetty.util.security.Password`] should be used to generate all varieties of passwords,the output from which can be put in to property files or entered into database tables. -==== - -===== JDBCLoginModule - -The `org.eclipse.jetty.jaas.spi.JDBCLoginModule` stores user passwords and roles in a database accessed via JDBC calls. -You can configure the JDBC connection information, as well as the names of the table and columns storing the username and credential, and the names of the table and columns storing the roles. - -Here is an example xref:og-jaas-loginconf[login module configuration file] entry for it using an HSQLDB driver: - -[source,subs=verbatim] ----- -jdbc { <1> - org.eclipse.jetty.jaas.spi.JDBCLoginModule required <2><3> - dbUrl="jdbc:hsqldb:." <4> - dbUserName="sa" <5> - dbDriver="org.hsqldb.jdbcDriver" <6> - userTable="myusers" <7> - userField="myuser" <8> - credentialField="mypassword" <9> - userRoleTable="myuserroles" <10> - userRoleUserField="myuser" <11> - userRoleRoleField="myrole"; <12> -}; ----- -<1> The name of the configuration. -<2> The name of the `LoginModule` class. -<3> A standard JAAS flag making successful authentication via this `LoginModule` mandatory. -<4> The JDBC url used to connect to the database. -<5> The name of the JDBC user to use for the connection. -<6> The name of the JDBC Driver class. -<7> The name of the table holding the user authenication information. -<8> The name of the column holding the user name. -<9> The name of the column holding the user credential. -<10> The name of the table holding the user authorization information. -<11> The name of the column holding the user name. -<12> The name of the column holding the user role. - -The properties *7*-*12* are used to format the following queries: - -[source,sql] ----- -select from where =? -select from where =? ----- - -Credential and role information is lazily read from the database when a previously unauthenticated user requests authentication. -Note that this information is _only_ cached for the length of the authenticated session. -When the user logs out or the session expires, the information is flushed from memory. - -Note that passwords can be stored in the database in plain text or encoded formats -- see the note on "Passwords/Credentials" above. - -===== DataSourceLoginModule - -Similar to the `org.eclipse.jetty.jaas.spi.JDBCLoginModule`, but using a `javax.sql.DataSource` to connect to the database instead of a JDBC driver. -The `javax.sql.DataSource` is obtained at runtime by performing a JNDI lookup on `java:comp/env/${dnJNDIName}`. - -A sample login module configuration for this `LoginModule`: - -[source,subs=verbatim] ----- -ds { <1> - org.eclipse.jetty.jaas.spi.DataSourceLoginModule required <2><3> - dbJNDIName="ds" <4> - userTable="myusers" <5> - userField="myuser" <6> - credentialField="mypassword" <7> - userRoleTable="myuserroles" <8> - userRoleUserField="myuser" <9> - userRoleRoleField="myrole"; <10> -}; ----- -<1> The name of the configuration. -<2> The name of the `LoginModule` class. -<3> A standard JAAS flag making successful authentication via this `LoginModule` mandatory. -<4> The JNDI name, relative to `java:comp/env/` to lookup to obtain the `javax.sql.DataSource`. -<5> The name of the table holding the user authenication information. -<6> The name of the column holding the user name. -<7> The name of the column holding the user credential. -<8> The name of the table holding the user authorization information. -<9> The name of the column holding the user name. -<10> The name of the column holding the user role. - -===== PropertyFileLoginModule - -With this login module implementation, the authentication and role information is read from a property file. - -[source,subs=verbatim] ----- -props { <1> - org.eclipse.jetty.jaas.spi.PropertyFileLoginModule required <2><3> - file="/somewhere/somefile.props"; <4> -}; ----- -<1> The name of the configuration. -<2> The name of the `LoginModule` class. -<3> A standard JAAS flag making successful authentication via this `LoginModule` mandatory. -<4> The location of a properties file containing the authentication and authorization information. - -The property file must be of the format: - -[source,text,subs=verbatim] ----- -: [, ...] ----- - -Here's an example: - ----- -fred: OBF:1xmk1w261u9r1w1c1xmq,user,admin -harry: changeme,user,developer -tom: MD5:164c88b302622e17050af52c89945d44,user -dick: CRYPT:adpexzg3FUZAk,admin ----- - -The contents of the file are fully read in and cached in memory the first time a user requests authentication. - -===== LdapLoginModule - -The `org.eclipse.jetty.jaas.spi.LdapLoginModule` uses LDAP to access authentication and authorization information stored in a directory. -The LDAP connection information and structure of the authentication/authorization data can be configured. - -Here's an example: - -[source,subs=verbatim] ----- -example { <1> - org.eclipse.jetty.jaas.spi.LdapLoginModule required <2><3> - contextFactory="com.sun.jndi.ldap.LdapCtxFactory" <4> - hostname="ldap.example.com" <5> - port="389" <6> - bindDn="cn=Directory Manager" <7> - bindPassword="directory" <8> - authenticationMethod="simple" <9> - useLdaps="true" <10> - userBaseDn="ou=people,dc=alcatel" <11> - userRdnAttribute="uid" <12> - userIdAttribute="cn" <13> - userPasswordAttribute="userPassword" <14> - userObjectClass="inetOrgPerson" <15> - roleBaseDn="ou=groups,dc=example,dc=com" <16> - roleNameAttribute="cn" <17> - roleMemberAttribute="uniqueMember" <18> - roleObjectClass="groupOfUniqueNames"; <19> - forceBindingLogin="false" <20> - debug="false" <21> -}; ----- -<1> The name of the configuration. -<2> The name of the `LoginModule` class. -<3> A standard JAAS flag making successful authentication via this `LoginModule` mandatory. -<4> The name of the context factory to use for the LDAP connection. -<5> The hostname for the LDAP connection. Optional. -<6> The port for the LDAP connection. Optional. -<7> The caller security Principal. Optional. -<8> The caller security credential. Optional. -<9> The security level for the LDAP connection environment. Optional. -<10> If true, use `ldaps` instead of `ldap` for the connection url. -<11> The distinguished name of the directory to search for user information. -<12> The name of the attribute for the user roles. -<13> The name of the attribute for the user id. -<14> The name of the attribute for the user password. -<15> The `ObjectClass` for users. -<16> The distinguished name of the directory to search for role information. -<17> The name of the attribute for roles. -<18> The name of the attribute storing the user for the roles `ObjectClass`. -<19> The name of the `ObjectClass` for roles. -<20> If true, the authentication proceeds on the basis of a successful LDAP binding using the username and credential provided by the user. -If false, then authentication proceeds based on username and password information retrieved from LDAP. -<21> If true, failed login attempts are logged on the server. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jaspi/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jaspi/chapter.adoc deleted file mode 100644 index e5a1fb0de6c1..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jaspi/chapter.adoc +++ /dev/null @@ -1,68 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-jaspi]] -=== JASPI - -Enabling this module allows Jetty to utilize authentication modules that implement the JSR 196 (JASPI) specification. JASPI provides an SPI (Service Provider Interface) for pluggable, portable, and standardized authentication modules. Compatible modules are portable between servers that support the JASPI specification. This module provides a bridge from Java Authentication to the Jetty Security framework. - -Only modules conforming to the "Servlet Container Profile" with the ServerAuthModule interface within the https://www.jcp.org/en/jsr/detail?id=196[JASPI Spec] are supported. These modules must be configured before start-up. Operations for runtime registering or de-registering authentication modules are not supported. - -[[og-jaspi-configuration]] -==== Configuration - -[[og-jaspi-module]] -===== The `jaspi` module - -Enable the `jaspi` module: - ----- -include::{JETTY_HOME}/modules/jaspi.mod[] ----- - -[[og-jaspi-xml]] -===== Configure JASPI - -To enable the `jaspi` module you can use the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=jaspi ----- - -You can then register a `AuthConfigProvider` onto the static `AuthConfigFactory` obtained with `AuthConfigFactory.getFactory()`. This registration can be done in the XML configuration file which will be copied to `$JETTY_BASE/etc/jaspi/jaspi-authmoduleconfig.xml` when the module is enabled. - -====== JASPI Demo -The `jaspi-demo` module illustrates setting up HTTP Basic Authentication using a Java Authentication module that comes packaged with jetty: `org.eclipse.jetty.security.jaspi.modules.BasicAuthenticationAuthModule`, and applies it for a context named `/test`. - -[source, xml] ----- -include::{JETTY_HOME}/etc/jaspi/jaspi-demo.xml[] ----- - -This example uses the `AuthConfigProvider` implementation provided by Jetty to register a `ServerAuthModule` directly. Other custom or 3rd party modules that are compatible with the `ServerAuthModule` interface in JASPI can be registered in the same way. - -===== Integration with Jetty Authentication Mechanisms - -To integrate with Jetty authentication mechanisms you must add a `LoginService` to your context. The `LoginService` provides a way for you to obtain a `UserIdentity` from a username and credentials. JASPI can interact with this Jetty `LoginService` by using the `PasswordValidationCallback`. - -The `CallerPrincipalCallback` and `GroupPrincipalCallback` do not require use of a Jetty `LoginService`. The principal from the `CallerPrincipalCallback` will be used directly with the `IdentityService` to produce a `UserIdentity`. - -===== Replacing the Jetty DefaultAuthConfigFactory - -Jetty provides an implementation of the `AuthConfigFactory` interface which is used to register `AuthConfigProviders`. This can be replaced by a custom implementation by adding a custom module which provides `auth-config-factory`. -This custom module must reference an XML file which sets a new instance of the `AuthConfigFactory` with the static method `AuthConfigFactory.setFactory()`. -For an example of this see the `jaspi-default-auth-config-factory` module, which provides the default implementation used by Jetty. - ----- -include::{JETTY_HOME}/modules/jaspi-default-auth-config-factory.mod[] ----- \ No newline at end of file diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/chapter.adoc deleted file mode 100644 index 8570c4db1ee0..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/chapter.adoc +++ /dev/null @@ -1,26 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-jmx]] -=== JMX Monitoring & Management - -Monitoring and management of a Jetty server is important because it allows you to monitor the status of the server (_"Is the server processing requests?"_) and to manage -- i.e. read and possibly change -- its configuration. - -The ability to read and change the Jetty configuration is very important for troubleshooting Jetty -- please refer to the xref:og-troubleshooting[troubleshooting section] for more information. - -Jetty relies on the Java Management Extensions (JMX) APIs included in OpenJDK to provide monitoring and management. - -The JMX APIs support a JVM-local `MBeanServer`, accessible only from within the JVM itself (or by tools that can _attach_ to a running JVM), and a way to expose the `MBeanServer` to remote clients via Java's RMI (Remote Method Invocation). - -include::jmx-local.adoc[] -include::jmx-remote.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/jmx-local.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/jmx-local.adoc deleted file mode 100644 index c88b03fa9f5e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/jmx-local.adoc +++ /dev/null @@ -1,34 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-jmx-local]] -==== Enabling Local JMX Support - -As with many other Jetty features, local JMX support is enabled with the `jmx` Jetty module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=jmx ----- - -With the `jmx` Jetty module enabled, Jetty components will be exported as JMX _MBeans_ to the JVM platform `MBeanServer`, so that they can be accessed by JMX compliant tools. - -Each Jetty component will export to its correspondent MBean relevant configuration parameters, so that a JMX tool can read and possibly change the component configuration through the MBean. - -Note that the Jetty MBeans are registered into the platform `MBeanServer`, but are not available to remote clients: they are _local_ to the JVM. - -This configuration is useful when you develop and test your Jetty server locally. - -JMX compliant tools such as link:https://adoptium.net/jmc.html[Java Mission Control (JMC)] can be started locally on your machine and can attach to other JVMs running on your machine, showing you the registered MBeans among which you will find the Jetty MBeans. - -NOTE: Enabling only the local JMX support is the most secure option for monitoring and management, but only users that have local access to the JVM will be able to browse the MBeans. -If you need to access the MBeans from a remote machine, read xref:og-jmx-remote[this section]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/jmx-remote.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/jmx-remote.adoc deleted file mode 100644 index dbc0cb239f39..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jmx/jmx-remote.adoc +++ /dev/null @@ -1,249 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-jmx-remote]] -==== Enabling Remote JMX Support - -There are two ways to configure a Jetty server so that it is possible to access the JVM platform MBeans from remote clients: - -* Use the `com.sun.management.jmxremote` and related system properties when starting Jetty. -Unfortunately, this solution does not work well with firewalls, and will not be discussed further. -* Use the `jmx-remote` Jetty module. - -Both ways use Java's Remote Method Invocation (RMI) to communicate between the client and the server. - -[IMPORTANT] -.Refresher: How RMI Works -==== -A server application that wants to make an object available to remote clients must _export_ the object. - -Exporting an object creates an RMI _stub_ that contains the host/port of the RMI _server_ that accepts incoming invocations from clients and forwards them to the object. -During the creation of the RMI stub, the host stored in the RMI stub is retrieved from the local name resolution system (for example, in Linux, from `/etc/hosts`). - -The RMI stub is then sent, along with a name that uniquely identifies the object, to the RMI _registry_. -The RMI registry is a service that maps names to RMI stubs; it may be external to both clients and server, although often it is part of the server JVM. - -When a client application wants to connect to the server object using RMI, it first connects to the RMI registry to download the RMI stub for the RMI server; recall that the RMI stub contains the host/port to connect to the RMI server. -Then, the client uses the RMI stub to connect to the RMI server, typically to a host/port that may be different from the RMI registry host/port (in particular, by default the RMI server port will be different from the RMI registry port). -==== - -Remote access to the platform MBeans, and therefore the Jetty MBeans, is enabled by the `jmx-remote` Jetty module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=jmx-remote ----- - -This command creates the `jmx-remote.ini` file: - -[source,subs=quotes] ----- -JETTY_BASE -└── start.d - └── #jmx-remote.ini# ----- - -Enabling the `jmx-remote` module transitively enables the xref:og-jmx-local[`jmx` module] as well. - -The configuration for the RMI registry and the RMI server is specified by a `JMXServiceURL`. -The string format of an RMI `JMXServiceURL` is the following: - ----- -service:jmx:rmi://:/jndi/rmi://:/jmxrmi ----- - -Below you can find examples of ``JMXServiceURL``s: - -[source,subs=quotes] ----- -*service:jmx:rmi:///jndi/rmi:///jmxrmi* -where: - rmi_server_host = local host address - rmi_server_port = randomly chosen - rmi_registry_host = local host address - rmi_registry_port = 1099 - -*service:jmx:rmi://0.0.0.0:1099/jndi/rmi://0.0.0.0:1099/jmxrmi* -where: - rmi_server_host = any address - rmi_server_port = 1099 - rmi_registry_host = any address - rmi_registry_port = 1099 - -*service:jmx:rmi://localhost:1100/jndi/rmi://localhost:1099/jmxrmi* -where: - rmi_server_host = loopback address - rmi_server_port = 1100 - rmi_registry_host = loopback address - rmi_registry_port = 1099 ----- - -The default `JMXServiceURL` configured by the `jmx-remote` module is the following: - ----- -service:jmx:rmi://localhost:1099/jndi/rmi://localhost:1099/jmxrmi ----- - -With the default configuration, only clients that are local to the server machine can connect to the RMI registry and RMI server - this is done for security reasons. -However, even with this local-only configuration, it would still be possible to access the MBeans from remote using an SSH tunnel, as explained in xref:og-jmx-remote-ssh-tunnel[this section]. - -By specifying an appropriate `JMXServiceURL`, you can fine tune the network address the RMI registry and the RMI server bind to, and the ports that the RMI registry and the RMI server listen to. -The RMI server and RMI registry hosts and ports can be the same (as in the default configuration) because RMI is able to multiplex traffic arriving to one port to multiple RMI objects. - -If you need to allow JMX remote access through a firewall, you must open both the RMI registry and the RMI server ports. -The default configuration simplifies the firewall configuration because you only need to open port `1099`. - -[NOTE] -==== -When Jetty is started with the `jmx-remote` module enabled, the RMI stub of the Jetty component that provides access to the MBeans is exported to the RMI registry. - -The RMI stub contains the host/port to connect to the RMI server, but the host is typically the machine host name, not the host specified in the `JMXServiceURL` (the latter is only used to specify the network address the RMI server binds to). - -To control the host stored in the RMI stub you need to set the system property `java.rmi.server.hostname` with the desired value in the module configuration file, `jmx-remote.ini`. -==== - -IMPORTANT: If your client cannot connect to the server, the most common cause is a mismatch between the RMI server host of the `JMXServiceURL` and the RMI server host of the RMI stub. - -You can customize the RMI server host/port, the RMI registry host/port and the system property `java.rmi.server.hostname` by editing the `jmx-remote.ini` configuration file. -Further information about the `jmx-remote` module configuration can be found xref:og-module-jmx-remote[here]. - -[[og-jmx-remote-ssh-tunnel]] -===== Remote JMX Access with Port Forwarding via SSH Tunnel - -You can access JMX MBeans on a remote machine when the RMI ports are not open, for example because of firewall policies, but you have SSH access to the machine, using local port forwarding via an SSH tunnel. - -In this case you want to configure the `JMXServiceURL` that binds the RMI server and the RMI registry to the loopback interface only and to the same port: - ----- -service:jmx:rmi://localhost:1099/jndi/rmi://localhost:1099/jmxrmi ----- - -You must set the system property `-Djava.rmi.server.hostname=localhost` so that the RMI stub contains `localhost` as the host name to connect to. -This is, incidentally, the default configuration of the `jmx-remote` module. - -Then you set up the local port forwarding with the SSH tunnel: - ----- -$ ssh -L 1099:localhost:1099 @ ----- - -Thanks to the local port forwarding of the SSH tunnel, when the client connects to `localhost:1099` on your local computer, the traffic will be forwarded to `machine_host` and when there, the SSH daemon will forward the traffic to `localhost:1099` on `machine_host`, which is exactly where the RMI server and the RMI registry listens to. - -The client first contacts the RMI registry, so it connects to `localhost:1099` on your local computer; the traffic is forwarded to `machine_host` through the SSH tunnel, connects to the RMI registry and the RMI stub is downloaded to the client. - -Then the client uses the RMI stub to connect to the RMI server. The RMI stub contains `localhost` as the RMI server host because that is what you have configured with the system property `java.rmi.server.hostname`. - -The client will connect again to `localhost:1099` on your local computer, this time to contact the RMI server; the traffic is forwarded to `machine_host` through the SSH tunnel, arrives to `machine_host` and connects to the RMI server. - -[[og-jmx-remote-auth]] -===== Remote JMX Access Authentication & Authorization - -The standard `javax.management.remote.JMXConnectorServer` class, used by the `jmx-remote` module to provide remote JMX access to Jetty MBeans, provides several options to authenticate and authorize users. -For a complete guide to controlling authentication and authorization in JMX, see link:https://docs.oracle.com/en/java/javase/11/management/monitoring-and-management-using-jmx-technology.html[the official JMX documentation]. - -The simplest way to control JMX authentication and authorization is to specify two files: one contains username and password pairs, and the other contains username and permission pairs. - -This is achieved by enabling the `jmx-remote-auth` Jetty module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=jmx-remote-auth ----- - -Enabling the `jmx-remote-auth` Jetty module creates the following files: - ----- -$JETTY_BASE -├── etc -│ ├── jmxremote.access -│ ├── jmxremote.password -│ └── jmx-remote-auth.xml -└── start.d - ├── jmx-remote-auth.ini - └── jmx-remote.ini ----- - -Then you edit the `$JETTY_BASE/etc/jmxremote.password` file, adding the username/password pairs that you need: - -.$JETTY_BASE/etc/jmxremote.password ----- -# The file format is: -alice wonderland -bob marley ----- - -You must also edit the `$JETTY_BASE/etc/jmxremote.access` file to give permissions to your users: - -.$JETTY_BASE/etc/jmxremote.access ----- -# The file format is: -alice readwrite -bob readonly ----- - -The above files define user `alice` with password `wonderland` to have `readwrite` access, and user `bob` with password `marley` to have `readonly` access. - -[[og-jmx-remote-secure]] -===== Securing Remote JMX Access with TLS - -The JMX communication via RMI happens by default in clear-text, but it is possible to secure the JMX communication via RMI with TLS. - -If you want to reuse the configuration that you are using for the xref:og-protocols-https[`https` module], you can just enable the `jmx-remote-ssl.xml` Jetty module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=jmx-remote-ssl ----- - -[NOTE] -==== -The `jmx-remote-ssl` Jetty module depends on the `ssl` Jetty module that in turn requires a KeyStore (read xref:og-protocols-ssl[this section] for more information). -==== - -The KeyStore must contain a valid certificate signed by a Certification Authority. -Having certificates signed by a Certification Authority simplifies by a lot the configuration needed to get the RMI communication over TLS working properly. - -The RMI mechanic is the usual one: the RMI client (typically a monitoring console) will connect first to the RMI registry (using TLS), download the RMI stub that contains the address and port of the RMI server to connect to, then connect to the RMI server (using TLS). - -This also mean that if the RMI registry and the RMI server are on different hosts, the RMI client must have available the cryptographic material to validate the certificates from both hosts. -This is where having certificates signed by a Certification Authority simplifies the configuration: if they are signed by a well known Certification Authority, the client does not need any extra configuration -- everything will be handled by the Java runtime. - -If the certificates are not signed by a Certification Authority (for example the certificate is self-signed), then you need to specify the TLS system properties that allow RMI (especially when acting as an RMI client) to retrieve the cryptographic material necessary to establish the TLS connection. - -[IMPORTANT] -==== -When the RMI server exports the `JMXConnectorServer` it acts as an RMI _client_ towards the RMI registry, and as such you must specify the TLS system properties as detailed below. -==== - -You must edit the `$JETTY_BASE/start.d/jmx-remote-ssl.ini` file and add the TrustStore path and password: - -.$JETTY_BASE/start.d/jmx-remote-ssl.ini ----- ---module=jmx-remote-ssl - -# System properties necessary for non-trusted certificates. --Djavax.net.ssl.trustStore=/path/to/trustStore.p12 --Djavax.net.ssl.trustStorePassword=password ----- - -[IMPORTANT] -==== -The TrustStore must contain the certificate you want to trust. - -If you are using self-signed certificates, the KeyStore already contains the self-signed certificate and therefore the KeyStore can be used as a TrustStore, and the system properties above can refer to the KeyStore path and password. -==== - -JMX compliant tools that offer a graphical user interface also must be started specifying the TrustStore path and password. - -For example, to launch link:https://adoptium.net/jmc.html[Java Mission Control (JMC)]: - ----- -$ jmc -vmargs -Djavax.net.ssl.trustStore=/path/to/trustStore.p12 -Djavax.net.ssl.trustStorePassword=password ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jndi/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jndi/chapter.adoc deleted file mode 100644 index bb51536e2b7f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jndi/chapter.adoc +++ /dev/null @@ -1,392 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-jndi]] -=== JNDI - -Enable the `plus` module in order to be able to use JNDI resources in your webapp. -If you already have the `annotations` module enabled, then it will already be enabled. - -If you have extra jars associated with your JNDI resources, eg database drivers etc, that are not located inside your webapp then you should place those jars into your `$jetty.base/lib/ext` directory. -If your base doesn't already contain this directory, then enable the `ext` module, and Jetty will create the directory for you and ensure its contents are on the server's classpath. - -You can now declare JNDI resources and reference them within your webapps. - -==== Declaring resources - -You must declare the objects you want bound into the environment so that you can then hook them into your webapp via `env-entry`, `resource-ref` and `resource-env-refs` in `web.xml`, `web-fragment.xml` or `override-web.xml`. - -You make these declarations in Jetty XML files that are either _external_ or _internal_ to your webapp. -A server or context XML file is external to your webapp. -The special `WEB-INF/jetty-env.xml` file is internal to your webapp. -See the section on xref:og-jndi-xml[Jetty XML files] for more information on how to choose in which XML file to place your declarations. - -For now, let's look at _what_ you declare in the XML file, regardless of its location. - -Declaring a JDNI resource to be referenced later in your webapp is accomplished by declaring new instances of the following types: - -xref:og-jndi-env[`org.eclipse.jetty.plus.jndi.EnvEntry`]:: -Used for `env-entry` type of entries -xref:og-jndi-resource[`org.eclipse.jetty.plus.jndi.Resource`]:: -Used for most other type of resources -xref:og-jndi-tx[`org.eclipse.jetty.plus.jndi.Transaction`]:: -For a JTA manager -xref:og-jndi-link[`org.eclipse.jetty.plus.jndi.Link`]:: -For the link between a `web.xml` resource name and a naming entry - -Declarations of each of these types follow a similar pattern: - -[source,xml,subs=verbatim] ----- - - - - - ----- -<1> Defines a resource to Jetty. -<2> Specifies the xref:og-jndi-scope[scope] of the resource. -<3> Specifies the name of the resource which will be looked up by the webapp relative to the `java:comp/env` namespace. -<4> Specifies the value of the resource. - - -[[og-jndi-env]] -===== org.eclipse.jetty.plus.jndi.EnvEntry - -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` ``. -In such cases, you can use the `org.eclipse.jetty.plus.jndi.EnvEntry` class, and optionally even override an entry of the same name in `web.xml`. - -Here's an example that defines the equivalent of an `env-entry` called `mySpecialValue` with value `4000` that overrides an `` declaration of the same name in web.xml: - -[source,xml,subs=verbatim] ----- - - - mySpecialValue - 4000 - true - ----- -<1> Define an `EnvEntry` that corresponds to an ``. -<2> xref:og-jndi-scope[Scoped] at the JVM level. -<3> The name of the entry, corresponding to a lookup by the webapp of `java:comp/env/mySpecialValue`. -<4> The value of the entry, in this case the integer value `4000`. -<5> `true` means to override the value of an `` of the same name in `web.xml`. - -Note that if you don't want to override the `web.xml` value, simply omit the last 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 - -Jetty is a little more flexible and allows you to also bind: - -* custom POJOs -* link:http://docs.oracle.com/javase/1.5.0/docs/api/javax/naming/Reference.html[`javax.naming.References`] -* link: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__. - -[[og-jndi-resource]] -===== org.eclipse.jetty.plus.jndi.Resource - -You can configure any type of resource that you want to refer to in `web.xml` via a `resource-ref` or `resource-env-ref` by 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, `javax.naming.Reference` or `javax.naming.Referenceable` instance. - -Let's examine how to configure some of the most common types of resources. - -====== DataSources - -In this example, we'll configure a link:http://db.apache.org/derby[Derby] DataSource named `jdbc/myds`: - -[source,xml,subs=verbatim] ----- - - - - jdbc/myds - - - test - create - - - - ----- - -This would linked into the webapps JNDI namespace via an entry in a `web.xml` like so: - -[source,xml,subs=verbatim] ----- - - jdbc/myds - javax.sql.DataSource - Container - ----- - -[NOTE] -==== -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. - -Also note that the link:http://jcp.org/aboutJava/communityprocess/pr/jsr244/index.html[J2EE Specification] recommends storing DataSources relative to `jdbc/` and thus looked up by the application as `java:comp/env/jdbc/xxx`. -Eg The Datasource bound in Jetty as `jdbc/users` would be looked up by the application as `java:comp/env/jdbc/users` - -==== - -//TODO For more examples of datasource configurations, see xref:jndi-datasource-examples[]. - - -====== JMS Queues, Topics and ConnectionFactories - -Jetty can bind any implementation of the JMS destinations and connection factories. - -Here is an example of binding an link:http://activemq.apache.org[ActiveMQ] in-JVM connection factory: - -[source,xml,subs=verbatim] ----- - - - - jms/connectionFactory - - - vm://localhost?broker.persistent=false - - - - ----- - -The corresponding entry in `web.xml` to bind the ConnectionFactory into the webapp's JNDI namespace would be: - -[source,xml,subs=verbatim] ----- - - jms/connectionFactory - javax.jms.ConnectionFactory - Container - ----- - -[NOTE] -==== -The link:http://jcp.org/aboutJava/communityprocess/pr/jsr244/index.html[J2EE Specification] recommends storing JMS connection factories under `jms/`. -Eg The ConnectionFactory bound in Jetty as `jms/inqueue` would be looked up by the application as `java:comp/env/jms/inqueue`. -==== - -====== Mail - -To configure access to `javax.mail.Session` from within a webapp, declare an `org.eclipse.jetty.plus.jndi.Resource` with an `org.eclipse.jetty.jndi.factories.MailSessionReference` that will hold the mail configuration and create the instance of the `Session` when it is referenced: - -[source,xml,subs=verbatim] ----- - - - - mail/Session - - - fred - OBF:1xmk1w261z0f1w1c1xmq - - - XXX - me@me - true - - - - - - ----- -<1> Use the `org.eclipse.jetty.jndi.factories.MailSessionReference` class to hold the configuration. -<2> Set the username for the mail instance. -<3> Set the password for the mail instance - use Jetty's secure password obfuscation to obscure the password. -<4> Set all other applicable properties. - -The webapp performs a lookup for `java:comp/env/mail/Session` at runtime and obtains a `javax.mail.Session` that has the correct configuration to permit it to send email via SMTP. - -[NOTE] -==== -Jetty does not provide the `javax.mail` and `javax.activation` jars. - -Note also that the link:http://jcp.org/aboutJava/communityprocess/pr/jsr244/index.html[J2EE Specification] recommends storing JavaMail connection factories under `mail/`. -Eg The `MailSessionReference` bound to jetty as `mail/smtp` would be looked up by the application as `java:comp/env/mail/smtp`. -==== - -[[og-jndi-tx]] -===== org.eclipse.jetty.plus.jndi.Transaction - -To perform distributed transactions with your resources, a _transaction manager_ that supports the JTA interfaces is required. -The transaction manager is looked up by the application as `java:comp/UserTransaction`. - -Jetty does not ship with a JTA manager, but _does_ provide the infrastructure to plug in the JTA manager of your choice. - -Use the link:{javadoc-url}/org/eclipse/jetty/plus/jndi/Transaction.html[org.eclipse.jetty.plus.jndi.Transaction] object in a xref:og-jndi-xml[Jetty XML file] to configure the JTA manager. - -The following example configures the link:http://www.atomikos.com/[Atomikos] transaction manager: - -[source,xml,subs=verbatim] ----- - - - - - ----- - -Jetty will automatically bind this JTA manager to the webapp's JNDI namespace at `java:comp/UserTransaction`. - -[[og-jndi-link]] -===== org.eclipse.jetty.plus.jndi.Link - -Usually, the name you provide for the `org.eclipse.jetty.plus.jndi.Resource` is the same name you reference in `web.xml`. -This ensures that the two are linked together and thus accessible to your webapp. - -However, if the names cannot be the same, then it is possible to effectively alias one to another using an `org.eclipse.jetty.plus.jndi.Link`. - -Let's look at an example. - -Supposing you have a declaration for a Datasource named `jdbc/workforce` in a Jetty context XML file, but your web.xml wants to link to a `` named `jdbc/employees`, and you cannot edit the web.xml. -You can create a `WEB-INF/jetty-env.xml` file with an `org.eclipse.jetty.plus.jndi.Link` that ties together the names `jdbc/workforce` and `jdbc/employees`: - -The context XML file declares `jdbc/workforce`: - -[source,xml,subs=verbatim] ----- - - - - jdbc/workforce - - - test - create - - - - ----- - -The `web.xml` refers to it as `jdbc/employees`: - -[source,xml,subs=verbatim] ----- - - jdbc/employees - javax.sql.DataSource - Container - ----- - -Create a `WEB-INF/jetty-env.xml` file with a `org.eclipse.jetty.plus.jndi.Link` to link these names together: - -[source,xml,subs=verbatim] ----- - - - jdbc/employees - jdbc/workforce - ----- -<1> The name as referenced in the `web.xml` file. -<2> The name as referenced in the context XML file. - -[[og-jndi-xml]] -===== Jetty XML files - -You can define naming resources in three places: - -Server XML file:: -Naming resources defined in a server XML file are xref:og-jndi-scope[scoped] at either the JVM level or the `org.eclipse.jetty.server.Server` level. -The classes for the resource _must_ be visible at the Jetty *container* level. -If instead the classes for the resource only exist inside your webapp, you must declare it in a `WEB-INF/jetty-env.xml` file. -Context XML file:: -Entries in a context XML file should be xref:og-jndi-scope[scoped] at the level of the webapp to which they apply (although it is possible to use a less strict scoping level of Server or JVM, but not recommended). -As with resources declared in a server XML file, classes associated with the resource _must_ be visible on the *container's* classpath. -WEB-INF/jetty-env.xml:: -Naming resources in a `WEB-INF/jetty-env.xml` file are xref:og-jndi-scope[scoped] to the webapp 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. - -[[og-jndi-scope]] -===== Resource scoping - -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. -This scope is represented by a `null` first parameter to the resource declaration. -For example: -[source,xml,subs=verbatim] ----- - - - jms/connectionFactory - - - vm://localhost?broker.persistent=false - - - ----- -<1> Empty first arg equates to JVM scope for the object bound to name `jms/connectionFactory`. - -*Server scope:* -The name is unique to a Server instance, and is only visible to applications associated with that instance. -This scope is represented by referencing the Server instance as the first parameter to the resource declaration. -For example: -[source,xml,subs=verbatim] ----- - - - jms/connectionFactory - - - vm://localhost?broker.persistent=false - - - ----- -<1> We refer to the id `Server` which identifies the default `org.eclipse.jetty.server.Server` instance. - -*Webapp scope:* -The name is unique to the `org.eclipse.jetty.webapp.WebAppContext` instance, and is only visible to that application. -This scope is represented by referencing the instance as the first parameter to the resource declaration. -For example: -[source,xml,subs=verbatim] ----- - - - jms/connectionFactory - - - vm://localhost?broker.persistent=false - - - ----- -<1> We refer to an instance of an `org.eclipse.jetty.webapp.WebAppContext` which has been previously defined. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jsp/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jsp/chapter.adoc deleted file mode 100644 index f28c2025b7a0..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/jsp/chapter.adoc +++ /dev/null @@ -1,210 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-jsp]] -=== Java Server Pages - -Jetty supports JSP via the `jsp` module, which is based on Apache Jasper: - ----- -include::{JETTY_HOME}/modules/jsp.mod[] ----- - -Logging has been bridged to Jetty logging, so you can enable logging for the `org.apache.jasper` package, subpackages and classes as usual. - -==== Configuration of the JSP Servlet - -The `org.eclipse.jetty.jsp.JettyJspServlet` is the servlet responsible for serving JSPs. - -It is configured as the default jsp servlet in the `$JETTY_HOME/etc/webdefault.xml` file. -Notice that Jetty identifies the jsp servlet by the presence of the `id="jsp"` attribute in the `` declaration. - -That file maps the `org.eclipse.jetty.jsp.JettyJspServlet` to the following partial urls: - -* `+*.jsp+` -* `+*.jspf+` -* `+*.jspx+` -* `+*.xsp+` -* `+*.JSP+` -* `+*.JSPF+` -* `+*.JSPX+` -* `+*.XSP+` - -You can change to a different servlet, change or add ````s or add extra ````s in your `web.xml` file. - -Here's an example of adding an `` to augment the definitions from the standard `webdefault.xml` file: - -[source,xml,subs=verbatim] ----- - - jsp - - keepgenerated - true - - ----- -<1> This identifies this servlet as the jsp servlet to Jetty. -<2> This identifies this declaration as augmenting the already-defined servlet called `jsp`. -<3> This init param controls whether the jsp servlet retains the `+*.java+` files generated during jsp compilation. -<4> This sets the value of the init param - -Another element you might consider adding to the default setup is `async-supported`: - -[source,xml,subs=verbatim] ----- - - jsp - true - ----- -<1> This identifies this servlet as the jsp servlet to Jetty. -<2> This identifies this declaration as augmenting the already-defined servlet called `jsp`. -<3> By default, the jsp servlet does not support async. - -There are many configuration parameters for the Apache Jasper JSP Servlet, here are some of them: - -.JSP Servlet Parameters -[cols=",,,",options="header"] -|=== -|init param |Description |Default |`webdefault.xml` - -|checkInterval |If non-zero and `development` is `false`, background jsp recompilation is enabled. This value is the interval in seconds between background recompile checks. - |0 |– -|classpath |The classpath is dynamically generated if the context has a URL classloader. The `org.apache.catalina.jsp_classpath` -context attribute is used to add to the classpath, but if this is not set, this `classpath` configuration item is added to the classpath instead.` |- |– - -|classdebuginfo |Include debugging info in class file. |true |– - -|compilerClassName |If not set, defaults to the Eclipse jdt compiler. |- |– - -|compiler |Used if the Eclipse jdt compiler cannot be found on the -classpath. It is the classname of a compiler that Ant should invoke. |– -|– - -|compilerTargetVM |Target vm to compile for. |1.8 |1.8 - -|compilerSourceVM |Sets source compliance level for the jdt compiler. -|1.8 |1.8 - -|development |If `true` recompilation checks occur at the frequency governed by `modificationTestInterval`. |true |– - -|displaySourceFragment |Should a source fragment be included in -exception messages |true |– - -|dumpSmap |Dump SMAP JSR45 info to a file. |false |– - -|enablePooling |Determines whether tag handler pooling is enabled. |true |– - -|engineOptionsClass |Allows specifying the Options class used to -configure Jasper. If not present, the default EmbeddedServletOptions -will be used. |- |– - -|errorOnUseBeanInvalidClassAttribute |Should Jasper issue an error when -the value of the class attribute in an useBean action is not a valid -bean class |true |– - -|fork |Only relevant if you use Ant to compile JSPs: by default Jetty will use the Eclipse jdt compiler.|true |- - -|genStrAsCharArray |Option for generating Strings as char arrays. |false |– - -|ieClassId |The class-id value to be sent to Internet Explorer when -using tags. |clsid:8AD9C840-044E-11D1-B3E9-00805F499D93 |– - -|javaEncoding |Pass through the encoding to use for the compilation. -|UTF8 |– - -|jspIdleTimeout |The amount of time in seconds a JSP can be idle before -it is unloaded. A value of zero or less indicates never unload. |-1 |– - -|keepgenerated |Do you want to keep the generated Java files around? -|true |– - -|mappedFile |Support for mapped Files. Generates a servlet that has a -print statement per line of the JSP file |true |– - -|maxLoadedJsps |The maximum number of JSPs that will be loaded for a web -application. If more than this number of JSPs are loaded, the least -recently used JSPs will be unloaded so that the number of JSPs loaded at -any one time does not exceed this limit. A value of zero or less -indicates no limit. |-1 |– - -|modificationTestInterval |If `development=true`, interval between -recompilation checks, triggered by a request. |4 |– - -|quoteAttributeEL | When EL is used in an attribute value on a JSP page, should the rules for quoting of attributes described in JSP.1.6 be applied to the expression - |true |- - -|recompileOnFail |If a JSP compilation fails should the -modificationTestInterval be ignored and the next access trigger a -re-compilation attempt? Used in development mode only and is disabled by -default as compilation may be expensive and could lead to excessive -resource usage. |false |– - -|scratchDir |Directory where servlets are generated. The default is the value of the context attribute `javax.servlet.context.tempdir`, or the system property `java.io.tmpdir` if the context attribute is not set. |– |– - -|strictQuoteEscaping |Should the quote escaping required by section JSP.1.6 of the JSP specification be applied to scriplet expression. - |true|- - -|suppressSmap |Generation of SMAP info for JSR45 debugging. |false |– - -|trimSpaces |Should template text that consists entirely of whitespace be removed from the output (true), replaced with a single space (single) or left unchanged (false)? Note that if a JSP page or tag file specifies a trimDirectiveWhitespaces value of true, that will take precedence over this configuration setting for that page/tag. -trimmed? |false |– - -|xpoweredBy |Generate an X-Powered-By response header. |false |false - -|=== - -[NOTE] -==== -If the value you set doesn't take effect, try using all lower case instead of camel case, or capitalizing only some of the words in the name, as Jasper is inconsistent in its parameter naming strategy. -==== - -=== JavaServer Pages Standard Tag Libraries - -The JavaServer Pages Standard Tag Library (JSTL) is part of the Jetty distribution, and is available via the `jstl` module: - ----- -include::{JETTY_HOME}/modules/jstl.mod[] ----- - -When enabled, Jetty will make the JSTL tags available for your webapps. - -=== JavaServer Faces TagLibs - -If you want to use JSF with your webapp, you should copy the relevant jars from your implementation of choice into your `$JETTY_BASE` directory, ideally into `$JETTY_BASE/lib/ext`. -If that directory does not exist, enable the `ext` module, which will create the directory and ensure all jars within it are put onto the container classpath. - - -Then you will need to tell Jetty which of those jars contains the `+*.tld+` files. -To accomplish that, you need to specify either the name of the file or a pattern that matches the name/s of the file/s as the `org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern` context attribute. -You will need to preserve the existing value of the attribute, and add in your extra pattern. - -Here's an example of using a context xml file to add in a pattern to match files starting with `jsf-`, which contain the `+*.tld+` files: - -[source,xml,subs=verbatim] ----- - - - - - - org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern - .*/jetty-servlet-api-[^/]*\.jar$|.*/javax.servlet.jsp.jstl-.*\.jar$|.*/org.apache.taglibs.taglibs-standard-impl-.*\.jar$|.*/jsf-[^/]*\.jar$ - - ----- -<1> Configures a link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`], which is the Jetty component that represents a standard Servlet web application. -<2> Specifies a context attribute. -<3> Specifies the name of the context attribute. -<4> Adds the additional pattern `+.*/jsf-[^/]*\.jar$+` to those already existing. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/chapter.adoc deleted file mode 100644 index 32b6f2cc6123..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/chapter.adoc +++ /dev/null @@ -1,26 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-keystore]] -=== Configuring SSL/TLS KeyStores - -A KeyStore is a file on the file system that contains a private key and a public certificate, along with the certificate chain of the certificate authorities that issued the certificate. -The private key, the public certificate and the certificate chain, but more generally the items present in a KeyStore, are typically referred to as "cryptographic material". - -Keystores may encode the cryptographic material with different encodings, the most common being link:https://en.wikipedia.org/wiki/PKCS_12[PKCS12], and are typically protected by a password. - -Refer to the xref:og-protocols-ssl[secure protocols section] for more information about how to configure a secure connector using a KeyStore. - -include::keystore-create.adoc[] -include::keystore-csr.adoc[] -include::keystore-client-authn.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-client-authn.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-client-authn.adoc deleted file mode 100644 index 76013cbbda7b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-client-authn.adoc +++ /dev/null @@ -1,141 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-keystore-client-authn]] -==== Creating a KeyStore for Client Certificate Authentication - -For the majority of secure web sites, it is the client (typically the browser) that validates the certificate sent by the server (by verifying the certificate chain). -This is the _server domain certificate_. - -However, the TLS protocol supports a _mutual authentication_ mode where also the client must send a certificate to the server, that the server validates. - -You typically want to sign the client certificate(s) with a server certificate that you control, and you must distribute the client certificate(s) to all the clients that need it, and redistribute the client certificates when they expire. -The _server authentication certificate_ may be different from the _server domain certificate_, but it's typically stored in the same KeyStore for simplicity (although under a different alias). - -First, you want to create the private key and server authentication certificate that you will use to sign client certificates: - -[source,subs=verbatim] ----- -keytool - -genkeypair - -alias server_authn <1> - -validity 90 - -keyalg RSA - -keysize 2048 - -keystore keystore.p12 <2> - -storetype pkcs12 - -dname "CN=server_authn, OU=Unit, O=Company, L=City, S=State, C=Country" <3> - -ext bc=ca:true <4> - -v ----- -<1> use the `server_authn` alias to differentiate from the alias of the server certificate -<2> the KeyStore file -<3> the CN is not that important, since this certificate will not be validated by clients -<4> the extension with the basic constraints (more below) - -IMPORTANT: The important difference with the xref:og-keystore-create[creation of a server certificate] is the _basic constraints_ extension (`bc`) that indicates that this certificates acts as a certificate authority (`ca:true`). - -Now you want to export both the private key and server authentication certificate. -Unfortunately, the `keytool` program cannot export private keys, so you need to use a different command line program like `openssl`, or a graphical program like link:https://keystore-explorer.org/[KeyStore Explorer]. - -Let's use `openssl` to export the server authentication private key: - ----- -openssl - pkcs12 - -in keystore.p12 - -nodes - -nocerts - -out server_authn.key ----- - -Now let's export the server authentication certificate: - ----- -keytool - -exportcert - -keystore keystore.p12 - -rfc - -file server_authn.crt - -v ----- - -At this point, you want to create a client KeyStore, so that you can sign the client certificate with the server authentication cryptographic material: - -[source,subs=verbatim] ----- -keytool - -genkeypair - -validity 90 - -keyalg RSA - -keysize 2048 - -keystore client_keystore.p12 <1> - -storetype pkcs12 - -dname "CN=client, OU=Unit, O=Company, L=City, S=State, C=Country" <2> - -v ----- -<1> the client KeyStore file -<2> the CN is not that important, since it will not be validated by the server - -Now produce a certificate signing request (CSR): - ----- -keytool - -certreq - -file client.csr - -keystore client_keystore.p12 ----- - -Now you need to sign the CSR, but again the `keytool` program does not have this functionality, and you must resort again to use `openssl`: - ----- -openssl - x509 - -req - -days 90 - -in client.csr - -CA server_authn.crt - -CAkey server_authn.key - -CAcreateserial - -sha256 - -out signed.crt ----- - -Now you need to import the server authentication certificate and the signed client certificate into the client KeyStore. - -First, the server authentication certificate: - ----- -keytool - -importcert - -alias ca - -file server_authn.crt - -keystore client_keystore.p12 - -v ----- - -Then, the signed client certificate: - ----- -keytool - -importcert - -file signed.crt - -keystore client_keystore.p12 - -v ----- - -Now you can distribute `client_keystore.p12` to your client(s). - -// TODO: add a section about renewal? - -Refer to the section about configuring xref:og-protocols-ssl[secure protocols] to configure the secure connector to require client authentication. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-create.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-create.adoc deleted file mode 100644 index dfd3aed33385..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-create.adoc +++ /dev/null @@ -1,70 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-keystore-create]] -==== Creating a KeyStore - -KeyStores are created with the JDK tool `$JAVA_HOME/bin/keytool`. - -The following command creates a KeyStore file containing a private key and a self-signed certificate: - -[source,subs=verbatim] ----- -keytool - -genkeypair <1> - -alias mykey <2> - -validity 90 <3> - -keyalg RSA <4> - -keysize 2048 <5> - -keystore /path/to/keystore.p12 <6> - -storetype pkcs12 <7> - -dname "CN=domain.com, OU=Unit, O=Company, L=City, S=State, C=Country" <8> - -ext san=dns:www.domain.com,dns:domain.org <9> - -v <10> ----- -<1> the command to generate a key and certificate pair -<2> the alias name of the key and certificate pair -<3> specifies the number of days after which the certificate expires -<4> the algorithm _must_ be RSA (the DSA algorithm does not work for web sites) -<5> indicates the strength of the key -<6> the KeyStore file -<7> the KeyStore type, stick with the standard PKCS12 -<8> the distinguished name (more below) -- customize it with your values for CN, OU, O, L, S and C -<9> the extension with the subject alternative names (more below) -<10> verbose output - -The command prompts for the KeyStore password that you must choose to protect the access to the KeyStore. - -[IMPORTANT] -==== -The important parts of the command above are the _Common Name_ (CN) part of the distinguished name, and the subject alternative names (SAN). - -The CN value must be the main domain you own and that you want to use for your web applications. -For example, if you have bought domains `domain.com` and `domain.org`, you want to specify `CN=domain.com` as your main domain. - -Furthermore, to specify additional domains or subdomains within the same certificate, you must specify the SAN extension. -In the example above, `san=dns:www.domain.com,dns:domain.org` specifies `www.domain.com` and `domain.org` as alternative names for your web applications (that you can configure using xref:og-deploy-virtual-hosts[virtual hosts]). - -In rare cases, you may want to specify IP addresses, rather than domains, in the SAN extension. -The syntax in such case is `san=ip:127.0.0.1,ip:[::1]`, which specifies as subject alternative names IPv4 `127.0.0.1` and IPv6 `[::1]`. -==== - -[[og-keystore-create-many]] -===== KeyStores with Multiple Entries - -A single KeyStore may contain multiple key/certificate pairs. -This is useful when you need to support multiple domains on the same Jetty server (typically accomplished using xref:og-deploy-virtual-hosts[virtual hosts]). - -You can create multiple key/certificate pairs as detailed in the xref:og-keystore-create[previous section], provided that you assign each one to a different alias. - -Compliant TLS clients will send the xref:og-protocols-ssl-sni[TLS SNI extension] when creating new connections, and Jetty will automatically choose the right certificate by matching the SNI name sent by the client with the CN or SAN of certificates present in the KeyStore. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-csr.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-csr.adoc deleted file mode 100644 index bb31195235e4..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/keystore/keystore-csr.adoc +++ /dev/null @@ -1,78 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-keystore-csr]] -==== Creating a Certificate Signing Request - -Self-signed certificates are not trusted by browsers and generic clients: you need to establish a trust chain by having your self-signed certificate signed by a certificate authority (CA). - -Browsers and generic clients (e.g. Java clients) have an internal list of trusted certificate authorities root certificates; they use these trusted certificates to verify the certificate they received from the server when they connect to your web applications. - -To have your self-signed certificate signed by a certificate authority you first need to produce a _certificate signing request_ (CSR): - -[source,subs=verbatim] ----- -keytool - -certreq <1> - -file domain.com.csr <2> - -keystore keystore.p12 <3> ----- -<1> the command to generate a certificate signing request -<2> the file to save the CSR -<3> the keystore that contains the self-signed certificate - -Then, you have to send the CSR file to the certificate authority of your choice, and wait for their reply (they will probably require a proof that you really own the domains indicated in your certificate). - -Eventually, the certificate authority will reply to you with one or more files containing the CA certificate chain, and your certificate signed by their certificate chain. - -[[og-keystore-csr-import]] -==== Importing the Signed Certificate - -The file you receive from the CA is typically in PEM format, and you *must* import it back into the same KeyStore file you used to generate the CSR. -You must import *both* the certificate chain and your signed certificate. - -First, import the certificate chain: - -[source,subs=verbatim] ----- -keytool - -importcert <1> - -alias ca <2> - -file chain_from_ca.pem <3> - -keystore keystore.p12 <4> - -trustcacerts <5> - -v <6> ----- -<1> the command to import certificates -<2> use the `ca` alias to differentiate from the alias of the server certificate -<3> the file containing the certificate chain received from the CA -<4> your KeyStore file -<5> specify that you trust CA certificates -<6> verbose output - -Then, import the signed certificate: - ----- -keytool - -importcert - -file signed_certificate.pem - -keystore keystore.p12 - -trustcacerts - -v ----- - -Now you have a trusted certificate in your KeyStore that you can use for the domains of your web applications. - -// TODO: add a section about renewal? - -Refer to the section about configuring xref:og-protocols-ssl[secure protocols] to configure the secure connector with your newly created KeyStore. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/chapter.adoc deleted file mode 100644 index 2b8956cf5642..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/chapter.adoc +++ /dev/null @@ -1,16 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -include::modules.adoc[] -include::modules-custom.adoc[] -include::modules-standard.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-alpn.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-alpn.adoc deleted file mode 100644 index 69d1ede999a9..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-alpn.adoc +++ /dev/null @@ -1,25 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-alpn]] -===== Module `alpn` - -The `alpn` module enables support for the ALPN negotiation mechanism of the TLS protocol. - -You can configure the list of application protocols negotiated by the ALPN mechanism, as well as the default protocol to use if the ALPN negotiation fails (for example, the client does not support ALPN). - -The module properties are: - ----- -include::{JETTY_HOME}/modules/alpn.mod[tags=documentation] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-bytebufferpool.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-bytebufferpool.adoc deleted file mode 100644 index b92c2a838367..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-bytebufferpool.adoc +++ /dev/null @@ -1,40 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-bytebufferpool]] -===== Module `bytebufferpool` - -The `bytebufferpool` module allows you to configure the server-wide `ByteBuffer` pool. -Pooling ``ByteBuffer``s results in less memory usage and less pressure on the Garbage Collector. - -``ByteBuffer``s are pooled in _buckets_; each bucket as a capacity that is a multiple of a capacity factor that you can configure. -For example, if a request for a `ByteBuffer` of capacity 2000 is requested, and the capacity factor is 1024, then the pool will allocate a buffer from the second bucket, of capacity 2048 (1024 * 2). - -Applications that need to sustain many concurrent requests -- or load spikes -- may require many buffers during peak load. These buffers will remain pooled once the system transitions to a lighter load (or becomes idle), and it may be undesirable to retain a lot of memory for an idle system. - -It is possible to configure the max heap memory and the max direct memory that the pool retains. -Excess buffers will not be pooled and will be eventually garbage collected. - -The module file is `$JETTY_HOME/modules/bytebufferpool.mod`: - ----- -include::{JETTY_HOME}/modules/bytebufferpool.mod[] ----- - -Among the configurable properties, the most relevant are: - -`jetty.byteBufferPool.maxHeapMemory`:: -This property allows you to cap the max heap memory retained by the pool. - -`jetty.byteBufferPool.maxDirectMemory`:: -This property allows you to cap the max direct memory retained by the pool. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-console-capture.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-console-capture.adoc deleted file mode 100644 index c9810f63d650..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-console-capture.adoc +++ /dev/null @@ -1,26 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-console-capture]] -===== Module `console-capture` - -The `console-capture` module captures `System.out` and `System.err` output and appends it to a rolling file. - -The file is rolled every day at the midnight of the configured timezone. -Old, rolled files are kept for the number of days specified by the `jetty.console-capture.retainDays` property. - -The module properties are: - ----- -include::{JETTY_HOME}/modules/console-capture.mod[tags=documentation] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-deploy.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-deploy.adoc deleted file mode 100644 index 7ab8abd7e042..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-deploy.adoc +++ /dev/null @@ -1,33 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-deploy]] -===== Module `deploy` - -The `deploy` module provides the deployment feature through a `DeploymentManager` component that watches a directory for changes (see xref:og-deploy[how to deploy web applications] for more information). - -Files or directories added in this monitored directory cause the `DeploymentManager` to deploy them as web applications; updating files already existing in this monitored directory cause the `DeploymentManager` to re-deploy the correspondent web application; removing files in this monitored directory cause the `DeploymentManager` to undeploy the correspondent web application (see also xref:og-deploy-rules[here] for more information). - -The module file is `$JETTY_HOME/modules/deploy.mod`: - ----- -include::{JETTY_HOME}/modules/deploy.mod[] ----- - -Among the configurable properties, the most relevant are: - -`jetty.deploy.monitoredDir`:: -The name of the monitored directory. -`jetty.deploy.scanInterval`:: -The scan period in seconds, that is how frequently the `DeploymentManager` wakes up to scan the monitored directory for changes. -Setting `jetty.deploy.scanInterval=0` disabled _hot_ deployment so that only static deployment will be possible (see also xref:og-deploy-hot-static[here] for more information). diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http-forwarded.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http-forwarded.adoc deleted file mode 100644 index 7f70c5a95968..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http-forwarded.adoc +++ /dev/null @@ -1,23 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-http-forwarded]] -===== Module `http-forwarded` - -The `http-forwarded` module provides support for processing the `Forwarded` HTTP header (defined in link:https://tools.ietf.org/html/rfc7239[RFC 7239]) and the now obsoleted `X-Forwarded-*` HTTP headers. - -The module properties are: - ----- -include::{JETTY_HOME}/modules/http-forwarded.mod[tags=documentation] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http.adoc deleted file mode 100644 index 395bbb2816cf..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http.adoc +++ /dev/null @@ -1,67 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-http]] -===== Module `http` - -The `http` module provides the clear-text connector and support for the clear-text HTTP/1.1 protocol, and depends on the xref:og-module-server[`server` module]. - -The module properties to configure the clear-text connector are: - ----- -include::{JETTY_HOME}/modules/http.mod[tags=documentation] ----- - -Among the configurable properties, the most relevant are: - -`jetty.http.port`:: -The network port that Jetty listens to for clear-text HTTP/1.1 connections -- default `8080`. -`jetty.http.idleTimeout`:: -The amount of time a connection can be idle (i.e. no bytes received and no bytes sent) until the server decides to close it to save resources -- default `30` seconds. -`jetty.http.acceptors`:: -The number of threads that compete to accept connections -- default 1. Use -1 to let the accept heuristic decides the value; the current heuristic calculates a value based on the number of cores). -Refer to xref:og-module-http-acceptors[this section] for more information about acceptor threads. -`jetty.http.selectors`:: -The number of NIO selectors (with an associated thread) that manage connections -- default -1 (i.e. a select heuristic decides the value; the current heuristic calculates a value based on the number of cores). - -[[og-module-http-acceptors]] -====== Configuration of Acceptors - -Accepting connections from remote clients may be configured as a blocking operation, or a non-blocking operation. - -When accepting connections is configured as a blocking operation (the number of acceptors is greater than zero), a thread is blocked in the `accept()` call until a connection is accepted, and other acceptor threads (if any) are blocked on the lock acquired by the accepting thread just before the `accept()` call. - -When the accepting thread accepts a connection, it performs a little processing of the just accepted connection, before forwarding it to other components. - -During this little processing other connections may be established; if there is only one accepting thread, the newly established connections are waiting for the accepting thread to finish the processing of the previously accepted connection and call again `accept()`. - -Servers that manage a very high number of connections that may (naturally) come and go, or that handle inefficient protocols that open and close connections very frequently (such as HTTP/1.0) may benefit of an increased number of acceptor threads, so that when one acceptor thread processes a just accepted connection, another acceptor thread can immediately take over accepting connections. - -When accepting connections is configured as a non-blocking operation (the number of acceptors is zero), then the server socket is set in non-blocking mode and added to a NIO selector. -In this way, no dedicated acceptor threads exist: the work of accepting connections is performed by the selector thread. - -[[og-module-http-selectors]] -====== Configuration of Selectors - -Performing a NIO `select()` call is a blocking operation, where the selecting thread is blocked in the `select()` call until at least one connection is ready to be processed for an I/O operation. -There are 4 I/O operations: ready to be accepted, ready to be connected, ready to be read and ready to be written. - -A single NIO selector can manage thousands of connections, with the assumption that not many of them will be ready at the same time. - -For a single NIO selector, the ratio between the average number of selected connections over the total number of connections for every `select()` call depends heavily on the protocol but also on the application. - -Multiplexed TCP protocols such as HTTP/2 tend to be busier than duplex protocols such as HTTP/1.1, leading to a higher ratio. - -REST applications that exchange many little JSON messages tend to be busier than file server applications, leading to a higher ratio. - -The higher the ratio, the higher the number of selectors you want to have, compatibly with the number of cores -- there is no point in having 64 selector threads on a single core hardware. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http2.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http2.adoc deleted file mode 100644 index c9ae5297e448..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http2.adoc +++ /dev/null @@ -1,32 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-http2]] -===== Module `http2` - -The `http2` module enables support for the secure HTTP/2 protocol. - -The module properties are: - ----- -include::{JETTY_HOME}/modules/http2.mod[tags=documentation] ----- - -// tag::rate-control[] -The `jetty.http2.rateControl.maxEventsPerSecond` property controls the number of "bad" or "unnecessary" frames that a client may send before the server closes the connection (with code link:https://tools.ietf.org/html/rfc7540#section-7[`ENHANCE_YOUR_CALM`]) to avoid a denial of service. - -For example, an attacker may send empty `SETTINGS` frames to a server in a tight loop. -While the `SETTINGS` frames don't change the server configuration and each of them is somehow harmless, the server will be very busy processing them because they are sent by the attacker one after the other, causing a CPU spike and eventually a denial of service (as all CPUs will be busy processing empty `SETTINGS` frames). - -The same attack may be performed with `PRIORITY` frames, empty `DATA` frames, `PING` frames, etc. -// end::rate-control[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http2c.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http2c.adoc deleted file mode 100644 index 215dd94673be..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http2c.adoc +++ /dev/null @@ -1,25 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-http2c]] -===== Module `http2c` - -The `http2c` module enables support for the clear-text HTTP/2 protocol. - -The module properties are: - ----- -include::{JETTY_HOME}/modules/http2c.mod[tags=documentation] ----- - -include::module-http2.adoc[tags=rate-control] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http3.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http3.adoc deleted file mode 100644 index 21655d4cd84e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-http3.adoc +++ /dev/null @@ -1,23 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-http3]] -===== Module `http3` - -The `http3` module enables support for the HTTP/3 protocol. - -The module properties are: - ----- -include::{JETTY_HOME}/modules/http3.mod[tags=documentation] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-https.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-https.adoc deleted file mode 100644 index f88e8838f248..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-https.adoc +++ /dev/null @@ -1,23 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-https]] -===== Module `https` - -The `https` module provides the HTTP/1.1 protocol to the xref:og-module-ssl[`ssl` module]. - -The module file is `$JETTY_HOME/modules/https.mod`: - ----- -include::{JETTY_HOME}/modules/https.mod[] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-jmx-remote.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-jmx-remote.adoc deleted file mode 100644 index 89c78d9be8da..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-jmx-remote.adoc +++ /dev/null @@ -1,39 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-jmx-remote]] -===== Module `jmx-remote` - -The `jmx-remote` module provides remote access to JMX clients. - -The module properties to configure remote JMX connector are: - ----- -include::{JETTY_HOME}/modules/jmx-remote.mod[tags=documentation] ----- - -The system property `java.rmi.server.hostname` is specified with the usual notation, prepending a `-D` in front of the system property name. - -The system property `java.rmi.server.hostname` is uncommented because it is necessary in the default configuration -- most systems do not have the local name resolution configured properly for remote access. - -As an example, in a Linux machine named `beryl`, the `/etc/hosts` file may contain these entries: - ----- -127.0.0.1 localhost -127.0.1.1 beryl ----- - -If the system property `java.rmi.server.hostname` is not specified, the RMI implementation uses the host name `beryl` to figure out the IP address to store in the RMI stub, in this case `127.0.1.1`. -However, we the RMI server is configured to bind to `localhost`, i.e. `127.0.0.1`. - -If the system property `java.rmi.server.hostname` is not specified, the RMI client will try to connect to `127.0.1.1` (because that's what in the RMI stub) and fail because nothing is listening on that address. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-requestlog.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-requestlog.adoc deleted file mode 100644 index 8e92043f3455..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-requestlog.adoc +++ /dev/null @@ -1,27 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-requestlog]] -===== Module `requestlog` - -The `requestlog` module provides HTTP request/response logging in the standard link:https://en.wikipedia.org/wiki/Common_Log_Format[NCSA format], or in a custom format of your choice. - -The module properties are: - ----- -include::{JETTY_HOME}/modules/requestlog.mod[tags=documentation] ----- - -The property `jetty.requestlog.formatString` can be customized using format codes. - -include::javadoc[file=jetty-server/src/main/java/org/eclipse/jetty/server/CustomRequestLog.java,xsl=src/main/asciidoc/operations-guide/modules/module-requestlog.xsl,tags=documentation,replace="\|,\\|"] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-requestlog.xsl b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-requestlog.xsl deleted file mode 100644 index 0d3d3bf1d28a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-requestlog.xsl +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - . - - [cols="1,3a"] - |=== - - - |=== - - - | - - - - - - - | - - - - - - - - - - - - - - ``:: - - - - - - - `` - - diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-server.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-server.adoc deleted file mode 100644 index da9e44083e4f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-server.adoc +++ /dev/null @@ -1,132 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-server]] -===== Module `server` - -The `server` module provides generic server support, and configures generic HTTP properties that apply to all HTTP protocols, the scheduler properties and the server specific properties. - -The `server` module depends on the xref:og-module-threadpool[`threadpool` module], the xref:og-module-bytebufferpool[`bytebufferpool` module] and the xref:og-module-logging[`logging` module]. - -[NOTE] -==== -The `server` module configures the shared parameters for generic HTTP handling, but does not enable any specific network protocol. You have to explicitly enable the protocols you want to support by enabling, for example, the xref:og-module-http[`http` module] for clear-text HTTP/1.1 support, or the xref:og-module-http2[`http2` module] for secure HTTP/2 support, etc. - -See also the xref:og-protocols[protocols section] for more information about the supported protocols. -==== - -[[og-module-server-http-config]] -====== HTTP Configuration Properties - -The module properties to configure generic HTTP properties are listed below. Mostly they frequently apply to HTTP/1, HTTP/2 and HTTP/3, but some parameters are version specific: - ----- -include::{JETTY_HOME}/modules/server.mod[tags=documentation-http-config] ----- - -Among the configurable properties, the most relevant are: - -`jetty.httpConfig.headerCacheSize`:: -The header cache is used when parsing HTTP/1 to more efficiently handle fields that are repeated in every request on a connection. If the server does not receive persistent connection or infrequent repeated fields, then there may be a performance gain in reducing the cache size. If large fields are frequently repeated, then a large cache may be beneficial. - -`jetty.httpConfig.delayDispatchUntilContent`:: -It is not uncommon for the network packets containing a request header to arrive before packets that contain the data of any request body. In such cases it may be beneficial for overall performance to delay dispatching the request to be handled until the first data packet arrives, as this may avoid blocking the handling thread. However, if minimum latency for receiving the request without content is important, then this parameter can be set to false. - -`jetty.httpConfig.sendServerVersion`:: -Whether you want to send the `Server` header in every HTTP response: -+ -[source,screen,subs=normal] ----- -HTTP/1.1 200 OK -Content-Length: 0 -Server: Jetty({version}) ----- - -[[og-module-server-config]] -====== Server Configuration Properties - -The module properties to configure the Jetty server are: - ----- -include::{JETTY_HOME}/modules/server.mod[tags=documentation-server-config] ----- - -Among the configurable properties, the most relevant are: - -`jetty.server.dumpAfterStart`:: -Whether to perform a `Server.dump()` operation after the `Server` has started. -The output of the dump operation is sent to `System.err`. -See also the xref:og-troubleshooting-dump[Jetty Server Dump] section for more information. - -`jetty.server.dumpBeforeStop`:: -Whether to perform a `Server.dump()` operation before the `Server` stops. -The output of the dump operation is sent to `System.err`. -See also the xref:og-troubleshooting-dump[Jetty Server Dump] section for more information. - -`jetty.server.stopAtShutdown`:: -Whether to call `Server.stop()` through a JVM shutdown hook when the JVM exits. - -[[og-module-server-compliance]] -====== Server Compliance Properties - -The Jetty server strives to keep up with the latest link:https://en.wikipedia.org/wiki/Request_for_Comments[IETF RFC]s for compliance with internet specifications, which are periodically updated. When possible, Jetty will support backwards compatibility by providing compliance modes that can be configured to allow violations of the current specifications that may have been allowed in obsoleted specifications. -The module properties to configure the Jetty server compliance are: - ----- -include::{JETTY_HOME}/modules/server.mod[tags=documentation-server-compliance] ----- - -Among the configurable properties, the most relevant are: - -`jetty.httpConfig.compliance`:: -Configures the compliance to HTTP specifications. -The value could be: - -* One of the predefined link:{javadoc-url}/org/eclipse/jetty/http/HttpCompliance.html[`HttpCompliance`] constants, such as `RFC7230` or `RFC2616`. -For example: `jetty.httpConfig.compliance=RFC2616`. -* A comma-separated list of violations to allow or forbid, as specified by the link:{javadoc-url}/org/eclipse/jetty/http/HttpCompliance.html#from(java.lang.String)[`HttpCompliance.from(String)`] method. -For example, `jetty.httpConfig.compliance=RFC7230,MULTIPLE_CONTENT_LENGTHS` means that the HTTP compliance is that defined by `RFC7230`, but also allows the `HttpCompliance.Violation.MULTIPLE_CONTENT_LENGTHS`, so that requests that have multiple `Content-Length` headers are accepted (they would be rejected when using just `HttpCompliance.RFC7230`). -+ -For more information about `HttpCompliance` see also xref:{prog-guide}#pg-server-compliance-http[this section]. - -`jetty.httpConfig.uriCompliance`:: -Configures the compliance to URI specifications. -The value could be: - -* One of the predefined link:{javadoc-url}/org/eclipse/jetty/http/UriCompliance.html[`UriCompliance`] constants, such as `DEFAULT` or `RFC3986`. -For example: `jetty.httpConfig.compliance=RFC3986`. -* A comma-separated list of violations to allow or forbid, as specified by the link:{javadoc-url}/org/eclipse/jetty/http/UriCompliance.html#from(java.lang.String)[`UriCompliance.from(String)`] method. -For example, `jetty.httpConfig.uriCompliance=RFC3986,-AMBIGUOUS_PATH_SEPARATOR` means that the URI compliance is that defined by `RFC3986`, but also does not allow the `UriCompliance.Violation.AMBIGUOUS_PATH_SEPARATOR`, so that requests that have URIs such as `/foo/bar%2Fbaz` (where `%2F` is the URL-encoded `/` character) are rejected (they would be accepted when using just `UriCompliance.RFC3986`). -+ -For more information about `UriCompliance` see also xref:{prog-guide}#pg-server-compliance-uri[this section]. - -`jetty.httpConfig.requestCookieCompliance`:: -`jetty.httpConfig.responseCookieCompliance`:: -Configures the compliance to HTTP cookie specifications. -The value could be: - -* One of the predefined link:{javadoc-url}/org/eclipse/jetty/http/CookieCompliance.html[`CookieCompliance`] constants, such as `RFC6265`. -For example: `jetty.httpConfig.compliance=RFC6265`. -* A comma-separated list of violations to allow or forbid, as specified by the link:{javadoc-url}/org/eclipse/jetty/http/CookieCompliance.html#from(java.lang.String)[`CookieCompliance.from(String)`] method. -For example, `jetty.httpConfig.requestCookieCompliance=RFC6265,-RESERVED_NAMES_NOT_DOLLAR_PREFIXED` means that the cookie compliance is that defined by `RFC6265`, but also does not allow the `CookieCompliance.Violation.RESERVED_NAMES_NOT_DOLLAR_PREFIXED`, so that requests that have cookie headers such as `Cookie: $foo=bar` are rejected (they would be accepted when using just `CookieCompliance.RFC6265`). -+ -For more information about `CookieCompliance` see also xref:{prog-guide}#pg-server-compliance-cookie[this section]. - -[[og-module-scheduler-config]] -====== Server Scheduler Configuration Properties - -The module properties to configure the Jetty server scheduler are: - ----- -include::{JETTY_HOME}/modules/server.mod[tags=documentation-scheduler-config] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-ssl-reload.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-ssl-reload.adoc deleted file mode 100644 index 6e65d4e95cac..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-ssl-reload.adoc +++ /dev/null @@ -1,24 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-ssl-reload]] -===== Module `ssl-reload` - -The `ssl-reload` module provides a periodic scanning of the directory where the KeyStore file resides. -When the scanning detects a change to the KeyStore file, the correspondent `SslContextFactory.Server` component is reloaded with the new KeyStore configuration. - -The module properties are: - ----- -include::{JETTY_HOME}/modules/ssl-reload.mod[tags=documentation] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-ssl.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-ssl.adoc deleted file mode 100644 index 75bcf793daf8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-ssl.adoc +++ /dev/null @@ -1,65 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-ssl]] -===== Module `ssl` - -The `ssl` module provides the secure connector, and allows you to configure the KeyStore properties and the TLS parameters, and depends on the xref:og-module-server[`server` module]. - -[[og-module-ssl-connector]] -====== Secure Connector Properties - -The module properties to configure the secure connector are: - ----- -include::{JETTY_HOME}/modules/ssl.mod[tags=documentation-connector] ----- - -Among the configurable properties, the most relevant are: - -`jetty.ssl.port`:: -The network port that Jetty listens to for secure connections -- default `8443`. -`jetty.ssl.idleTimeout`:: -The amount of time a connection can be idle (i.e. no bytes received and no bytes sent) until the server decides to close it to save resources -- default `30000` milliseconds. -`jetty.ssl.acceptors`:: -The number of threads that compete to accept connections -- default 1. Use -1 to let the accept heuristic decides the value; the current heuristic calculates a value based on the number of cores). -Refer to xref:og-module-http-acceptors[this section] for more information about acceptor threads. -`jetty.ssl.selectors`:: -The number of NIO selectors (with an associated thread) that manage connections -- default -1 (i.e. a select heuristic decides the value; the current heuristic calculates a value based on the number of cores). -Refer to xref:og-module-http-selectors[this section] for more information about selector threads. - -The module properties to configure the KeyStore and TLS parameters are: - ----- -include::{JETTY_HOME}/modules/ssl.mod[tags=documentation-ssl-context] ----- - -[[og-module-ssl-keystore-tls]] -====== KeyStore Properties and TLS Properties - -Among the configurable properties, the most relevant are: - -`jetty.sslContext.keyStorePath`:: -The KeyStore path on the file system, either an absolute path or a relative path to `$JETTY_BASE` -- defaults to `$JETTY_BASE/etc/keystore.p12`. -`jetty.sslContext.keyStorePassword`:: -The KeyStore password, which you want to explicitly configure. -The password may be obfuscated with the xref:og-password[Jetty Password Tool]. - -If you need to configure client certificate authentication, you want to configure one of these properties (they are mutually exclusive): - -`jetty.sslContext.needClientAuth`:: -Whether client certificate authentication should be required. -`jetty.sslContext.wantClientAuth`:: -Whether client certificate authentication should be requested. - -If you configure client certificate authentication, you need to configure and distribute a client KeyStore as explained in xref:og-keystore-client-authn[this section]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-test-keystore.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-test-keystore.adoc deleted file mode 100644 index 868988a11db0..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-test-keystore.adoc +++ /dev/null @@ -1,27 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-test-keystore]] -===== Module `test-keystore` - -The `test-keystore` module creates on-the-fly a KeyStore containing a self-signed certificate for domain `localhost`. -The KeyStore file is automatically deleted when the JVM exits, and re-created when you restart Jetty, to enforce the fact that it is a _test_ KeyStore that should not be reused if not for testing. - -The module file is `$JETTY_HOME/modules/test-keystore.mod`: - ----- -include::{JETTY_HOME}/modules/test-keystore.mod[] ----- - -Note how properties `jetty.sslContext.keyStorePath` and `jetty.sslContext.keyStorePassword` are configured, only if not already set (via the `?=` operator), directly in the module file, rather than in a `+*.ini+` file. -This is done to avoid that these properties accidentally overwrite a real KeyStore configuration. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool-virtual-preview.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool-virtual-preview.adoc deleted file mode 100644 index 33230257b6ba..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool-virtual-preview.adoc +++ /dev/null @@ -1,41 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-threadpool-virtual-preview]] -===== Module `threadpool-virtual-preview` - -The `threadpool-virtual-preview` module allows you to configure the server-wide thread pool, similarly to what you can do with the xref:og-module-threadpool[`threadpool`] Jetty module, but also specify to use virtual threads, introduced as a preview feature in Java 19 and in Java 20. - -CAUTION: Only use this module if you are using Java 19 or Java 20. -If you are using Java 21 or later, use the xref:og-module-threadpool-virtual[`threadpool-virtual`] Jetty module instead. - -NOTE: To enable preview features, this module needs to specify the `+--enable-preview+` command line option using the xref:og-modules-directive-exec[[exec\] directive], and as such it will fork another JVM. - -Refer to the xref:og-module-threadpool[`threadpool`] Jetty module for the general features provided by that Jetty module that also this Jetty module provides. - -The module properties to configure the thread pool are: - ----- -include::{JETTY_HOME}/modules/threadpool-virtual-preview.mod[tags=documentation] ----- - -The specific properties to configure virtual threads are: - -`jetty.threadPool.virtual.namePrefix`:: -The name prefix to use for the virtual thread names. - -`jetty.threadPool.virtual.allowSetThreadLocals`:: -Whether virtual threads are allowed to set thread locals. - -`jetty.threadPool.virtual.inheritInheritableThreadLocals`:: -Whether virtual threads inherit the values of `InheritableThreadLocal` variables. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool-virtual.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool-virtual.adoc deleted file mode 100644 index e12fdef5e219..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool-virtual.adoc +++ /dev/null @@ -1,36 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-threadpool-virtual]] -===== Module `threadpool-virtual` - -The `threadpool-virtual` module allows you to configure the server-wide thread pool, similarly to what you can do with the xref:og-module-threadpool[`threadpool`] Jetty module, but also specify to use virtual threads, introduced as an official feature since Java 21. - -CAUTION: Only use this module if you are using Java 21 or later. -If you are using Java 19 or Java 20, use the xref:og-module-threadpool-virtual-preview[`threadpool-virtual-preview`] Jetty module instead. - -Refer to the xref:og-module-threadpool[`threadpool`] Jetty module for the general features provided by that Jetty module that also this Jetty module provides. - -The module properties to configure the thread pool are: - ----- -include::{JETTY_HOME}/modules/threadpool-virtual.mod[tags=documentation] ----- - -The specific properties to configure virtual threads are: - -`jetty.threadPool.virtual.namePrefix`:: -The name prefix to use for the virtual thread names. - -`jetty.threadPool.virtual.inheritInheritableThreadLocals`:: -Whether virtual threads inherit the values of `InheritableThreadLocal` variables. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool.adoc deleted file mode 100644 index 63b3b142227e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-threadpool.adoc +++ /dev/null @@ -1,49 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-threadpool]] -===== Module `threadpool` - -The `threadpool` module allows you to configure the server-wide thread pool. - -The thread pool creates threads on demand up to `maxThreads`, and idles them out if they are not used. - -Since Jetty uses the thread pool internally to execute critical tasks, it is not recommended to constrain the thread pool to small values of `maxThreads` with the purpose of limiting HTTP request concurrency, as this could very likely cause a server lockup when Jetty needs to run a critical task but there are no threads available. -Start with the default value of `maxThreads`, and tune for larger values if needed. - -The module properties to configure the thread pool are: - ----- -include::{JETTY_HOME}/modules/threadpool.mod[tags=documentation] ----- - -Among the configurable properties, the most relevant are: - -`jetty.threadPool.namePrefix`:: -The name prefix to use for the thread names. - -`jetty.threadPool.detailedDump`:: -Whether the thread pool should dump the whole stack trace of each thread, or just the topmost stack frame -- defaults to `false`. - -`jetty.threadPool.idleTimeout`:: -The time, in milliseconds, after which an idle thread is released from the pool -- defaults to 60000, i.e. 60 seconds. - -`jetty.threadPool.maxThreads`:: -The max number of threads pooled by the thread pool -- defaults to 200. - -If you want to use virtual threads, introduced as a preview feature in Java 19 and Java 20, and become an official feature since Java 21, use the following modules: - -* The xref:og-module-threadpool-virtual[`threadpool-virtual`] Jetty module for Java 21 or later. -* The xref:og-module-threadpool-virtual-preview[`threadpool-virtual-preview`] Jetty module for Java 19 and Java 20. - -See also the xref:og-server-threadpool[section about configuring the thread pool]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-well-known.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-well-known.adoc deleted file mode 100644 index d41ffbdef270..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/module-well-known.adoc +++ /dev/null @@ -1,29 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-module-well-known]] -===== Module `well-known` - -The `well-known` Jetty module creates a `ResourceHandler` deployed at the `/.well-known` context path which serves files from a directory. -By default, the directory created at `$JETTY_BASE/.well-known` is used, but it can be configured from `well-known.ini` to anywhere in the filesystem. -Note that the `.well-known` directory may be seen as a hidden directory by the filesystem. - -The concept of well-known URIs has been defined in link:https://datatracker.ietf.org/doc/html/rfc5785[RFC5785]. -This module can be used for things like the automatic renewal of link:https://letsencrypt.org/[Let's Encrypt] certificates. -See link:https://www.iana.org/assignments/well-known-uris/well-known-uris.xhtml[IANA Well-Known URIs] for more possible examples of how this can be used. - -The module properties are: - ----- -include::{JETTY_HOME}/modules/well-known.mod[tags=documentation] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules-custom.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules-custom.adoc deleted file mode 100644 index 3dc63f663e8b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules-custom.adoc +++ /dev/null @@ -1,238 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-modules-custom]] -==== Custom Jetty Modules - -In addition to the modules that come packaged with Jetty, you can create your own custom modules. - -NOTE: Make sure you have read the xref:og-modules[Jetty modules section] if you are not familiar with the concepts used in this section. - -Custom modules can be used for a number of reasons -- they can extend Jetty features, or add new features, or make additional libraries available to the server, etc. - -[[og-modules-custom-modify]] -===== Modifying an Existing Module - -The standard Jetty modules typically come with a number of configurable properties that can be easily customized without the need of writing a custom module. - -However, there may be cases where the customization is more complex than a simple property, and a custom module is necessary. - -For example, let's assume that you want to modify the order of the TLS cipher suites offered by the server when a client connects, using the link:https://www.openssl.org/docs/man1.1.0/man1/ciphers.html[OpenSSL cipher list format]. - -The Jetty class that handles the TLS configuration is `SslContextFactory`, and it already has a method `setCipherComparator(Comparator)`; however, you need to pass your custom implementation, which cannot be represented with a simple module property. - -The `SslContextFactory` component is already allocated by the standard Jetty module `ssl`, so what you need to do is the following: - -* Write the custom cipher `Comparator` and package it into a `+*.jar+` file (exercise left to reader). -* Write a custom Jetty XML file that calls the `SslContextFactory.setCipherComparator(Comparator)` method. -* Write a custom Jetty module file that depends on the standard `ssl` module. - -Start with the custom Jetty XML file, `$JETTY_BASE/etc/custom-ssl.xml`: - -.custom-ssl.xml -[source,xml] ----- - - - - - - - - - ECDH+AESGCM:ECDH+AES256:!aNULL:!MD5:!DSS:!ADH - - - - - - ----- -<1> Reference the existing `SslContextFactory` object created by the standard `ssl` module using its `id`. -<2> Call the `setCipherComparator()` method. -<3> Instantiate your custom cipher comparator. -<4> Pass to the constructor the ordering string in OpenSSL format, reading it from the module property `com.acme.ssl.cipherList`. - -CAUTION: The cipher list used above may not be secure -- it's just an example. - -Then write your custom module in the `$JETTY_BASE/modules/custom-ssl.mod` file: - -.custom-ssl.mod -[source,subs=verbatim] ----- -[description] -Customizes the standard ssl module. - -[tags] <1> -acme - -[depends] <2> -ssl - -[lib] <3> -lib/custom-cipher-comparator.jar - -[xml] <4> -etc/custom-ssl.xml - -[ini-template] <5> -## The cipher list in OpenSSL format. -# com.acme.ssl.cipherList=ECDH+AESGCM:ECDH+AES256:!aNULL:!MD5:!DSS:!ADH - ----- -<1> A tag that characterizes this custom module (see xref:og-modules-directive-tags[here]). -<2> This custom module depends on the standard `ssl` module. -<3> The custom cipher comparator class is compiled and packaged into this `+*.jar+` file. -<4> The custom Jetty XML file from above. -<5> The text that will be copied in the `custom-ssl.ini` file when this custom module will be enabled. - -Now you can xref:og-start-configure-enable[enable] the custom module with the following command issued from the `$JETTY_BASE` directory: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=https,custom-ssl ----- - -The command above will produce the following `$JETTY_BASE` directory structure: - -[source,subs=normal] ----- -$JETTY_BASE -├── etc -│ └── custom-ssl.xml -├── modules -│ └── custom-ssl.mod -├── resources -│ └── jetty-logging.properties -└── start.d - ├── https.ini - └── ##custom-ssl.ini## ----- - -In the custom XML file you have used a custom module property to parametrize your custom cipher comparator. -This custom module property was then referenced in the `[ini-template]` section of the custom module file, so that when the custom module is enabled, a correspondent `custom-ssl.ini` file is created. - -In this way, updating the cipher list won't require you to update the XML file, but just the `custom-ssl.ini` file. - -[[og-modules-custom-create]] -===== Creating a New Module - -In the cases where you need to enhance Jetty with a custom functionality, you can write a new Jetty module that provides it. - -For example, let's assume that you need to add a custom auditing component that integrates with the auditing tools used by your company. -This custom auditing component should measure the HTTP request processing times and record them (how they are recorded is irrelevant here -- could be in a local log file or sent via network to an external service). - -The Jetty libraries already provide a way to measure HTTP request processing times via xref:{prog-guide}#pg-server-http-channel-events[`HttpChannel` events]: you write a custom component that implements the `HttpChannel.Listener` interface and add it as a bean to the server `Connector` that receives the HTTP requests. - -The steps to create a Jetty module are similar to those necessary to xref:og-modules-custom-modify[modify an existing module]: - -* Write the auditing component and package it into a `+*.jar+` file. -* Write a custom Jetty XML file that wires the auditing component to the `ServerConnector`. -* Write a custom Jetty module file that puts everything together. - -Let's start with the auditing component, sketched below: - -[source,java] ----- -package com.acme.audit; - -public class AuditingHttpChannelListener implements HttpChannel.Listener { - // Auditing is implemented here. -} ----- - -Let's assume that this class is compiled and packaged into `acme-audit.jar`, and that it has a dependency on `acme-util.jar`. -Both `+*.jar+` files will be put in the `$JETTY_BASE/lib/` directory. - -Next, let's write the Jetty XML file that wires the auditing component to the `ServerConnector`, `$JETTY_BASE/etc/acme-audit.xml`: - -.acme-audit.xml -[source,xml,subs=verbatim,options=nowrap] ----- - - - - - - - - - - - - - - - - ----- -<1> Reference the existing clear-text HTTP `ServerConnector` object created by the standard `http` module. -<2> Call `addBean()` on the `ServerConnector` to wire the auditing component. -<3> Instantiate the auditing component. -<4> Configure the auditing component with a property. - -The last step is to create the custom Jetty module file for the auditing component, `$JETTY_BASE/modules/acme-audit.mod`: - -.acme-audit.mod ----- -[description] -Adds auditing to the clear-text HTTP connector - -[tags] <1> -acme -audit - -[depends] <2> -http - -[libs] <3> -lib/acme-audit.jar -lib/acme-util.jar - -[xml] <4> -etc/acme-audit.xml - -[ini-template] <5> -## An auditing property. -# com.acme.audit.some.property=42 ----- -<1> The tags that characterize this custom module (see xref:og-modules-directive-tags[here]). -<2> This custom module depends on the standard `http` module. -<3> The `+*.jar+` files that contains the custom auditing component, and its dependencies. -<4> The custom Jetty XML file from above. -<5> The text that will be copied in the `acme-audit.ini` file when this custom module will be enabled. - -Now you can xref:og-start-configure-enable[enable] the custom auditing module with the following command issued from the `$JETTY_BASE` directory: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=http,acme-audit ----- - -The command above will produce the following `$JETTY_BASE` directory structure: - -[source,subs=normal] ----- -$JETTY_BASE -├── etc -│ └── acme-audit.xml -├── modules -│ └── acme-audit.mod -├── resources -│ └── jetty-logging.properties -└── start.d - ├── http.ini - └── ##acme-audit.ini## ----- - -Enabling the custom auditing component will create the `$JETTY_BASE/start.d/acme-audit.ini` module configuration file that you can edit to configure auditing properties. - -// TODO: it's possible to have an *.ini file without a correspondent *.mod -- it's just a list of command line arguments, so make an example of a custom connector with a custom-connector.ini and XML file, but no module file. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules-standard.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules-standard.adoc deleted file mode 100644 index e4da39d3500a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules-standard.adoc +++ /dev/null @@ -1,36 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-modules-standard]] -==== Standard Modules - -include::module-alpn.adoc[] -include::module-bytebufferpool.adoc[] -include::module-console-capture.adoc[] -include::module-deploy.adoc[] -include::module-http.adoc[] -include::module-http2.adoc[] -include::module-http2c.adoc[] -include::module-http3.adoc[] -include::module-http-forwarded.adoc[] -include::module-https.adoc[] -include::module-jmx-remote.adoc[] -include::module-requestlog.adoc[] -include::module-server.adoc[] -include::module-ssl.adoc[] -include::module-ssl-reload.adoc[] -include::module-test-keystore.adoc[] -include::module-threadpool.adoc[] -include::module-threadpool-virtual.adoc[] -include::module-threadpool-virtual-preview.adoc[] -include::module-well-known.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules.adoc deleted file mode 100644 index a2a0211f1a2d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/modules/modules.adoc +++ /dev/null @@ -1,494 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-modules]] -=== Jetty Modules - -A Jetty _module_ provides one or more Java components that work together to implement one or more features. -Such features could be listening for clear-text HTTP/1.1 requests, exposing Jetty components to JMX, provide hot-deployment of web applications, etc. - -Every Jetty feature is provided by a Jetty module. - -A Jetty module is defined in a `.mod` file, where `` is the module name (see also the xref:og-modules-names[section about module names]). - -Jetty module files are read from the typical xref:og-start-configure[configuration source directories], under the `modules/` subdirectory; from higher priority to lower priority: - -* The `$JETTY_BASE/modules/` directory. -* If a directory is specified with the `--include-jetty-dir` option, its `modules/` subdirectory. -* The `$JETTY_HOME/modules/` directory. - -The standard Jetty modules that Jetty provides out-of-the-box are under `$JETTY_HOME/modules/`. - -xref:og-modules-custom[Custom Jetty modules] should be put under `$JETTY_BASE/modules/`. - -[[og-modules-names]] -==== Module Names - -A Jetty module has a unique name. -The module name is by default derived from the file name, so module file `acme.mod` identifies a module named `acme`. - -However, a module file may specify a xref:og-modules-directive-provides[+[provides]+] directive for a _virtual_ module, so that many modules may provide a different implementation for the same feature. - -For example, among the standard modules provided by Jetty, the `server` module depends on the `logging` module, but there is no correspondent `logging.mod` file. - -However, the `logging-jetty.mod` file has, among others, this section: - -.logging-jetty.mod ----- -[provides] -logging|default ----- - -This section means that the `logging-jetty.mod` file provides the virtual module `logging`, and it is the default provider. - -The `logging-log4j2.mod` file has a similar section: - -.logging-log4j2.mod ----- -[provides] -logging ----- - -If there are no enabled modules that provide the `logging` virtual module, either explicitly or transitively, then the default provider is used, in this case `logging-jetty.mod`. - -Otherwise, a module that provides the `logging` virtual module is explicitly or transitively enabled, and the default provider is not used. - -[[og-modules-components]] -==== Module Components - -A Jetty module may provide one or more Java components that implement a feature. -These Java components are nothing more than regular Java classes that are instantiated and configured via xref:og-xml[Jetty XML] files. - -The Jetty XML file of a Jetty module may instantiate and assemble together its own components, or reference existing components from other Jetty modules to enhance or reconfigure them. - -The Jetty module's XML files are read from the typical xref:og-start-configure[configuration source directories], under the `etc/` subdirectory; from higher priority to lower priority: - -* The `$JETTY_BASE/etc/` directory. -* If a directory is specified with the `--include-jetty-dir` option, its `etc/` subdirectory. -* The `$JETTY_HOME/etc/` directory. - -The standard Jetty modules XML files that Jetty provides out-of-the-box are under `$JETTY_HOME/etc/`. - -For example, a Jetty XML file that allocates Jetty's `QueuedThreadPool` could be as simple as: - -[source,xml] -.jetty-threadpool.xml ----- - - - - - - - - - ----- - -Note how the Jetty XML file above is allocating (with the `` element) a `QueuedThreadPool` instance, giving it the unique `id` of `threadPool` (so that other modules can reference it, if they need to). -It is then calling the setter method `QueuedThreadPool.setMaxThreads(int)` with the value defined by the xref:og-modules-properties[module property] `jetty.threadPool.maxThreads`; if the property value is not defined, it will have the default value of `256`. - -This is nothing more than Java code in XML format with configurable properties support that can be leveraged by the xref:og-start[Jetty start mechanism]. - -The Jetty module's XML files make easy to instantiate and assemble Java components (just write the equivalent Java code in XML format), and make easy to configure them by declaring module properties that can be easily customized elsewhere (for example, in `+*.ini+` files as described in xref:og-start-configure-enable[this section], or on the command line as described in xref:og-start-start[this section]). - -[IMPORTANT] -==== -Remember that the standard Jetty XML files in `$JETTY_HOME/etc/` should not be modified. - -Even if you need to modify a standard Jetty component, write a new Jetty XML file, save it under `$JETTY_BASE/etc/`, and create a xref:og-modules-custom[custom Jetty module] so that it gets processed when Jetty starts. -==== - -[[og-modules-properties]] -==== Module Properties - -A Jetty module property is declared in the xref:og-modules-components[module XML file(s)] via the `` element. -Modules properties are used to parametrize Jetty components so that you can customize their values when Jetty starts, rather than hard-coding it in the XML files. - -NOTE: You can declare your own properties, but the `+jetty.*+` namespace is reserved. - -A module property can be given a value in a Jetty module `[ini]` section (see xref:og-modules-directive-ini[here]), in a `+*.ini+` file as described in xref:og-start-configure-enable[this section], or on the command line as described in xref:og-start-start[this section]. - -The syntax to specify a property value is the following: - -=:: -Sets the property value unconditionally. -+=:: -Appends the value to the existing value. -This is useful to append a value to properties that accept a comma separated list of values, for example: -+ ----- -jetty.webapp.addServerClasses+=,com.acme ----- -+ -// TODO: check what happens if the property is empty and +=,value is done: is the comma stripped? If so add a sentence about this. -?=:: -Sets the property value only if it is not already set. -This is useful to define default values, for example for "version" properties, where the "version" property can be explicitly configured to a newer version, but if it is not explicitly configured it will have a default version (see also xref:og-start-configure-custom-module[here]). -For example: -+ ----- -conscrypt.version?=2.5.1 -jetty.sslContext.provider?=Conscrypt ----- - -[[og-modules-directives]] -==== Module Directives - -Lines that start with `#` are comments. - -[[og-modules-directive-description]] -===== [description] - -A text that describes the module. - -This text will be shown by the xref:og-start-configure[Jetty start mechanism] when using the `--list-modules` command. - -[[og-modules-directive-tags]] -===== [tags] - -A list of words that characterize the module. - -Modules that have the same tags will be shown by the Jetty start mechanism when using the `--list-modules=` command. - -.example.mod ----- -[tags] -demo -webapp -jsp ----- - -[[og-modules-directive-provides]] -===== [provides] - -A module name with an optional `default` specifier. - -As explained in the xref:og-modules-names[module name section], there can be many module files each providing a different implementation for the same feature. - -The format is: - ----- -[provides] -[|default] ----- - -where the `|default` part is optional and specifies that the module is the default provider. - -[[og-modules-directive-depends]] -===== [depends] - -A list of module names that this module depends on. - -For example, the standard module `http` depends on module `server`. -Enabling the `http` module also enables, transitively, the `server` module, since the `http` module cannot work without the `server` module; when the `server` module is transitively enabled, the modules it depends on will be transitively enabled, and so on recursively. - -The `[depends]` directive establishes a link:https://en.wikipedia.org/wiki/Partially_ordered_set[_partial order_] relationship among modules so that enabled modules can be sorted and organized in a graph. -Circular dependencies are not allowed. - -The order of the enabled modules is used to determine the processing of the configuration, for example the order of processing of the xref:og-modules-directive-files[+[files]+] section, the order of processing of XML files defined in the xref:og-modules-directive-xml[+[xml]+] section, etc. - -[[og-modules-directive-after]] -===== [after] - -This directive indicates that this module is ordered after the listed module names, if they are enabled. - -For example, module `https` is `[after]` module `http2`. -Enabling the `https` module _does not_ enable the `http2` module. - -However, if the `http2` module is enabled (explicitly or transitively), then the `https` module is xref:og-modules-directive-depends[sorted] _after_ the `http2` module. -In this way, you are guaranteed that the `https` module is processed after the `http2` module. - -[[og-modules-directive-before]] -===== [before] - -This directive indicates that this module is ordered before the listed module names, if they are enabled. - -One use of this directive is to create a prerequisite module without the need to modify the `depends` directive of an existing module. -For example, to create a custom `org.eclipse.jetty.server.Server` subclass instance to be used by the standard `server` module, without modifying the existing `server.mod` file nor the `jetty.xml` file that it uses. This can be achieved by creating the `custom-server` xref:og-modules-custom[Jetty custom module]: - -.custom-server.mod ----- -[description] -This module creates a custom Server subclass instance. - -[before] -server - -[xml] -etc/custom-server.xml ----- - -The `custom-server.xml` file is the following: - -.custom-server.xml -[source,xml] ----- - - - - ----- - -The presence of the `[before]` directive in `custom-server.mod` causes the processing of the `custom-server.xml` file to happen before the processing of the standard `jetty.xml` file referenced by the standard `server.mod` Jetty module. - -Thus, the instance assigned to the `Server` identifier is your custom `com.acme.server.CustomJettyServer` instance from the `custom-server.xml` file; this instance is then used while processing the `jetty.xml` file. - -[[og-modules-directive-files]] -===== [files] - -A list of paths (directories and/or files) that are necessary for the module, created or resolved when the module is enabled. - -Each path may be of the following types: - -Path Name:: -A path name representing a file, or a directory if the path name ends with `/`, such as `webapps/`. -The file or directory will be created relative to `$JETTY_BASE`, if not already present. -+ -For example: -+ ----- -[files] -logs/ ----- - -Maven Artifact:: -An URI representing a Maven artifact to be downloaded from Maven Central, if not already present. -Property expansion is supported. -+ -The format is: -+ ----- -[files] -maven:////[/]| ----- -+ -where `` is optional, and `` after the `|` is the path under `$JETTY_BASE` where the downloaded file should be saved. -+ -For example: -+ -[source,options=nowrap] ----- -[files] -maven://org.postgresql/postgresql/${postgresql-version}|lib/postgresql-${postgresql-version}.jar ----- - -BaseHome:: -An URI representing a `$JETTY_HOME` resource to be copied in `$JETTY_BASE`, if not already present. -URIs of this type are typically only used by standard Jetty modules; custom modules should not need to use it. -+ -The format is: -+ ----- -[files] -basehome:| ----- -+ -For example: -+ ----- -[files] -basehome:modules/demo.d/demo-moved-context.xml|webapps/demo-moved-context.xml ----- - -HTTP URL:: - -An `http://` or `https://` URL to be downloaded, if not already present. -+ -The format is: -+ ----- -[files] -| ----- -+ -For example: -+ ----- -[files] -https://acme.com/favicon.ico|webapps/acme/favicon.ico ----- - -[[og-modules-directive-libs]] -===== [libs] - -A list of paths, relative to the xref:og-start-configure[configuration source directories], of `+*.jar+` library files and/or directories that are added to the server class-path (or module-path when xref:og-start-start-jpms[running in JPMS mode]). - -The `[libs]` section if often used in conjunction with the `[files]` section. - -For example: - ----- -[files] -maven://org.postgresql/postgresql/${postgresql-version}|lib/postgresql-${postgresql-version}.jar - -[libs] -lib/postgresql-${postgresql-version}.jar ----- - -The `postgresql-.jar` artifact is downloaded from Maven Central, if not already present, into the `$JETTY_BASE/lib/` directory when the module is enabled. - -When Jetty starts, the `$JETTY_BASE/lib/postgresql-.jar` will be in the server class-path (or module-path). - -[[og-modules-directive-xml]] -===== [xml] - -A list of paths, relative to the xref:og-start-configure[configuration source directories], of Jetty `+*.xml+` files that are passed as program arguments to be processed when Jetty starts (see the xref:og-start-start-xml[section about assembling Jetty components]). - -Jetty XML files are read from the typical xref:og-start-configure[configuration source directories], under the `etc/` subdirectory. -Standard Jetty XML files are under `$JETTY_HOME/etc/`, while custom Jetty XML files are typically under `$JETTY_BASE/etc/`. - -For example: - ----- -[xml] -etc/custom/components.xml ----- - -[[og-modules-directive-ini]] -===== [ini] - -A list of program arguments to pass to the command line when Jetty is started. - -The program arguments may include any command line option (see xref:og-start-reference[here] for the list of command line options), xref:og-modules-properties[module properties] and/or xref:og-modules-components[module XML files]. - -A property defined in the `[ini]` section is available in the `+*.mod+` module file for property expansion, for example: - ----- -[ini] -postgresql-version?=42.2.18 - -[lib] -lib/postgresql-${postgresql-version}.jar ----- - -In the example above, the `[lib]` section contains `${postgresql-version}`, a reference to property `postgresql-version` whose value is defined in the `[ini]` section. -The expression `${}` _expands_ the property replacing the expression with the property value. - -See also the xref:og-start-start-jpms[JPMS section] for additional examples about the `[ini]` section. - -[[og-modules-directive-ini-template]] -===== [ini-template] - -A list of properties to be copied in the `+*.ini+` file generated when xref:og-start-configure-enable[the module is enabled]. - -The list of properties is derived from the xref:og-modules-components[module XML file(s)] that declare them. - -The properties are typically assigned their default value and commented out, so that it is evident which properties have been uncommented and customized with a non-default value. - -[[og-modules-directive-exec]] -===== [exec] - -A list of JVM command line options and/or system properties passed to a forked JVM. - -When the `[exec]` section is present, the JVM running the Jetty start mechanism will fork another JVM, passing the JVM command line options and system properties listed in the `[exec]` sections of the enabled modules. - -This is necessary because JVM options such as `-Xmx` (that specifies the max JVM heap size) cannot be changed in a running JVM. -For an example, see xref:og-start-configure-custom-module-exec[this section]. - -You can avoid that the Jetty start mechanism forks the second JVM, as explained in xref:og-start-configure-dry-run[this section]. - -[[og-modules-directive-jpms]] -===== [jpms] - -A list of JVM command line options related to the Java Module System. - -This section is processed only when Jetty is xref:og-start-start-jpms[started in JPMS mode]. - -The directives are: - -add-modules:: -Equivalent to the JVM option `--add-modules`. -The format is: -+ ----- -[jpms] -add-modules: (,)* ----- -+ -where `module` is a JPMS module name. - -patch-module:: -Equivalent to the JVM option `--patch-module`. -The format is: -+ ----- -[jpms] -patch-module: =(:)* ----- -where `module` is a JPMS module name. - -add-opens:: -Equivalent to the JVM option `--add-opens`. -The format is: -+ ----- -[jpms] -add-opens: /=(,)* ----- -where `module` and `target-module` are a JPMS module names. - -add-exports:: -Equivalent to the JVM option `--add-exports`. -The format is: -+ ----- -[jpms] -add-exports: /=(,)* ----- -where `module` and `target-module` are a JPMS module names. - -add-reads:: -Equivalent to the JVM option `--add-exports`. -The format is: -+ ----- -[jpms] -add-reads: =(,)* ----- -where `module` and `target-module` are a JPMS module names. - -[[og-modules-directive-license]] -===== [license] - -The license under which the module is released. - -A Jetty module may be released under a license that is different from Jetty's, or use libraries that require end-users to accept their licenses in order to be used. - -You can put the license text in the `[license]` section, and when the Jetty module is enabled the license text will be printed on the terminal, and the user prompted to accept the license. -If the user does not accept the license, the module will not be enabled. - -For example: - ----- -[license] -Acme Project is an open source project hosted on GitHub -and released under the Apache 2.0 license. -https://www.apache.org/licenses/LICENSE-2.0.txt ----- - -[[og-modules-directive-version]] -===== [version] - -The minimum Jetty version for which this module is valid. - -For example, a module may only be valid for Jetty 10 and later, but not for earlier Jetty versions (because it references components that have been introduced in Jetty 10). - -For example: - ----- -[version] -10.0 ----- - -A Jetty module with such a section will only work for Jetty 10.0.x or later. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/chapter.adoc deleted file mode 100644 index 59d244ab6593..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/chapter.adoc +++ /dev/null @@ -1,47 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols]] -=== Jetty Connectors and Protocols - -Connectors are the network components through which Jetty accepts incoming network connections. - -Each connector listens on a network port and can be configured with `ConnectionFactory` components that _understand_ one or more network protocols. - -Understanding a protocol means that the connector is able to interpret incoming network bytes (for example, the bytes that represent an HTTP/1.1 request) and convert them into more abstract objects (for example an `HttpServletRequest` object) that are then processed by applications. -Conversely, an abstract object (for example an `HttpServletResponse`) is converted into the correspondent outgoing network bytes (the bytes that represent an HTTP/1.1 response). - -Like other Jetty components, connectors are enabled and configured by enabling and configuring the correspondent Jetty module. - -IMPORTANT: Recall that you must always issue the commands to enable Jetty modules from within the `$JETTY_BASE` directory, and that the Jetty module configuration files are in the `$JETTY_BASE/start.d/` directory. - -You can obtain the list of connector-related modules in this way: - ----- -$ java -jar $JETTY_HOME/start.jar --list-modules=connector ----- - -include::protocols-http.adoc[] -include::protocols-https.adoc[] -include::protocols-http2.adoc[] -include::protocols-http2s.adoc[] -include::protocols-http2c.adoc[] -include::protocols-http3.adoc[] -include::protocols-ssl.adoc[] -include::protocols-proxy.adoc[] -include::protocols-websocket.adoc[] - -// TODO: old_docs/connectors/*.adoc - -// TODO: add documentation for how to add an additional connector e.g. with a name -// we have 2 connectors out of the box, but a third would need an additional XML. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http.adoc deleted file mode 100644 index 19cb90244bb6..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http.adoc +++ /dev/null @@ -1,72 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-http]] -==== Clear-Text HTTP/1.1 - -Clear text HTTP/1.1 is enabled with the `http` Jetty module with the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=http ----- ----- -INFO : mkdir ${jetty.base}/start.d -INFO : server transitively enabled, ini template available with --add-module=server -INFO : logging-jetty transitively enabled -INFO : http initialized in ${jetty.base}/start.d/http.ini -INFO : resources transitively enabled -INFO : threadpool transitively enabled, ini template available with --add-module=threadpool -INFO : logging/slf4j dynamic dependency of logging-jetty -INFO : bytebufferpool transitively enabled, ini template available with --add-module=bytebufferpool -INFO : mkdir ${jetty.base}/resources -INFO : copy ${jetty.home}/modules/logging/jetty/resources/jetty-logging.properties to ${jetty.base}/resources/jetty-logging.properties -INFO : Base directory was modified ----- - -After having enabled the `http` module, the `$JETTY_BASE` directory looks like this: - -[source,subs=quotes] ----- -JETTY_BASE -├── resources -│ └── jetty-logging.properties -└── start.d - └── #http.ini# ----- - -The `http.ini` file is the file that you want to edit to configure network and protocol parameters -- for more details see xref:og-module-http[this section]. - -Note that the `http` Jetty module depends on the `server` Jetty module. - -Some parameters that you may want to configure are in fact common HTTP parameters that are applied not only for clear-text HTTP/1.1, but also for secure HTTP/1.1 or for clear-text HTTP/2 or for encrypted HTTP/2, or for HTTP/3, and these configuration parameters may be present in the `server` module configuration file. - -You can force the creation of the `server.ini` file via: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=server ----- - -Now the `$JETTY_BASE` directory looks like this: - -[source] ----- -JETTY_BASE -├── resources -│ └── jetty-logging.properties -└── start.d - ├── http.ini - └── server.ini ----- - -Now you can edit the `server.ini` file -- for more details see xref:og-module-server[this section]. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2.adoc deleted file mode 100644 index 3ba1495e9a81..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2.adoc +++ /dev/null @@ -1,145 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-http2]] -==== Configuring HTTP/2 - -link:https://tools.ietf.org/html/rfc7540[HTTP/2] is the successor of the HTTP/1.1 protocol, but it is quite different from HTTP/1.1: where HTTP/1.1 is a duplex, text-based protocol, HTTP/2 is a multiplex, binary protocol. - -Because of these fundamental differences, a client and a server need to _negotiate_ what version of the HTTP protocol they speak, based on what versions each side supports. - -To ensure maximum compatibility, and reduce the possibility that an intermediary that only understands HTTP/1.1 will close the connection when receiving unrecognized HTTP/2 bytes, HTTP/2 is typically deployed over secure connections, using the TLS protocol to wrap HTTP/2. - -IMPORTANT: Browsers only support secure HTTP/2. - -The protocol negotiation is performed by the link:https://tools.ietf.org/html/rfc7301[ALPN TLS extension]: the client advertises the list of protocols it can speak, and the server communicates to the client the protocol chosen by the server. - -For example, you can have a client that only supports HTTP/1.1 and a server that supports both HTTP/1.1 and HTTP/2: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant "client\nsupports\nhttp/1.1" as client -participant "server\nsupports\nhttp/1.1 & http/2" as server - -group TLS handshake -client -> server : ClientHello (alpn=[http/1.1]) -server -> server : picks http/1.1 -server -> client : ServerHello (alpn=http/1.1) -...rest of TLS handshake... -end -group TLS HTTP/1.1 -client -> server : HTTP/1.1 GET -server -> client : HTTP/1.1 200 -end ----- - -Nowadays, it's common that both clients and servers support HTTP/2, so servers prefer HTTP/2 as the protocol to speak: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant "client\nsupports\nhttp/1.1 & http/2" as client -participant "server\nsupports\nhttp/1.1 & http/2" as server - -group TLS handshake -client -> server : ClientHello (alpn=[http/1.1,h2]) -server -> server : picks http/2 -server -> client : ServerHello (alpn=h2) -...rest of TLS handshake... -end -group TLS HTTP/2 -client -> server : HTTP/2 GET -server -> client : HTTP/2 200 -end ----- - -When you configure a connector with the HTTP/2 protocol, you typically want to also configure the HTTP/1.1 protocol. -The reason to configure both protocols is that you typically do not control the clients: for example an old browser that does not support HTTP/2, or a monitoring console that performs requests using HTTP/1.1, or a heartbeat service that performs a single HTTP/1.0 request to verify that the server is alive. - -==== Secure vs Clear-Text HTTP/2 - -Deciding whether you want to configure Jetty with xref:og-protocols-http2s[secure HTTP/2] or xref:og-protocols-http2c[clear-text HTTP/2] depends on your use case. - -You want to configure secure HTTP/2 when Jetty is exposed directly to browsers, because browsers only support secure HTTP/2. - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam roundCorner 10 - -rectangle browser -cloud internet -rectangle jetty - -jetty <--> internet : TLS+HTTP/2 -internet <--> browser : TLS+HTTP/2 ----- - -You may configure clear-text HTTP/2 (mostly for performance reasons) if you offload TLS at a load balancer (for example, link:https://haproxy.org/[HAProxy]) or at a reverse proxy (for example, link:https://nginx.org/[nginx]). - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam roundCorner 10 - -rectangle browser -cloud internet -rectangle haproxy -rectangle jetty - -note right of haproxy: TLS offload - -jetty <--> haproxy : HTTP/2 (clear-text) -haproxy <--> internet : TLS+HTTP/2 -internet <--> browser : TLS+HTTP/2 ----- - -You may configure clear-text HTTP/2 (mostly for performance reasons) to call microservices deployed to different Jetty servers (although you may want to use secure HTTP/2 for confidentiality reasons). - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam roundCorner 10 - -rectangle browser -cloud internet -rectangle haproxy -rectangle jetty -rectangle microservice1 -rectangle microservice2 -rectangle microservice3 - -note right of haproxy: TLS offload - -internet <--> browser : TLS+HTTP/2 -haproxy <--> internet : TLS+HTTP/2 -jetty <--> haproxy : HTTP/2 (clear-text) -microservice1 <--> jetty : HTTP/2 -microservice2 <--> jetty : HTTP/2 -microservice3 <--> jetty : HTTP/2 -microservice2 <--> microservice3 : HTTP/2 -microservice1 <--> microservice3 : HTTP/2 ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2c.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2c.adoc deleted file mode 100644 index feb8da5c5d0a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2c.adoc +++ /dev/null @@ -1,66 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-http2c]] -==== Clear-Text HTTP/2 - -When you enable clear-text HTTP/2 you typically want to enable also clear-text HTTP/1.1, for backwards compatibility reasons and to allow clients to link:https://tools.ietf.org/html/rfc7540#section-3.2[upgrade] from HTTP/1.1 to HTTP/2. - -You need to enable: - -* the `http` Jetty module, which provides the clear-text connector and adds the HTTP/1.1 protocol to the clear-text connector -* the `http2c` Jetty module, which adds the HTTP/2 protocol to the clear-text connector - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=http,http2c ----- - -Starting Jetty yields: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=http,http2c",highlight="(\{.+:8080})"] ----- - -Note how Jetty is listening on port `8080` and the protocols supported are HTTP/1.1 and `h2c` (i.e. clear-text HTTP/2). - -With this configuration, browsers and client applications will be able to connect to port `8080` using: - -* HTTP/1.1 directly (e.g. `curl --http1.1 ++http://localhost:8080++`): ----- -GET / HTTP/1.1 -Host: localhost:8080 ----- -* HTTP/1.1 with upgrade to HTTP/2 (e.g. `curl --http2 ++http://localhost:8080++`): ----- -GET / HTTP/1.1 -Host: localhost:8080 -Connection: Upgrade, HTTP2-Settings -Upgrade: h2c -HTTP2-Settings: ----- -* HTTP/2 directly (e.g. `curl --http2-prior-knowledge ++http://localhost:8080++`): ----- -50 52 49 20 2a 20 48 54 54 50 2f 32 2e 30 0d 0a -0d 0a 53 4d 0d 0a 0d 0a 00 00 12 04 00 00 00 00 -00 00 03 00 00 00 64 00 04 40 00 00 00 00 02 00 -00 00 00 00 00 1e 01 05 00 00 00 01 82 84 86 41 -8a a0 e4 1d 13 9d 09 b8 f0 1e 07 7a 88 25 b6 50 -c3 ab b8 f2 e0 53 03 2a 2f 2a ----- - -The HTTP/2 protocol parameters can be configured by editing the xref:og-module-http2c[`http2c` module] properties. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2s.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2s.adoc deleted file mode 100644 index e9685d07cb51..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http2s.adoc +++ /dev/null @@ -1,58 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-http2s]] -==== Secure HTTP/2 - -When you enable secure HTTP/2 you typically want to enable also secure HTTP/1.1, for backwards compatibility reasons: in this way, old browsers or other clients that do not support HTTP/2 will be able to connect to your server. - -You need to enable: - -* the `ssl` Jetty module, which provides the secure connector and the KeyStore and TLS configuration -* the `http2` Jetty module, which adds ALPN handling and adds the HTTP/2 protocol to the secured connector -* optionally, the `https` Jetty module, which adds the HTTP/1.1 protocol to the secured connector - -Use the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=ssl,http2,https ----- - -As when enabling the `https` Jetty module, you need a valid KeyStore (read xref:og-keystore[this section] to create your own KeyStore). - -As a quick example, you can enable the xref:og-module-test-keystore[`test-keystore` module], that creates on-the-fly a KeyStore containing a self-signed certificate: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=test-keystore ----- - -Starting Jetty yields: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=ssl,http2,https,test-keystore",highlight="(\{.*:8443})"] ----- - -Note how Jetty is listening on port `8443` and the protocols supported are the sequence `(ssl, alpn, h2, http/1.1)`. - -The (ordered) list of protocols after `alpn` are the _application protocols_, in the example above `(h2, http/1.1)`. - -When a new connection is accepted by the connector, Jetty first interprets the TLS bytes, then it handles the ALPN negotiation knowing that the application protocols are (in order) `h2` and then `http/1.1`. - -You can customize the list of application protocols and the default protocol to use in case the ALPN negotiation fails by editing the xref:og-module-alpn[`alpn` module] properties. - -The HTTP/2 protocol parameters can be configured by editing the xref:og-module-http2[`http2` module] properties. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http3.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http3.adoc deleted file mode 100644 index 009d36e62fad..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-http3.adoc +++ /dev/null @@ -1,49 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-http3]] -==== HTTP/3 - -When you enable support for the HTTP/3 protocol, by default the secure HTTP/2 protocol is also enabled, so that browsers or clients that do not support HTTP/3 will be able to connect to your server. - -You need to enable: - -* the `ssl` Jetty module, which provides the KeyStore and TLS configuration -* the `http3` Jetty module, which adds the HTTP/3 protocol on the HTTP/3 connector - -Use the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=ssl,http3 ----- - -Enabling any module Jetty module that supports secure network communication requires a valid KeyStore (read xref:og-keystore[this section] to create your own KeyStore), that, as a quick example, you can enable with the xref:og-module-test-keystore[`test-keystore` module], that creates on-the-fly a KeyStore containing a self-signed certificate: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=test-keystore ----- - -Starting Jetty yields: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupArgs="--approve-all-licenses --add-modules=ssl,http3,test-keystore",highlight="(\{.*:8444})"] ----- - -Note how Jetty is listening on port `8443` for HTTP/2 and on port `8444` for HTTP/3. - -The HTTP/3 protocol parameters can be configured by editing the xref:og-module-http3[`http3` module] properties. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-https.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-https.adoc deleted file mode 100644 index d9ef7d3e685c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-https.adoc +++ /dev/null @@ -1,92 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-https]] -==== Secure HTTP/1.1 - -Secure HTTP/1.1 is enabled with both the `ssl` and `https` Jetty modules with the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=ssl,https ----- - -[source,options=nowrap] ----- -include::jetty[args="--add-modules=ssl,https"] ----- - -The command above enables the `ssl` module, that provides the secure network connector, the KeyStore configuration and TLS configuration -- for more details see xref:og-protocols-ssl[this section]. -Then, the xref:og-module-https[`https` module] adds HTTP/1.1 as the protocol secured by TLS. - -The `$JETTY_BASE` directory looks like this: - -[source] ----- -$JETTY_BASE -├── resources -│ └── jetty-logging.properties -└── start.d - ├── https.ini - └── ssl.ini ----- - -Note that the KeyStore file is missing, because you have to provide one with the cryptographic material you want (read xref:og-keystore[this section] to create your own KeyStore). -You need to configure these two properties by editing `ssl.ini`: - -* `jetty.sslContext.keyStorePath` -* `jetty.sslContext.keyStorePassword` - -As a quick example, you can enable the xref:og-module-test-keystore[`test-keystore` module], that creates on-the-fly a KeyStore containing a self-signed certificate: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=test-keystore ----- - -[source,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=ssl,https",args="--add-modules=test-keystore"] ----- - -The `$JETTY_BASE` directory is now: - -[source,subs=quotes] ----- -├── etc -│ └── #test-keystore.p12# -├── resources -│ └── jetty-logging.properties -└── start.d - ├── https.ini - ├── ssl.ini - └── test-keystore.ini ----- - -Starting Jetty yields: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=ssl,https,test-keystore",highlight="(\{.*:8443})"] ----- - -Note how Jetty is listening on port `8443` for the secure HTTP/1.1 protocol. - -[WARNING] -==== -If you point your browser at `+https://localhost:8443/+` you will get a warning from the browser about a "potential security risk ahead", or that "your connection is not private", or similar message depending on the browser. - -This is normal because the certificate contained in `test-keystore.p12` is self-signed -- and as such not signed by a recognized certificate authority -- and therefore browsers do not trust it. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-proxy.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-proxy.adoc deleted file mode 100644 index 56543b2c3f3d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-proxy.adoc +++ /dev/null @@ -1,261 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-proxy]] -==== Jetty Behind a Load Balancer or Reverse Proxy - -You may need to configure one or more Jetty instances behind an _intermediary_, typically a load balancer such as link:https://haproxy.org[HAProxy], or a reverse proxy such as link:https://httpd.apache.org[Apache HTTP Server] or link:https://nginx.org[Nginx]. - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam padding 5 - -scale 1.5 - -rectangle client -rectangle proxy -rectangle "Jetty" as jetty1 -rectangle "Jetty" as jetty2 - -client -- proxy -proxy -- jetty1 -proxy -- jetty2 ----- - -[WARNING] -==== -HAProxy can communicate either HTTP/1.1 or HTTP/2 to backend servers such as Jetty. - -Apache HTTP Server and Nginx can only speak HTTP/1.1 to backend servers such as Jetty, and have no plans to support HTTP/2 towards backend servers. -==== - -In these setups, typically the proxy performs TLS offloading, and the communication with backend servers happens in clear-text. -It is possible, however, to configure the proxy so that all the bytes arriving from the client are tunnelled opaquely to the backend Jetty server (that therefore needs to perform the TLS offloading) and viceversa the bytes arriving from the Jetty server are tunnelled opaquely to the client. - -Also in these setups, the TCP/IP connection terminating on the Jetty servers does not originate from the client, but from the proxy, so that the remote IP address and port number may be reported incorrectly in backend server logs, or worse applications may not work because they need to be able to differentiate different clients based on the client IP address. - -For this reason, intermediaries typically implement at least one of several _de facto_ standards to communicate information about the original client connection to the backend Jetty server. - -Jetty supports two methods to process client information sent by intermediaries: - -* The `Forwarded` HTTP header, defined in link:https://tools.ietf.org/html/rfc7239[RFC 7239] and replacing the old `X-Forwarded-*` headers, defined in xref:og-protocols-proxy-forwarded[this section]. -* The link:https://www.haproxy.org/download/2.2/doc/proxy-protocol.txt[Proxy Protocol], defined in xref:og-protocols-proxy-protocol[this section]. - -In both methods, web applications that call `HttpServletRequest.getRemoteAddr()` will receive the remote client IP address as specified by the client information sent by the intermediary, not the physical IP address of TCP connection with the intermediary. -Likewise, `HttpServletRequest.getRemotePort()` will return the remote client IP port as specified by the client information sent by the intermediary, and `HttpServletRequest.isSecure()` will return whether the client made a secure request using the `https` scheme as specified by the client information sent by the intermediary. - -[[og-protocols-proxy-forwarded]] -===== Configuring the Forwarded Header - -The `Forwarded` HTTP header is added by the intermediary with information about the client and the client request, for example: - ----- -GET / HTTP/1.1 -Host: domain.com -Forwarded: for=2.36.72.144:21216;proto=https ----- - -In the example above, the intermediary added the `Forwarded` header specifying that the client remote address is `2.36.72.144:21216` and that the request was made with the `https` scheme. - -Let's assume you have already configured Jetty with the HTTP/1.1 protocol with the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=http ----- - -Support for the `Forwarded` HTTP header (and its predecessor `X-Forwarded-*` headers) is enabled with the `http-forwarded` Jetty module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=http-forwarded ----- - -[source,options=nowrap] ----- -include::jetty[setupArgs="--add-module=http",args="--add-module=http-forwarded"] ----- - -With the `http-forwarded` Jetty module enabled, Jetty interprets the `Forwarded` header and makes its information available to web applications via the standard Servlet APIs. - -For further information about configuring the `http-forwarded` Jetty module, see xref:og-module-http-forwarded[this section]. - -[[og-protocols-proxy-protocol]] -===== Configuring the Proxy Protocol - -The link:https://www.haproxy.org/download/2.2/doc/proxy-protocol.txt[Proxy Protocol] is the _de facto_ standard, introduced by link:https://haproxy.org[HAProxy], to communicate client information to backend servers via the TCP connection, rather than via HTTP headers. - -The information about the client connection is sent as a small data frame on each newly established connection. -This mechanism is therefore independent of any protocol, so it can be used for TLS, HTTP/1.1, HTTP/2, etc. - -[NOTE] -==== -There are 2 versions of the proxy protocol: v1 and v2, both supported by Jetty. - -Proxy protocol v1 is human readable, but it only carries information about the client TCP connection (IP address and IP port). - -Proxy protocol v2 has a binary format, carries the information about the client TCP connection, and can carry additional arbitrary information encoded in pairs `(type, value)` where `type` is a single byte that indicates the value's meaning, and `value` is a variable length byte array that can encode user-defined data. -==== - -Support for the proxy protocol can be enabled for the clear-text connector or for the secure connector (or both). - -Let's assume you have already configured Jetty with the HTTP/1.1 clear-text protocol with the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=http ----- - -To enable proxy protocol support for the clear-text connector, enable the `proxy-protocol` Jetty module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=proxy-protocol ----- - -[source,options=nowrap] ----- -include::jetty[setupArgs="--add-module=http",args="--add-module=proxy-protocol"] ----- - -Starting Jetty yields: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[args="--module=proxy-protocol",highlight="(\{.*:8080})"] ----- - -Note how in the example above the list of protocols for the clear-text connector is first `proxy` and then `http/1.1`. -For every new TCP connection, Jetty first interprets the proxy protocol bytes with the client information; after this initial proxy protocol processing, Jetty interprets the incoming bytes as HTTP/1.1 bytes. - -Enabling proxy protocol support for the secure connector is similar. - -Let's assume you have already configured Jetty with the HTTP/1.1 secure protocol and the test KeyStore with the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=https,test-keystore ----- - -Enable the `proxy-protocol-ssl` Jetty module with the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=proxy-protocol-ssl ----- - -[source,options=nowrap] ----- -include::jetty[setupArgs="--add-module=https",args="--add-module=proxy-protocol-ssl"] ----- - -Starting Jetty yields: - ----- -$ java -jar $JETTY_HOME/start.jar ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=https,test-keystore,proxy-protocol-ssl",highlight="(\{.*:8443})"] ----- - -Note how in the example above the list of protocols for the secure connector is first `proxy`, then `ssl` and then `http/1.1`. - -[[og-protocols-proxy-haproxy]] -===== HAProxy and Jetty with HTTP/1.1 and HTTP/2 - -link:https://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. - -The deployment proposed here has HAProxy playing the role that Apache and Nginx usually do: to perform the TLS offloading (that is, decrypt incoming bytes and encrypt outgoing bytes) and then forwarding the now clear-text traffic to a backend Jetty server, speaking either HTTP/1.1 or HTTP/2. -Since HAProxy's TLS offloading is based on OpenSSL, it is much more efficient than the Java implementation shipped with OpenJDK. - -After you have installed HAProxy on your system, you want to configure it so that it can perform TLS offloading. - -HAProxy will need a single file containing the X509 certificates and the private key, all in link: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 is 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. - -Refer to the xref:og-keystore[section about KeyStores] for more information about generating the required certificates and private key. - -Now you can create the HAProxy configuration file (in Linux it's typically `/etc/haproxy/haproxy.cfg`). -This is a minimal configuration: - -.haproxy.cfg -[source,subs=verbatim] ----- -global -tune.ssl.default-dh-param 1024 - -defaults -timeout connect 10000ms -timeout client 60000ms -timeout server 60000ms - -frontend fe_http <1> -mode http -bind *:80 -# Redirect to https -redirect scheme https code 301 - -frontend fe_https <2> -mode tcp -bind *:443 ssl no-sslv3 crt /path/to/domain.pem ciphers TLSv1.2 alpn h2,http/1.1 -default_backend be_http - -backend be_http <3> -mode tcp -server domain 127.0.0.1:8282 send-proxy-v2 ----- -<1> The `fe_http` front-end accepts connections on port 80 and redirects them to use the `https` scheme. -<2> 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 /path/to/domain.pem` part), the ciphers that are suitable for HTTP/2 (`ciphers TLSv1.2`), and the ALPN protocols supported (`alpn h2,http/1.1`). -This front-end then forwards the now decrypted bytes to the backend in `mode tcp`. -The `mode tcp` says that HAProxy will not try to interpret the bytes but instead opaquely forwards them to the backend. -<3> The `be_http` backend 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. -The `send-proxy-v2` directive sends the proxy protocol v2 bytes to the backend server. - -On the Jetty side, you need to enable the following modules: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=proxy-protocol,http2c,http,deploy ----- - -You need to specify the host (`127.0.0.1`) and port (`8282`) you have configured in HAProxy when you start Jetty: - ----- -$ java -jar $JETTY_HOME/start.jar jetty.http.host=127.0.0.1 jetty.http.port=8282 ----- - -[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 `$JETTY_BASE/start.d/http.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. -==== - -With this configuration for HAProxy and Jetty, 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` and the `http` modules 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. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-ssl.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-ssl.adoc deleted file mode 100644 index 031593299116..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-ssl.adoc +++ /dev/null @@ -1,290 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-ssl]] -==== Configuring Secure Protocols - -Secure protocols are normal protocols such as HTTP/1.1, HTTP/2 or WebSocket that are wrapped by the link:https://en.wikipedia.org/wiki/Transport_Layer_Security[TLS protocol]. -Any network protocol based on TCP can be wrapped with TLS. - -QUIC, the protocol based on UDP that transports HTTP/3, uses TLS messages but not the TLS protocol framing. - -The `https` scheme used in URIs really means `tls+http/1.1` (or `tls+http/2`, or `quic+http/3`) and similarly the `wss` scheme used in URIs really means `tls+websocket`, etc. -Senders wrap the underlying protocol bytes (e.g. HTTP bytes or WebSocket bytes) with the TLS protocol, while receivers first interpret the TLS protocol to obtain the underlying protocol bytes, and then interpret the wrapped bytes. - -The xref:og-module-ssl[`ssl` Jetty module] allows you to configure a secure network connector; if other modules require encryption, they declare a dependency on the `ssl` module. - -It is the job of other Jetty modules to configure the wrapped protocol. -For example, it is the xref:og-protocols-https[`https` module] that configures the wrapped protocol to be HTTP/1.1. -Similarly, it is the xref:og-protocols-http2[`http2` module] that configures the wrapped protocol to be HTTP/2. -If you enable _both_ the `https` and the `http2` module, you will have a single secure connector that will be able to interpret both HTTP/1.1 and HTTP/2. - -TIP: Recall from the xref:og-modules[section about modules], that only modules that are explicitly enabled get their module configuration file (`+*.ini+`) saved in `$JETTY_BASE/start.d/`, and you want `$JETTY_BASE/start.d/ssl.ini` to be present so that you can configure the connector properties, the KeyStore properties and the TLS properties. - -[[og-protocols-ssl-customize]] -===== Customizing KeyStore and SSL/TLS Configuration - -Secure protocols have a slightly more complicated configuration since they require to configure a _KeyStore_. -Refer to the xref:og-keystore[KeyStore section] for more information about how to create and manage a KeyStore. - -For simple cases, you only need to configure the KeyStore path and KeyStore password as explained in xref:og-module-ssl-keystore-tls[this section]. - -For more advanced configuration you may want to configure the TLS protocol versions, or the ciphers to include/exclude, etc. -The correct way of doing this is to create a custom xref:og-xml[Jetty XML file] and reference it in `$JETTY_BASE/start.d/ssl.ini`: - -.ssl.ini -[source,subs=verbatim] ----- -jetty.sslContext.keyStorePassword=my_passwd! <1> -etc/tls-config.xml <2> ----- -<1> Configures the `jetty.sslContext.keyStorePassword` property with the KeyStore password. -<2> References your newly created `$JETTY_BASE/etc/tls-config.xml`. - -The `ssl.ini` file above only shows the lines that are not commented out (you can leave the lines that are commented unmodified for future reference). - -You want to create the `$JETTY_BASE/etc/tls-config.xml` with the following template content: - -.tls-config.xml -[source,xml,subs=verbatim] ----- - - - - - - ... <1> - - ----- -<1> Here goes your advanced configuration. - -The `tls-config.xml` file references the `sslContextFactory` component (created by the `ssl` Jetty module) that configures the KeyStore and TLS parameters, so that you can now call its APIs via XML, and you will have full flexibility for any advanced configuration you want (see below for few examples). - -Refer to the link:{javadoc-url}/org/eclipse/jetty/util/ssl/SslContextFactory.html[SslContextFactory javadocs] for the list of methods that you can call through the Jetty XML file. - -CAUTION: Use module properties whenever possible, and only resort to use a Jetty XML file for advanced configuration that you cannot do using module properties. - -[[og-protocols-ssl-customize-versions]] -====== Customizing SSL/TLS Protocol Versions - -By default, the SSL protocols (SSL, SSLv2, SSLv3, etc.) are already excluded because they are vulnerable. -To explicitly add the exclusion of TLSv1.0 and TLSv1.1 (that are also vulnerable -- which leaves only TLSv1.2 and TLSv1.3 available), you want to use this XML: - -.tls-config.xml -[source,xml] ----- - - - - - - - - - TLSv1.0 - TLSv1.1 - - - - - ----- - -[[og-protocols-ssl-customize-ciphers]] -====== Customizing SSL/TLS Ciphers - -You can precisely set the list of excluded ciphers, completely overriding Jetty's default, with this XML: - -.tls-config.xml -[source,xml] ----- - - - - - - - - ^TLS_RSA_.*$ - ^.*_RSA_.*_(MD5|SHA|SHA1)$ - ^.*_DHE_RSA_.*$ - SSL_RSA_WITH_DES_CBC_SHA - SSL_DHE_RSA_WITH_DES_CBC_SHA - SSL_DHE_DSS_WITH_DES_CBC_SHA - SSL_RSA_EXPORT_WITH_RC4_40_MD5 - SSL_RSA_EXPORT_WITH_DES40_CBC_SHA - SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA - SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA - - - - ----- - -Note how each array item specifies a _regular expression_ that matches multiple ciphers, or specifies a precise cipher to exclude. - -You can choose to create multiple XML files, and reference them all from `$JETTY_BASE/start.d/ssl.ini`, or put all your custom configurations in a single XML file. - -[[og-protocols-ssl-renew]] -===== Renewing the Certificates - -When you create a certificate, you must specify for how many days it is valid. - -The typical validity is 90 days, and while this period may seem short, it has two advantages: - -* Reduces the risk in case of compromised/stolen keys. -* Encourages automation, i.e. certificate renewal performed by automated tools (rather than manually) at scheduled times. - -To renew a certificate, you must go through the xref:og-keystore-create[same steps] you followed to create the certificate the first time, and then you can xref:og-protocols-ssl-reload[reload the KeyStore] without the need to stop Jetty. - -[[og-protocols-ssl-reload]] -===== Watching and Reloading the KeyStore - -Jetty can be configured to monitor the directory of the KeyStore file, and reload the `SslContextFactory` component if the KeyStore file changed. - -This feature can be enabled by activating the `ssl-reload` Jetty module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=ssl-reload ----- - -For more information about the configuration of the `ssl-reload` Jetty module, see xref:og-module-ssl-reload[this section]. - -[[og-protocols-ssl-conscrypt]] -===== Using Conscrypt as SSL/TLS Provider - -If not explicitly configured, the TLS implementation is provided by the JDK you are using at runtime. - -OpenJDK's vendors may replace the default TLS provider with their own, but you can also explicitly configure an alternative TLS provider. - -The standard TLS provider from OpenJDK is implemented in Java (no native code), and its performance is not optimal, both in CPU usage and memory usage. - -A faster alternative, implemented natively, is Google's link:https://github.com/google/conscrypt/[Conscrypt], which is built on link:https://boringssl.googlesource.com/boringssl/[BoringSSL], which is Google's fork of link:https://www.openssl.org/[OpenSSL]. - -CAUTION: As Conscrypt eventually binds to a native library, there is a higher risk that a bug in Conscrypt or in the native library causes a JVM crash, while the Java implementation will not cause a JVM crash. - -To use Conscrypt as the TLS provider just enable the `conscrypt` Jetty module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-module=conscrypt ----- - -[[og-protocols-ssl-sni]] -===== Configuring SNI - -Server Name Indication (SNI) is a TLS extension that clients send to indicate what domain they want to connect to during the initial TLS handshake. - -Modern TLS clients (e.g. browsers) always send the SNI extension; however, older TLS clients may not send the SNI extension. - -Being able to handle the SNI is important when you have xref:og-deploy-virtual-hosts[virtual hosts] and a KeyStore with multiple certificates, one for each domain. - -For example, you may have deployed over a secure connector two web applications, both at context path `/`, one at virtual host `one.com` and one at virtual host `two.net`. -The KeyStore contains two certificates, one for `one.com` and one for `two.net`. - -There are three `ssl` module properties that control the SNI behavior on the server: one that works at the TLS level, and two that works at the HTTP level. - -The property that works at the TLS level is: - -`jetty.sslContext.sniRequired`:: -Whether SNI is required at the TLS level, defaults to `false`. -Its behavior is explained by the following table: -+ -.Behavior of the `jetty.sslContext.sniRequired` property -[cols="3*a"] -|=== -| -| `sniRequired=false` -| `sniRequired=true` - -| SNI = `null` -| client receives default certificate -| client receives TLS failure - -| SNI = `wrong.org` -| client receives default certificate -| client receives TLS failure - -| SNI = `one.com` -| client receives `one.com` certificate -| client receives `one.com` certificate -|=== -+ -[WARNING] -==== -The _default certificate_ is the certificate returned by the TLS implementation in case there is no SNI match, and you should not rely on this certificate to be the same across Java vendors and versions, or Jetty versions, or TLS provider vendors and versions. - -In the example above it could be either the `one.com` certificate or the `two.net` certificate. -==== - -When `jetty.sslContext.sniRequired=true`, clients that don't send a valid SNI receive a TLS failure, and their attempt to connect to the server fails. -The details of this failure may not be reported and could be difficult to figure out that the failure is related to an invalid SNI. - -For this reason, other two properties are defined at the HTTP level, so that clients can received an HTTP 400 response with more details about what went wrong while trying to connect to the server: - -`jetty.ssl.sniRequired`:: -Whether SNI is required at the HTTP level, defaults to `false`. -Its behavior is similar to the `jetty.sslContext.sniRequired` property above, and is explained by the following table: -+ -.Behavior of the `jetty.ssl.sniRequired` property -[cols=3*a] -|=== -| -| `sniRequired=false` -| `sniRequired=true` - -| SNI = `null` -| Accept -| Reject: 400 Bad Request - -| SNI = `wrong.org` -| Accept -| Reject: 400 Bad Request - -| SNI = `one.com` -| Accept -| Accept -|=== - -When `jetty.ssl.sniRequired=true`, the SNI is matched against the certificate sent to the client, and only if there is a match the request is accepted. - -When the request is accepted, there could be an additional check controlled by the following property: - -`jetty.ssl.sniHostCheck`:: -Whether the certificate sent to the client matches the `Host` header, defaults to `true`. -Its behavior is explained by the following table: -+ -.Behavior of the `jetty.ssl.sniHostCheck` property -[cols="3*a"] -|=== -| -| `sniHostCheck=false` -| `sniHostCheck=true` - -| certificate = `one.com` + -`Host: wrong.org` -| Accept -| Reject: 400 Bad Request - -| certificate = `one.com` + -`Host: one.com` -| Accept -| Accept -|=== - -In the normal case with the default server configuration, for a TLS clients that sends SNI, and then sends an HTTP request with the correct `Host` header, Jetty will pick the correct certificate from the KeyStore based on the SNI received from the client, and accept the request. - -Accepting the request does not mean that the request is responded with an HTTP 200 OK, but just that the request passed successfully the SNI checks and will be processed by the server. -If the request URI is for a resource that does not exist, the response will likely be a 404 Not Found. - -You may modify the default values of the SNI properties if you want stricter control over old/broken TLS clients or bad HTTP requests. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-websocket.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-websocket.adoc deleted file mode 100644 index 8a733a9848d5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/protocols/protocols-websocket.adoc +++ /dev/null @@ -1,117 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-protocols-websocket]] -==== WebSocket - -WebSocket is a network protocol for bidirectional data communication initiated via the link:https://tools.ietf.org/html/rfc7230#section-6.7[HTTP/1.1 upgrade mechanism]. -WebSocket provides a simple, low-level, framing protocol layered over TCP. -One or more WebSocket frames compose a WebSocket _message_ that is either a UTF-8 _text_ message or _binary_ message. - -Jetty provides an implementation of the following standards and specifications. - -http://tools.ietf.org/html/rfc6455[RFC-6455] - The WebSocket Protocol:: -Jetty supports version 13 of the released and final specification. - -http://www.jcp.org/en/jsr/detail?id=356[JSR-356] - The Java WebSocket API (`javax.websocket`):: -This is the official Java API for working with WebSockets. - -https://tools.ietf.org/html/rfc7692[RFC-7692] - WebSocket Per-Message Deflate Extension:: -This is the replacement for perframe-compression, switching the compression to being based on the entire message, not the individual frames. - -https://tools.ietf.org/html/rfc8441[RFC-8441] - Bootstrapping WebSockets with HTTP/2:: -Allows a single stream of an HTTP/2 connection to be upgraded to WebSocket. -This allows one TCP connection to be shared by both protocols and extends HTTP/2's more efficient use of the network to WebSockets. - -[[og-protocols-websocket-configure]] -===== Configuring WebSocket - -Jetty provides two WebSocket implementations: one based on the Java WebSocket APIs defined by JSR 356, provided by module `websocket-javax`, and one based on Jetty specific WebSocket APIs, provided by module `websocket-jetty`. -The Jetty `websocket` module enables both implementations, but each implementation can be enabled independently. - -NOTE: Remember that a WebSocket connection is always initiated from the HTTP protocol (either an HTTP/1.1 upgrade or an HTTP/2 connect), therefore to enable WebSocket you need to enable HTTP. - -To enable WebSocket support, you also need to decide what version of the HTTP protocol you want WebSocket to be initiated from, and whether you want secure HTTP. - -For example, to enable clear-text WebSocket from HTTP/1.1, use the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=http,websocket ----- - -To enable secure WebSocket from HTTP/2, use the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=http2,websocket ----- - -When enabling secure protocols you need a valid KeyStore (read xref:og-keystore[this section] to create your own KeyStore). -As a quick example, you can enable the xref:og-module-test-keystore[`test-keystore` module], that creates on-the-fly a KeyStore containing a self-signed certificate: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=test-keystore ----- - -To enable WebSocket on both HTTP/1.1 and HTTP/2, both clear-text and secure, use the following command (issued from within the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=http,https,http2c,http2,websocket ----- - -[[og-protocols-websocket-disable]] -===== Selectively Disabling WebSocket - -Enabling the WebSocket Jetty modules comes with a startup cost because Jetty must perform two steps: - -. Scan web applications `+*.war+` files (and all the jars and classes inside it) looking for WebSocket EndPoints classes (either annotated with WebSocket API annotations or extending/implementing WebSocket API classes/interfaces). -This can be a significant cost if your web application contains a lot of classes and/or jar files. - -. Configure and wire WebSocket EndPoints so that WebSocket messages are delivered to the correspondent WebSocket EndPoint. - -WebSocket support is by default enabled for all web applications. - -For a specific web application, you can disable step 2 for Java WebSocket support (i.e. when the `websocket-javax` module is enabled) by setting the context attribute `org.eclipse.jetty.websocket.javax` to `false`: - -[source,xml] ----- - - - - - - org.eclipse.jetty.websocket.javax - false - - - ... - - ----- - -Furthermore, for a specific web application, you can disable step 1 (and therefore also step 2) as described in the xref:og-annotations[annotations processing section]. - -[[og-protocols-websocket-webapp-client]] -===== Using WebSocket Client in WebApps - -Web applications may need to use a WebSocket client to communicate with third party WebSocket services. - -If the web application uses the Java WebSocket APIs, the WebSocket client APIs are provided by the Servlet Container and are available to the web application by enabling the WebSocket server APIs, and therefore you must enable the `websocket-javax` Jetty module. - -However, the Java WebSocket Client APIs are quite limited (for example, they do not support secure WebSocket). -For this reason, web applications may want to use the Jetty WebSocket Client APIs. - -When using the Jetty WebSocket Client APIs, web applications should include the required jars and their dependencies in the `WEB-INF/lib` directory of the `+*.war+` file. -Alternatively, when deploying your web applications in Jetty, you can enable the `websocket-jetty-client` Jetty module to allow web applications to use the Jetty WebSocket Client APIs provided by Jetty, without the need to include jars and their dependencies in the `+*.war+` file. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/quickstart/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/quickstart/chapter.adoc deleted file mode 100644 index a7775063c72e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/quickstart/chapter.adoc +++ /dev/null @@ -1,69 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-quickstart]] -=== Faster Web Application Deployment - - -The auto discovery features of the Servlet Specification can make deployments slow and uncertain. -Auto discovery of web application configuration can be useful during the development as it allows new features and frameworks to be enabled simply by dropping in a jar file. -However for production deployment, the need to scan the contents of many jars can have a significant impact at startup time. - -The `quickstart` module allows a webapp to be pre-scanned, making startup predictable and faster. -During scanning all declarative configuration (ie from web.xml, web-fragment.xml and annotations) are encoded into an effective `web.xml`, called `WEB-INF/quickstart-web.xml`, which can be inspected to understand what will be deployed. - -[NOTE] -==== -Programmatic configuration is _not_ encoded into the generated `quickstart-web.xml` file. -==== - -With `quickstart`, webapps that took many seconds to scan and deploy can now be deployed in a few hundred milliseconds. - -==== Enabling - -Enable the `quickstart` module for your jetty base: - ----- -$ cd $JETTY-BASE -$ java -jar $JETTY_HOME/start.jar --add-module=quickstart ----- - -The `$JETTY-BASE/start.d/quickstart.ini` file contains these configurable parameters: - -jetty.quickstart.mode:: - The values are: - - AUTO::: - Allows jetty to run either with or without a `quickstart-web.xml` file. - If jetty detects the file, then it will be used, otherwise the app is started normally. - GENERATE::: - In this mode, jetty will generate a `quickstart-web.xml` file and then terminate. - Use this mode first before changing to either `AUTO` or `QUICKSTART`. - QUICKSTART::: - In this mode, if jetty does not detect a `quickstart-web.xml` file then jetty will not start. - -jetty.quickstart.origin:: -Use this parameter to set the name of the attribute in the `quickstart-web.xml` file that contains the origin of each element. -Knowing the descriptor or annotation from which each element derives can be useful for debugging. -Note that the origin attribute does not conform to the web xml schema, so if you deploy with xml validation, you'll see errors. -It is probably best to do a few trial runs with the attribute set, then turn it off for final generation. - -jetty.quickstart.xml:: -Use this parameter to change the name of the generated file. -By default this is `quickstart-web.xml` in the webapp's `WEB-INF` directory. -The file named by this parameter will always be interpreted relative to `WEB-INF`. - -If your webapp is a war file, you will need to either first unpack it yourself, or use a context xml file (or code equivalent) that calls `WebAppContext.setExtractWAR(true)`. -If you allow Jetty to do the unpacking, it will use the usual mechanisms to find the location to which to unpack. -Note that by default Jetty unpacks to a temporary location which is _not_ reused between executions. -So either specify the directory to which to unpack, or make a `work` directory in your base to ensure the unpacked war is preserved and reused across restarts. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/chapter.adoc deleted file mode 100644 index f0ac9d8ee785..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/chapter.adoc +++ /dev/null @@ -1,26 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-server]] -=== Jetty Server - -The Jetty `Server` object is the central component that links protocol connectors to web applications. - -The `Server` component is defined by the xref:og-module-server[`server` Jetty module], that in turn depends on other Jetty modules that provide key functionalities, in particular: - -* xref:og-server-logging[Logging] -* xref:og-module-bytebufferpool[`ByteBuffer` pooling] -* xref:og-server-threadpool[`Thread` pooling] - -include::server-logging.adoc[] -include::server-threadpool.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging-request.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging-request.adoc deleted file mode 100644 index b924dcac54e3..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging-request.adoc +++ /dev/null @@ -1,62 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-logging-request]] -===== Request Logging - -HTTP requests and responses can be logged to provide data that can be later analyzed with other tools, that can provide information such as the most frequently accessed request URIs, the response status codes, the request/response content lengths, geographical information about the clients, etc. - -Request logging is enabled by enabling the `requestlog` Jetty module. -In the example below, both the `http` Jetty module and the `requestlog` module are enabled, so that you can make HTTP requests to the server and have them logged: - ----- -$ cd $JETTY_BASE -$ java -jar $JETTY_HOME/start.jar --add-modules=http,requestlog ----- - -The `$JETTY_BASE` directory looks like this: - -[source] ----- -$JETTY_BASE -├── logs -├── resources -│ └── jetty-logging.properties -└── start.d - ├── http.ini - └── requestlog.ini ----- - -The `$JETTY_BASE/start.d/requestlog.ini` file is the Jetty module configuration file that allows you to configure the `requestlog` module, see xref:og-module-requestlog[this section] for more details. - -By default the `requestlog` Jetty module produces the `$JETTY_BASE/logs/yyyy_MM_dd.request.log`, where the pattern `yyyy_MM_dd` is replaced with the current date, for example `2020_01_31`. - -The format of the request log lines is the result of a _format string_ that uses formatting symbols to log relevant request/response data. - -The default format is the link:https://en.wikipedia.org/wiki/Common_Log_Format[NCSA Format] extended with referrer data and user-agent data. -A typical log line looks like this: - -[source,options=nowrap] ----- -192.168.0.100 - - [31/Jan/2020:20:30:40 +0000] "GET / HTTP/1.1" 200 6789 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36" ----- - -The line above (that uses fake values) shows `192.168.0.100` for the client IP address, a hard-coded `-` for the identity, `-` for the authenticated user name, `[31/Jan/2020:20:30:40 +0000]` for the date and time with timezone, `"GET / HTTP/1.1"` for the HTTP request line, `200` for the HTTP response status code, `6789` for the HTTP response content length, `"-"` for the referrer and `"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"` for the user-agent. - -The format string can be customized as described in xref:og-module-requestlog[this section]. -Request log files are rolled every day, and retained for customizable number of days, by default 90 days. - -[NOTE] -==== -When Jetty is behind a load balancer, you want to log the remote client IP address, not the load balancer IP address. Refer to xref:og-protocols-proxy[this section] to configure the load balancer and Jetty to retain the remote client IP address information. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging-server.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging-server.adoc deleted file mode 100644 index b8f98b715b97..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging-server.adoc +++ /dev/null @@ -1,227 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-server-logging-server]] -===== Server Logging - -The Jetty code uses the link:http://slf4j.org/[SLF4J] API for its logging. - -Thanks to the SLF4J library, the logging of the Jetty server can therefore be directed to the implementation (called SLF4J _binding_) of your choice. - -The Jetty project provides an SLF4J binding (via the `jetty-slf4j-impl` Maven artifact) that is used as the default SLF4J binding. - -The logging of the Jetty server itself is enabled by default with the `logging` Jetty module, which is a transitive dependency of the `server` module and therefore it is typically always enabled. - -The `logging` Jetty module is a _virtual_ module (see xref:og-modules-names[this section]) and its default implementation is provided by the `logging-jetty` Jetty module, which uses the Jetty SLF4J binding. - -[[og-server-logging-server-default]] -====== Default Configuration - -The Jetty SLF4J binding is configured with an appender (`org.eclipse.jetty.logging.StdErrAppender`) that directs the logging to `System.err`, and reads its configuration from a file named `jetty-logging.properties` that must be found in the class-path. - -The `StdErrAppender` format is: - ----- -:::: ----- - -where `=yyyy-MM-dd HH:mm:ss.SSS`. - -You can configure `StdErrAppender` by specifying the following properties in `jetty-logging.properties`: - -org.eclipse.jetty.logging.appender.NAME_CONDENSE=:: -Specifies whether to condense logger names, so that for example `org.eclipse.jetty.util.QueuedThreadPool` becomes `oeju.QueuedThreadPool`. -Default value is `true`. - -org.eclipse.jetty.logging.appender.MESSAGE_ALIGN=:: -Specifies the column at which the logging `` should be printed. -The value `0` specifies no alignment. -Default value is `0`. - -org.eclipse.jetty.logging.appender.MESSAGE_ESCAPE=:: -Specifies whether to escape ISO control characters such as `\r` or `\n` present in the message. -Character `\r` is replaced with `<` and character `\n` is replaced with `|`; all other ISO control characters are replaced with `?`. -Default value is `false`. - -org.eclipse.jetty.logging.appender.ZONE_ID=:: -Specifies the timezone ID (such as `PST`, or `America/Los_Angeles` or `GMT-8:00`) for the `` part of the logging line. -The empty string specifies the `UTC` timezone. -Default value is the local timezone. - -The `logging-jetty` Jetty module, enabled transitively, provides the configuration file `$JETTY_BASE/resources/jetty-logging.properties` to configure the logging levels, for example: - ----- -$ cd $JETTY_BASE -$ java -jar $JETTY_HOME/start.jar --add-modules=http ----- - ----- -$JETTY_BASE -├── resources -│ └── jetty-logging.properties -└── start.d - └── http.ini ----- - -.jetty-logging.properties -[source,properties] ----- -# Do not condense logger names. -org.eclipse.jetty.logging.appender.NAME_CONDENSE=false - -# By default, log at INFO level all Jetty loggers. -org.eclipse.jetty.LEVEL=INFO - -# However, the Jetty client loggers log at DEBUG level. -org.eclipse.jetty.client.LEVEL=DEBUG ----- - -The logging levels that you can specify in the `jetty-logging.properties` file are the usual SLF4J logging levels, `TRACE`, `DEBUG`, `INFO`, `WARN` and `ERROR`, plus two additional levels: - -* `ALL`, which is an alias for `TRACE` -* `OFF`, which disables entirely the logging (not even `ERROR` level messages are logged) - -When using the Jetty SLF4J binding, the logging levels can be dynamically changed via JMX, see xref:og-troubleshooting-logging[the troubleshooting section] for more information. - -[[og-server-logging-server-default-rolling]] -====== Capturing Logs to a Rolling File - -Having the logging output on `System.err` may be fine at development time, but you typically want the logs to be captured in a file so that they can be looked at even if you don't have a terminal (for example, you started Jetty as a service). - -The `console-capture` Jetty module allows you to capture what is written to `System.out` and `System.err` and write it to a log file, by default under the `$JETTY_BASE/logs/` directory. - -The `console-capture` Jetty module defines a number of properties that you can customize to control the log directory, the number of days rolled files are retained, etc. -See the xref:og-module-console-capture[`console-capture` module] for more information. - -[NOTE] -==== -The `console-capture` Jetty module should be used only in conjunction with the `logging-jetty` module, as other SLF4J bindings such as LogBack or Log4j2 have their own, more sophisticated, rolling file appenders. -==== - -[[og-server-logging-server-custom]] -====== Custom Configuration - -You can use a different SLF4J binding if you are more familiar with other logging libraries, or if you need custom logging appenders. -There are a number of out-of-the-box Jetty modules that you can use: - -* `logging-logback`, to use the link:http://logback.qos.ch/[LogBack] binding -* `logging-log4j2`, to use the link:https://logging.apache.org/log4j/2.x/[Log4j2] binding -* `logging-log4j1`, to use the link:https://logging.apache.org/log4j/1.2/[Log4j1] binding (note that Log4j 1.x is end-of-life) -* `logging-jul`, to use the `java.util.logging` binding -* `logging-noop`, to use the SLF4J no-operation binding (discards all logging) - -[[og-server-logging-server-custom-logback]] -====== Logging with LogBack - -You can enable, for example, the `logging-logback` Jetty module in this way (from the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=logging-logback,http ----- - -Since LogBack is released under a license that is different from Jetty's, you will be prompted to accept the LogBack license. -Once you accept the LogBack license, you will have the following directory structure: - ----- -$JETTY_BASE -├── lib -│ └── logging -│ ├── logback-classic-.jar -│ └── logback-core-.jar -├── resources -│ └── logback.xml -└── start.d - ├── http.ini - └── logging-logback.ini ----- - -As you can see, the Jetty module system downloaded the required LogBack `+*.jar+` files, and created a `$JETTY_BASE/resources/logback.xml` file that you can configure to customize your LogBack logging. -Please refer to the link:http://logback.qos.ch/manual/configuration.html[LogBack configuration manual] for more information about how to configure LogBack. - -[[og-server-logging-server-custom-log4j2]] -====== Logging with Log4j2 - -Similarly to xref:og-server-logging-server-custom-logback[logging with LogBack], you can enable the `logging-log4j2` Jetty module in this way (from the `$JETTY_BASE` directory): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=logging-log4j2,http ----- - -After accepting the Log4j2 license, you will have the following directory structure: - ----- -$JETTY_BASE -├── lib -│ └── logging -│ ├── log4j-api-.jar -│ ├── log4j-core-.jar -│ └── log4j-slf4j18-impl-.jar -├── resources -│ └── log4j2.xml -└── start.d - ├── http.ini - └── logging-log4j2.ini ----- - -The Jetty module system downloaded the required Log4j2 `+*.jar+` files, and created a `$JETTY_BASE/resources/log4j2.xml` file that you can configure to customize your Log4j2 logging. - -[[og-server-logging-server-bridges]] -====== Bridging Logging to SLF4J - -When you use libraries that provide the features you need (for example, JDBC drivers), it may be possible that those libraries use a different logging framework than SLF4J. - -SLF4J provides link:http://www.slf4j.org/legacy.html[bridges for legacy logging APIs] that allows you to bridge logging from one of these legacy logging frameworks to SLF4J. -Once the logging is bridged to SLF4J, you can use the xref:og-server-logging-server-default[default configuration] or the xref:og-server-logging-server-custom[custom configuration] so that your logging is centralized in one place only. - -Jetty provides out-of-the-box modules that you can enable to bridge logging from other logging frameworks to SLF4J. - -[[og-server-logging-server-bridge-jul]] -====== Bridging `java.util.logging` - -For libraries that use `java.util.logging` as their logging framework you can enable the `logging-jul-capture` Jetty module. - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=logging-jul-capture ----- - -The `logging-jul-capture` Jetty module implies `--exec` and therefore spawns a second JVM (see xref:og-start-start[this section]) because it needs to provide the system property `java.util.logging.config.file` (so that `java.util.logging` can read the configuration from the specified file), and because it needs to make available on the System ClassLoader the class `org.slf4j.bridge.SLF4JBridgeHandler`. - -For example, a library that uses `java.util.logging` as its logging library is the Postgresql JDBC driver. -With the `logging-jul-capture` Jetty module, the logging follows this diagram: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant "Postgresql JDBC" as postgresql -participant java.util.logging -participant SLF4JBridgeHandler -participant Jetty -participant SLF4J -participant "Jetty SLF4J Binding" as binding - - -postgresql -> java.util.logging -java.util.logging -> SLF4JBridgeHandler -SLF4JBridgeHandler -> SLF4J -SLF4J -> binding -Jetty -> SLF4J -SLF4J -> binding ----- - -Note how Jetty logs directly to SLF4J, while the Postgresql JDBC driver logs to SLF4J through the `SLF4JBridgeHandler`. -They both arrive to the SLF4J binding, in this case the Jetty SLF4J binding (but could be any other SLF4J binding such as LogBack). - -// TODO: add the other bridges diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging.adoc deleted file mode 100644 index cdb51a4fe2cc..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-logging.adoc +++ /dev/null @@ -1,23 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-server-logging]] -==== Logging - -There are two types of logging that can be configured in Jetty: - -* The logging of Jetty itself, that logs the server activity -* The HTTP request logging, that logs information about HTTP requests and responses processed by Jetty - -include::server-logging-server.adoc[] -include::server-logging-request.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-threadpool.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-threadpool.adoc deleted file mode 100644 index 216d2a37bfc8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/server/server-threadpool.adoc +++ /dev/null @@ -1,81 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-server-threadpool]] -==== Thread Pooling - -Jetty uses thread pooling to efficiently execute tasks that provide Jetty functionalities. - -Like any other component, the Jetty thread pool is configured and enabled via the xref:og-module-threadpool[`threadpool` Jetty module], that is transitively enabled by the xref:og-module-server[`server` Jetty module] which, in turn, is transitively enabled by a protocol module such as the xref:og-protocols-http[`http` Jetty module]: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=http ----- - -The command above gives you the default configuration for the thread pool. - -If you want to explicitly configure the thread pool, it is enough to explicitly specify the xref:og-module-threadpool[`threadpool`] module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=threadpool,http ----- - -After the command above, the `$JETTY_BASE` directory looks like this: - -[source,subs=verbatim] ----- -$JETTY_BASE -├── resources -│ └── jetty-logging.properties -└── start.d - ├── http.ini - └── threadpool.ini ----- - -Now you can customize the `threadpool.ini` file to explicitly configure the thread pool. - -[[og-server-threadpool-virtual]] -===== Virtual Threads Support - -Virtual threads have been introduced as a preview feature in Java 19 and Java 20, and have become an official feature since Java 21. - -The xref:og-module-threadpool-virtual-preview[`threadpool-virtual-preview`] Jetty module provides support for virtual threads in Java 19 and Java 20, and it is mutually exclusive with the `threadpool` Jetty module. - -The xref:og-module-threadpool-virtual[`threadpool-virtual`] Jetty module provides support for virtual threads in Java 21 or later, and it is mutually exclusive with the `threadpool` Jetty module. - -If you have already enabled the `threadpool` Jetty module, it is sufficient to remove it by removing the `$JETTY_BASE/start.d/threadpool.ini` file. - -When using Java 21 or later, you can enable the xref:og-module-threadpool-virtual[`threadpool-virtual`] module: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=threadpool-virtual,http ----- - -After the command above, the `$JETTY_BASE` directory looks like this: - -[source,subs=verbatim] ----- -$JETTY_BASE -├── resources -│ └── jetty-logging.properties -└── start.d - ├── http.ini - └── threadpool-virtual.ini ----- - -Now you can customize the `threadpool-virtual.ini` file to explicitly configure the thread pool and the virtual threads and then start Jetty: - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=threadpool-virtual,http"] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/chapter.adoc deleted file mode 100644 index 9b5d87e0cd10..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/chapter.adoc +++ /dev/null @@ -1,31 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-sessions]] -=== HTTP Session Management - -HTTP sessions are a concept within the Servlet API which allow requests to store and retrieve information across the time a user spends in an application. -Jetty offers a number of pluggable alternatives for managing and distributing/persisting sessions. -Choosing the best alternative is an important consideration for every application as is the correct configuration to achieve optimum performance. - -include::session-overview.adoc[] -include::session-base.adoc[] -include::session-cache.adoc[] -include::session-filesystem.adoc[] -include::session-jdbc.adoc[] -include::session-mongodb.adoc[] -include::session-infinispan.adoc[] -include::session-hazelcast.adoc[] -include::session-gcloud.adoc[] -include::session-memcached.adoc[] -include::session-usecases.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-base.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-base.adoc deleted file mode 100644 index 7e4e0f4515c1..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-base.adoc +++ /dev/null @@ -1,76 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-base]] -==== The Base Session Module - -The `sessions` module is the base module that all other session modules depend upon. -As such it will be _transitively_ enabled if you enable any of the other session modules: you need to _explicitly_ enable it if you wish to _change_ any settings from their defaults. - -Enabling the `sessions` module puts the `$JETTY_HOME/etc/sessions/id-manager.xml` file onto the execution path and generates a `$JETTY_BASE/start.d/sessions.ini` file. - -The `id-manager.xml` file instantiates a `DefaultSessionIdManager` and `HouseKeeper`. -The former is used to generate and manage session ids whilst the latter is responsible for periodic xref:og-session-base-scavenge[scavenging] of expired sessions. - -===== Configuration - -The `$JETTY_BASE/start.d/sessions.ini` file contains these configuration properties: - -jetty.sessionIdManager.workerName:: -This uniquely identifies the jetty server instance and is applied to the `SessionIdManager`. -You can either provide a value for this property, or you can allow Jetty to try and synthesize a `workerName` - the latter option is _only_ advisable in the case of a single, non-clustered deployment. -There are two ways a default `workerName` can be synthesized: - -* if running on Google AppEngine, the `workerName` will be formed by concatenating the values of the environment variables `JETTY_WORKER_INSTANCE` and `GAE_MODULE_INSTANCE` -* otherwise, the `workerName` will be formed by concatenating the environment variable `JETTY_WORKER_INSTANCE` and the literal `0`. - -So, if you're not running on Google AppEngine, and you haven't configured one, the workerName will always be: `node0`. - -IMPORTANT: If you have more than one Jetty instance, it is *crucial* that you configure the `workerName` differently for each instance. - -jetty.sessionScavengeInterval.seconds:: -This is the period in _seconds_ between runs of the `HouseKeeper`, responsible for orchestrating the removal of expired sessions. -By default it will run approximately every 600 secs (ie 10 mins). -As a rule of thumb, you should ensure that the xref:og-session-base-scavenge[scavenge] interval is shorter than the `` of your sessions to ensure that they are promptly scavenged. -On the other hand, if you have a backend store configured for your sessions, xref:og-session-base-scavenge[scavenging] too frequently can increase the load on it. - -CAUTION: Don't forget that the `` is specified in `web.xml` in _minutes_ and the value of the `jetty.sessionScavengeInterval.seconds` is in _seconds_. - -[[og-session-base-scavenge]] -===== Session Scavenging - -The `HouseKeeper` is responsible for the periodic initiation of session scavenge cycles. -The `jetty.sessionScavengeInterval.seconds` property in `$JETTY_BASE/start.d/sessions.ini` controls the periodicity of the cycle. - -[NOTE] -==== -The HouseKeeper semi-randomly adds an additional 10% to the configured `sessionScavengeInterval`. -This is to prevent multiple nodes in a cluster that are all started at once from syncing up scavenge cycles and placing extra load on the configured persistence mechanism. -==== - -A session whose expiry time has been exceeded is considered eligible for scavenging. -The session might be present in a `SessionCache` and/or present in the session persistence/clustering mechanism. - -Scavenging occurs for all contexts on a server at every cycle. -The `HouseKeeper` sequentially asks the `SessionHandler` in each context to find and remove expired sessions. -The `SessionHandler` works with the `SessionDataStore` to evaluate candidates for expiry held in the `SessionCache`, and also to sweep the persistence mechanism to find expired sessions. - -The sweep takes two forms: once per cycle the `SessionDataStore` searches for sessions for its own context that have expired; infrequently, the `SessionDataStore` will widen the search to expired sessions in all contexts. -The former finds sessions that are no longer in this context's `SessionCache`, and using some heuristics, are unlikely to be in the `SessionCache` of the same context on another node either. -These sessions will be loaded and fully expired, meaning that `HttpSessionListener.destroy()` will be called for them. -The latter finds sessions that have not been disposed of by scavenge cycles on any other context/node. -As these will be sessions that expired a long time ago, and may not be appropriate to load by the context doing the scavenging, these are summarily deleted without `HttpSessionListener.destroy()` being called. - -A combination of these sweeps should ensure that the persistence mechanism does not fill over time with expired sessions. - -As aforementioned, the sweep period needs to be short enough to find expired sessions in a timely fashion, but not so often that it overloads the persistence mechanism. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-cache.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-cache.adoc deleted file mode 100644 index 3eca5112bdfa..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-cache.adoc +++ /dev/null @@ -1,102 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-cache]] -==== Modules for HTTP Session Caching - -In this section we will look at the alternatives for the `SessionCache`, i.e. the L1 cache of in-use session objects. -Jetty ships with 2 alternatives: an in-memory cache, and a null cache. -The latter does not actually do any caching of sessions, and can be useful if you either want to minimize your support for sessions, or you are in a clustered deployment without a sticky loadbalancer. - -The xref:og-session-usecases[scenarios] go into more detail on this. - -[[og-session-cache-hash]] -===== Caching in Memory - -If you wish to change any of the default configuration values you should enable the `session-cache-hash` xref:og-modules[module]. -The name `"hash"` harks back to historical Jetty session implementations, whereby sessions were kept in memory using a HashMap. - -====== Configuration - -The `$JETTY_BASE/start.d/session-cache-hash.ini` contains the following configurable properties: - -jetty.session.evictionPolicy:: -Integer, default -1. -This controls whether session objects that are held in memory are subject to eviction from the cache. -Eviction means that the session is removed from the cache. -This can reduce the memory footprint of the cache and can be useful if you have a lot of sessions. -Eviction is usually used in conjunction with a `SessionDataStore` that persists sessions. -The eviction strategies and their corresponding values are: - -1 (NO EVICTION)::: - sessions are never evicted from the cache. - The only way they leave are via expiration or invalidation. - 0 (EVICT AFTER USE)::: - sessions are evicted from the cache as soon as the last active request for it finishes. - The session will be passed to the `SessionDataStore` to be written out before eviction. - >= 1 (EVICT ON INACTIVITY)::: - any positive number is the time in seconds after which a session that is in the cache but has not experienced any activity will be evicted. - Use the `jetty.session.saveOnInactiveEvict` property to force a session write before eviction. - -NOTE: If you are not using one of the session store modules, ie one of the ``session-store-xxxx``s, then sessions will be lost when the context is stopped, or the session is evicted. - -jetty.session.saveOnInactiveEvict:: -Boolean, default `false`. -This controls whether a session will be persisted to the `SessionDataStore` if it is being evicted due to the EVICT ON INACTIVITY policy. -Usually sessions will be written to the `SessionDataStore` whenever the last simultaneous request exits the session. -However, as `SessionDataStores` can be configured to skip some writes (see the documentation for the `session-store-xxx` module that you are using), this option is provided to ensure that the session will be written out. - -NOTE: Be careful with this option, as in clustered scenarios it would be possible to "re-animate" a session that has actually been deleted by another node. - -jetty.session.saveOnCreate:: -Boolean, default `false`. -Controls whether a session that is newly created will be immediately saved to the `SessionDataStore` or lazily saved as the last request for the session exits. -This can be useful if the request dispatches to another context and needs to re-use the same session id. - -jetty.session.removeUnloadableSessions:: -Boolean, default `false`. -Controls whether the session cache should ask a `SessionDataStore` to delete a session that cannot be restored - for example because it is corrupted. - -jetty.session.flushOnResponseCommit:: -Boolean, default `false`. -If true, if a session is "dirty" - ie its attributes have changed - it will be written to the `SessionDataStore` as the response is about to commit. -This ensures that all subsequent requests whether to the same or different node will see the updated session data. -If false, a dirty session will only be written to the backing store when the last simultaneous request for it leaves the session. - -jetty.session.invalidateOnShutdown:: -Boolean, default `false`. -If true, when a context is shutdown, all sessions in the cache are invalidated and deleted both from the cache and from the `SessionDataStore`. - -[[og-session-cache-null]] -===== No Caching - -You may need to use the `session-cache-null` module if your clustering setup does not have a sticky load balancer, or if you want absolutely minimal support for sessions. -If you enable this module, but you don't enable a module that provides session persistence (ie one of the `session-store-xxx` modules), then sessions will _neither_ be retained in memory _nor_ persisted. - -====== Configuration - -The `$JETTY_BASE/start.d/session-cache-null.ini` contains the following configurable properties: - -jetty.session.saveOnCreate:: -Boolean, default `false`. -Controls whether a session that is newly created will be immediately saved to the `SessionDataStore` or lazily saved as the last request for the session exits. -This can be useful if the request dispatches to another context and needs to re-use the same session id. - -jetty.session.removeUnloadableSessions:: -Boolean, default `false`. -Controls whether the session cache should ask a `SessionDataStore` to delete a session that cannot be restored - for example because it is corrupted. - -jetty.session.flushOnResponseCommit:: -Boolean, default `false`. -If true, if a session is "dirty" - ie its attributes have changed - it will be written to the backing store as the response is about to commit. -This ensures that all subsequent requests whether to the same or different node will see the updated session data. -If false, a dirty session will only be written to the backing store when the last simultaneous request for it leaves the session. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-filesystem.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-filesystem.adoc deleted file mode 100644 index 18ed6310a90b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-filesystem.adoc +++ /dev/null @@ -1,76 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-filesystem]] -==== Modules for Persistent HTTP Sessions: File System - -The `session-store-file` Jetty module supports persistent storage of session data in a filesystem. - -IMPORTANT: Persisting sessions to the local file system should *never* be used in a clustered environment. - -Enabling this module creates the `$JETTY_BASE/sessions` directory. -By default session data will be saved to this directory, one file representing each session. - -File names follow this pattern: - -`+[expiry]_[contextpath]_[virtualhost]_[id]+` - -expiry:: -This is the expiry time in milliseconds since the epoch. - -contextpath:: -This is the context path with any special characters, including `/`, replaced by the `_` underscore character. -For example, a context path of `/catalog` would become `_catalog`. -A context path of simply `/` becomes just `__`. - -virtualhost:: -This is the first virtual host associated with the context and has the form of 4 digits separated by `.` characters: `+[digit].[digit].[digit].[digit]+`. -If there are no virtual hosts associated with a context, then `0.0.0.0` is used. - -id:: -This is the unique id of the session. - -Putting all of the above together as an example, a session with an id of `node0ek3vx7x2y1e7pmi3z00uqj1k0` for the context with path `/test` with no virtual hosts and an expiry of `1599558193150` would have a file name of: - -`1599558193150__test_0.0.0.0_node0ek3vx7x2y1e7pmi3z00uqj1k0` - -===== Configuration - -The `$JETTY_BASE/start.d/sessions.ini` file contains the following properties which may be modified to customise filesystem session storage: - -jetty.session.storeDir:: -The default is `$JETTY_BASE/sessions`. -This is a path that defines the location for storage of session files. - -jetty.session.file.deleteUnrestorableFiles:: -Boolean, default `false`. -If set to `true`, unreadable files will be deleted. -This is useful to prevent repeated logging of the same error when the scavenger periodically (re-)attempts to load the corrupted information for a session in order to expire it. - -jetty.session.gracePeriod.seconds:: -Integer, default 3600. -Used during session xref:og-session-base-scavenge[scavenging]. -Multiples of this period are used to define how long ago a stored session must have expired before it should be xref:og-session-base-scavenge[scavenged]. - -jetty.session.savePeriod.seconds:: -Integer, in seconds, default is `0`. -Whenever a session is accessed by a request, its `lastAccessTime` and `expiry` are updated. -Even if your sessions are read-mostly, the `lastAccessTime` and `expiry` will always change. -For heavily-used, read-mostly sessions you can save some time by skipping some writes for sessions for which only these fields have changed (ie no session attributes changed). -The value of this property is used to skip writes for these kinds of sessions: the session will only be written out if the time since the last write exceeds the value of this property. - -[WARNING] -==== -You should be careful in the use of this property in clustered environments: if you set too large a value for this property, the session may not be written out sufficiently often to update its `expiry` time thus making it appear to other nodes that it has expired. -Thorough consideration of the `maxIdleTime` of the session when setting the `savePeriod` is imperative - it would be undesirable to set a `savePeriod` that is larger than the `maxIdleTime`. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-gcloud.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-gcloud.adoc deleted file mode 100644 index 47b45843a88a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-gcloud.adoc +++ /dev/null @@ -1,146 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-gcloud]] -==== Modules for Persistent HTTP Sessions: Google Cloud DataStore - -Jetty can store http session information into GCloud by enabling the `session-store-gcloud` module. - -===== Preparation - -You will first need to create a project and enable the Google Cloud api: link:https://cloud.google.com/docs/authentication#preparation[]. -Take note of the project id that you create in this step as you need to supply it in later steps. - -===== Communicating with GCloudDataStore - -====== When Running Jetty Outside of Google Infrastructure - -Before running Jetty, you will need to choose one of the following methods to set up the local environment to enable remote GCloud DataStore communications. - -1. Using the GCloud SDK: - * Ensure you have the GCloud SDK installed: link:https://cloud.google.com/sdk/?hl=en[] - * Use the GCloud tool to set up the project you created in the preparation step: `gcloud config set project PROJECT_ID` - * Use the GCloud tool to authenticate a google account associated with the project created in the preparation step: `gcloud auth login ACCOUNT` - -2. Using environment variables - * Define the environment variable `GCLOUD_PROJECT` with the project id you created in the preparation step. - * Generate a JSON link:https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts[service account key] and then define the environment variable `GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/key.json` - -====== When Running Jetty Inside of Google Infrastructure - -The Google deployment tools will automatically configure the project and authentication information for you. - -===== Configuring Indexes for Session Data - -Using some special, composite indexes can speed up session search operations, although it may make write operations slower. -By default, indexes will _not_ be used. -In order to use them, you will need to manually upload a file that defines the indexes. -This file is named `index.yaml` and you can find it in your distribution in `$JETTY_BASE/etc/sessions/gcloud/index.yaml`. - -Follow the instructions link:https://cloud.google.com/datastore/docs/tools/#the_development_workflow_using_gcloud[here] to upload the pre-generated `index.yaml` file. - -===== Communicating with the GCloudDataStore Emulator - -To enable communication using the GCloud Emulator: - -* Ensure you have the GCloud SDK installed: link:https://cloud.google.com/sdk/?hl=en[] -* Follow the instructions link:https://cloud.google.com/datastore/docs/tools/datastore-emulator[here] on how to start the GCloud datastore emulator, and how to propagate the environment variables that it creates to the terminal in which you run Jetty. - -===== Enabling the Google Cloud DataStore Module - -The `session-store-gcloud` module provides GCloud support for storing session data. - -Because the Google Cloud DataStore is not a technology provided by the Eclipse Foundation, when enabling the module you will be prompted to assent to the licenses of the external vendor. - -As GCloud requires certain Java Commons Logging features to work correctly, Jetty routes these through SLF4J. -By default Jetty implements the SLF4J api, but you can choose a different logging implementation by following the instructions xref:og-server-logging[here] - -IMPORTANT: If you want to use updated versions of the jar files automatically downloaded during the module enablement, you can place them in the associated `$JETTY_BASE/lib/` directory and use the `--skip-file-validation=` command line option to prevent errors when starting your server. - -==== Configuration - -The `$JETTY_BASE/start.d/session-store-gcloud.ini` file contains all of the configurable properties for the `session-store-gcloud` module: - -jetty.session.gcloud.maxRetries:: -Integer. -Default 5. -Maximum number of retries to connect to GCloud DataStore to write a session. - -jetty.session.gcloud.backoffMs:: -Integer in milliseconds. -Default 1000. -Number of milliseconds between successive attempts to connect to the GCloud DataStore to write a session. - -jetty.session.gracePeriod.seconds:: -Integer, in seconds. -Default 3600. -Used during session xref:og-session-base-scavenge[scavenging]. -Multiples of this period are used to define how long ago a stored session must have expired before it should be xref:og-session-base-scavenge[scavenged]. - -jetty.session.savePeriod.seconds:: -Integer, in seconds, default is `0`. -Whenever a session is accessed by a request, its `lastAccessTime` and `expiry` are updated. -Even if your sessions are read-mostly, the `lastAccessTime` and `expiry` will always change. -For heavily-used, read-mostly sessions you can save some time by skipping some writes for sessions for which only these fields have changed (ie no session attributes changed). -The value of this property is used to skip writes for these kinds of sessions: the session will only be written out if the time since the last write exceeds the value of this property. - -[WARNING] -==== -You should be careful in the use of this property in clustered environments: if you set too large a value for this property, the session may not be written out sufficiently often to update its `expiry` time thus making it appear to other nodes that it has expired. -Thorough consideration of the `maxIdleTime` of the session when setting the `savePeriod` is imperative - it would be undesirable to set a `savePeriod` that is larger than the `maxIdleTime`. -==== - -jetty.session.gcloud.namespace:: -Optional. -Sets the namespace for GCloud Datastore to use. -If set, partitions the visibility of session data between webapps, which is helpful for multi-tenant deployments. -More information can be found link:https://cloud.google.com/datastore/docs/concepts/multitenancy[here.] - -Configuration of the stored session object and its fields names-:: -You should very rarely, if ever, need to change these defaults. -jetty.session.gcloud.model.kind::: -The default is "GCloudSession". -This is the type of the object that is stored in GCloud. -jetty.session.gcloud.model.id::: -The default is "id". -This is the session id. -jetty.session.gcloud.model.contextPath::: -The default is "contextPath". -This is the canonicalized context path of the context to which the session belongs. -jetty.session.gcloud.model.vhost::: -The default is "vhost". -This is the canonicalized virtual host of the context to which the session belongs. -jetty.session.gcloud.model.accessed::: -The default is "accessed". -This is the current access time of the session. -jetty.session.gcloud.model.lastAccessed::: -The default is "lastAccessed". -This is the last access time of the session. -jetty.session.gcloud.model.createTime::: -The default is "createTime". -This is the time, in ms since the epoch, at which the session was created. -jetty.session.gcloud.model.cookieSetTime::: -The default is "cookieSetTime". -This is the time at which the session cookie was last set. -jetty.session.gcloud.model.lastNode::: -The default is "lastNode". -This is the `workerName` of the last node to manage the session. -jetty.session.gcloud.model.expiry::: -The default is "expiry". -This is the time, in ms since the epoch, at which the session will expire. -jetty.session.gcloud.model.maxInactive::: -The default is "maxInactive". -This is the session timeout in ms. -jetty.session.gcloud.model.attributes::: -The default is "attributes". -This is a map of all the session attributes. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-hazelcast.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-hazelcast.adoc deleted file mode 100644 index 47aca91d2839..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-hazelcast.adoc +++ /dev/null @@ -1,128 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-hazelcast]] -==== Modules for Persistent HTTP Sessions: Hazelcast - -Hazelcast can be used to cluster session information in one of two modes: either remote or embedded. -Remote mode means that Hazelcast will create a client to talk to other instances, possibly on other nodes. -Embedded mode means that Hazelcast will start a local instance and communicate with that. - -[[og-session-hazelcast-remote]] -===== Remote Hazelcast Clustering - -Enabling the `session-store-hazelcast-remote` module allows jetty to communicate with a remote Hazelcast instance to cluster session data. - -Because Hazelcast is not a technology provided by the Eclipse Foundation, you will be prompted to assent to the licenses of the external vendor (Apache in this case). - -Hazelcast-specific jar files will be downloaded and saved to a directory named `$JETTY_BASE/lib/hazelcast/`. - -NOTE: If you have updated versions of the jar files automatically downloaded by Jetty, you can place them in the associated `$JETTY_BASE/lib/` directory and use the `--skip-file-validation=` command line option to prevent errors when starting your server. - -====== Configuration - -The `start.d/session-store-hazelcast-remote.ini` contains a list of all the configurable options for the Hazelcast module: - -jetty.session.hazelcast.mapName:: -The default is "jetty-distributed-session-map". -This is the name of the Map in Hazelcast where sessions will be stored. - -jetty.session.hazelcast.onlyClient:: -Boolean, default `true`. -The Hazelcast instance will be configured in client mode. - -jetty.session.hazelcast.configurationLocation:: -Optional. -This is the path to an external Hazelcast xml configuration file. - -jetty.session.hazelcast.useQueries:: -Boolean, default `false`. -If `true`, Jetty will use Hazelcast queries to find sessions to xref:og-session-base-scavenge[scavenge]. -If `false` sessions that are not currently in a xref:og-session-cache[session cache] cannot be xref:og-session-base-scavenge[scavenged], and will need to be removed by some external process. - -jetty.session.hazelcast.addresses:: -Optional. -These are the addresses of remote Hazelcast instances with which to communicate. - -jetty.session.gracePeriod.seconds:: -Integer, in seconds. -Default 3600. -Used during session xref:og-session-base-scavenge[scavenging]. -Multiples of this period are used to define how long ago a stored session must have expired before it should be xref:og-session-base-scavenge[scavenged]. - -jetty.session.savePeriod.seconds:: -Integer, in seconds, default is `0`. -Whenever a session is accessed by a request, its `lastAccessTime` and `expiry` are updated. -Even if your sessions are read-mostly, the `lastAccessTime` and `expiry` will always change. -For heavily-used, read-mostly sessions you can save some time by skipping some writes for sessions for which only these fields have changed (ie no session attributes changed). -The value of this property is used to skip writes for these kinds of sessions: the session will only be written out if the time since the last write exceeds the value of this property. - -[WARNING] -==== -You should be careful in the use of this property in clustered environments: if you set too large a value for this property, the session may not be written out sufficiently often to update its `expiry` time thus making it appear to other nodes that it has expired. -Thorough consideration of the `maxIdleTime` of the session when setting the `savePeriod` is imperative - it would be undesirable to set a `savePeriod` that is larger than the `maxIdleTime`. -==== - -IMPORTANT: Be aware that if your session attributes contain classes from inside your webapp (or Jetty classes) then you will need to put these classes onto the classpath of all of your Hazelcast instances. - -[[og-session-hazelcast-embedded]] -===== Embedded Hazelcast Clustering - -This will run an in-process instance of Hazelcast. -This can be useful for example during testing. -To enable this you enable the `session-store-hazelcast-embedded` module. - -Because Hazelcast is not a technology provided by the Eclipse Foundation, you will be prompted to assent to the licenses of the external vendor (Apache in this case). - -Hazelcast-specific jar files will be downloaded to a directory named `$JETTY_BASE/lib/hazelcast/`. - -====== Configuration - -The `$JETTY_BASE/start.d/start.d/session-store-hazelcast-embedded.ini` contains a list of all the configurable options for the Hazelcast module: - -jetty.session.hazelcast.mapName:: -The default is "jetty-distributed-session-map". -This is the name of the Map in Hazelcast where sessions will be stored. -jetty.session.hazelcast.hazelcastInstanceName -Default is "JETTY_DISTRIBUTED_SESSION_INSTANCE". -This is the unique name of the Hazelcast instance that will be created. - -jetty.session.hazelcast.configurationLocation:: -Optional. -This is the path to an external Hazelcast xml configuration file. - -jetty.session.hazelcast.useQueries:: -Boolean, default `false'. -If `true`, Jetty will use Hazelcast queries to find expired sessions to xref:og-session-base-scavenge[scavenge]. -If `false` sessions that are not currently in a xref:og-session-cache[session cache] cannot be xref:og-session-base-scavenge[scavenged], and will need to be removed by some external process. - -jetty.session.gracePeriod.seconds:: -Integer, in seconds. -Default 3600. -Used during session xref:og-session-base-scavenge[scavenging]. -Multiples of this period are used to define how long ago a stored session must have expired before it should be xref:og-session-base-scavenge[scavenged]. - -jetty.session.savePeriod.seconds:: -Integer, in seconds, default is `0`. -Whenever a session is accessed by a request, its `lastAccessTime` and `expiry` are updated. -Even if your sessions are read-mostly, the `lastAccessTime` and `expiry` will always change. -For heavily-used, read-mostly sessions you can save some time by skipping some writes for sessions for which only these fields have changed (ie no session attributes changed). -The value of this property is used to skip writes for these kinds of sessions: the session will only be written out if the time since the last write exceeds the value of this property. - -[WARNING] -==== -You should be careful in the use of this property in clustered environments: if you set too large a value for this property, the session may not be written out sufficiently often to update its `expiry` time thus making it appear to other nodes that it has expired. -Thorough consideration of the `maxIdleTime` of the session when setting the `savePeriod` is imperative - it would be undesirable to set a `savePeriod` that is larger than the `maxIdleTime`. -==== - -IMPORTANT: If your session attributes contain classes from inside your webapp (or jetty classes) then you will need to put these classes onto the classpath of all of your hazelcast instances. In the case of embedded hazelcast, as it is started before your webapp, it will NOT have access to your webapp's classes - you will need to extract these classes and put them onto the jetty server's classpath. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-infinispan.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-infinispan.adoc deleted file mode 100644 index cbf6624783a4..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-infinispan.adoc +++ /dev/null @@ -1,160 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-infinispan]] -==== Modules for Persistent HTTP Sessions: Infinispan - -In order to persist/cluster sessions using Infinispan, Jetty needs to know how to contact Infinispan. -There are two options: a remote Infinispan instance, or an in-process Infinispan instance. -The former is referred to as "remote" Infinispan and the latter as "embedded" Infinispan. -If you wish Jetty to be able to xref:og-session-base-scavenge[scavenge] expired sessions, you will also need to enable the appropriate `infinispan-[remote|embedded]-query` module. - -[[og-session-infinispan-remote]] -===== Remote Infinispan Session Module - -The `session-store-infinispan-remote` module configures Jetty to talk to an external Infinispan instance to store session data. - -Because Infinispan is not a technology provided by the Eclipse Foundation, you will be prompted to assent to the licenses of the external vendor (Apache in this case). - -Infinispan-specific jar files are download to the directory named `$JETTY_BASE/lib/infinispan/`. - -In addition to adding these modules to the classpath of the server it also added several ini configuration files to the `$JETTY_BASE/start.d` directory. - -NOTE: If you have updated versions of the jar files automatically downloaded by Jetty, you can place them in the associated `$JETTY_BASE/lib/` directory and use the `--skip-file-validation=` command line option to prevent errors when starting your server. - -====== Configuration - -The `$JETTY_BASE/start.d/session-store-infinispan-remote.ini` contains the following configurable properties: - -jetty.session.infinispan.remoteCacheName:: -Default `"sessions"`. -This is the name of the cache in Infinispan where sessions will be stored. - -jetty.session.infinispan.idleTimeout.seconds:: -Integer, in seconds, default `0`. -This is the amount of time, in seconds, that a session entry in Infinispan can be idle (ie neither read nor written) before Infinispan will delete its entry. -Usually, you do *not* want to set a value for this, as you want Jetty to manage all session expiration (and call any HttpSessionListeners). -You *should* enable the xref:og-session-infinispan-remote-query[infinispan-remote-query] to allow jetty to xref:og-session-base-scavenge[scavenge] for expired sessions. -If you do not, then there is the possibility that sessions can be left in Infinispan but no longer referenced by any Jetty node (so called "zombie" or "orphan" sessions), in which case you can use this feature to ensure their removal. - -IMPORTANT: You should make sure that the number of seconds you specify is larger than the configured `maxIdleTime` for sessions. - -jetty.session.gracePeriod.seconds:: -Integer, default 3600. -Used during session xref:og-session-base-scavenge[scavenging]. -Multiples of this period are used to define how long ago a stored session must have expired before it should be xref:og-session-base-scavenge[scavenged]. - -jetty.session.savePeriod.seconds:: -Integer, in seconds, default is `0`. -Whenever a session is accessed by a request, its `lastAccessTime` and `expiry` are updated. -Even if your sessions are read-mostly, the `lastAccessTime` and `expiry` will always change. -For heavily-used, read-mostly sessions you can save some time by skipping some writes for sessions for which only these fields have changed (ie no session attributes changed). -The value of this property is used to skip writes for these kinds of sessions: the session will only be written out if the time since the last write exceeds the value of this property. - -[WARNING] -==== -You should be careful in the use of this property in clustered environments: if you set too large a value for this property, the session may not be written out sufficiently often to update its `expiry` time thus making it appear to other nodes that it has expired. -Thorough consideration of the `maxIdleTime` of the session when setting the `savePeriod` is imperative - it would be undesirable to set a `savePeriod` that is larger than the `maxIdleTime`. -==== - -[[og-session-infinispan-remote-query]] -===== Remote Infinispan Query Module - -The `infinispan-remote-query` module allows Jetty to xref:og-session-base-scavenge[scavenge] expired sessions. -Note that this is an *additional* module, to be used in conjunction with the `session-store-infinispan-remote` module. - -There are no configuration properties associated with this module. - -[[og-session-infinispan-embedded]] -===== Embedded Infinispan Session Module - -Enabling the `session-store-infinispan-embedded` module runs an in-process instance of Infinispan. - -Because Infinispan is not a technology provided by the Eclipse Foundation, you will be prompted to assent to the licenses of the external vendor (Apache in this case). -Infinispan-specific jar files will be downloaded and saved to a directory named `$JETTY_BASE/lib/infinispan/`. - -NOTE: If you have updated versions of the jar files automatically downloaded by Jetty, you can place them in the associated `$JETTY_BASE/lib/` directory and use the `--skip-file-validation=` command line option to prevent errors when starting your server. - -====== Configuration - -The `$JETTY_BASE/start.d/session-store-infinispan-embedded.ini` contains the following configurable properties: - -jetty.session.infinispan.idleTimeout.seconds:: -Integer, in seconds, default `0`. -This is the amount of time, in seconds, that a session entry in Infinispan can be idle (ie neither read nor written) before Infinispan will delete its entry. -Usually, you do *not* want to set a value for this, as you want Jetty to manage all session expiration (and call any HttpSessionListeners). -You *should* enable the xref:og-session-infinispan-embedded-query[infinispan-embedded-query] to allow Jetty to xref:og-session-base-scavenge[scavenge] for expired sessions. -If you do not, then there is the possibility that expired sessions can be left in Infinispan. - -IMPORTANT: You should make sure that the number of seconds you specify is larger than the configured `maxIdleTime` for sessions. - -jetty.session.gracePeriod.seconds:: -Integer, default 3600. -Used during session xref:og-session-base-scavenge[scavenging]. -Multiples of this period are used to define how long ago a stored session must have expired before it should be xref:og-session-base-scavenge[scavenged]. - -jetty.session.savePeriod.seconds:: -Integer, in seconds, default is `0`. -Whenever a session is accessed by a request, its `lastAccessTime` and `expiry` are updated. -Even if your sessions are read-mostly, the `lastAccessTime` and `expiry` will always change. -For heavily-used, read-mostly sessions you can save some time by skipping some writes for sessions for which only these fields have changed (ie no session attributes changed). -The value of this property is used to skip writes for these kinds of sessions: the session will only be written out if the time since the last write exceeds the value of this property. - -[WARNING] -==== -Thorough consideration of the `maxIdleTime` of the session when setting the `savePeriod` is imperative - it would be undesirable to set a `savePeriod` that is larger than the `maxIdleTime`. -==== - -[[og-session-infinispan-embedded-query]] -===== Embedded Infinispan Query Module - -The `infinispan-embedded-query` module allows Jetty to xref:og-session-base-scavenge[scavenge] expired sessions. - -There are no configuration properties associated with this module. - -===== Converting Session Format for Jetty-9.4.13 - -From Jetty-9.4.13 onwards, we have changed the format of the serialized session when using a remote cache (ie using hotrod). -Prior to release 9.4.13 we used the default Infinispan serialization, however this was not able to store sufficient information to allow Jetty to properly deserialize session attributes in all circumstances. -See issue link:https://github.com/jetty/jetty.project/issues/2919[] for more background. - -We have provided a conversion program which will convert any sessions stored in Infinispan to the new format. - -IMPORTANT: We recommend that you backup your stored sessions before running the conversion program. - -How to use the converter: - ----- -java -cp jetty-servlet-api-4.0.2.jar:jetty-util-{VERSION}.jar:jetty-server-{VERSION}.jar:infinispan-remote-9.1.0.Final.jar:jetty-infinispan-{VERSION}.jar:[other classpath] org.eclipse.jetty.session.infinispan.InfinispanSessionLegacyConverter - -Usage: InfinispanSessionLegacyConverter [-Dhost=127.0.0.1] [-Dverbose=true|false] [check] ----- - -The classpath:: -Must contain the servlet-api, jetty-util, jetty-server, jetty-infinispan and infinispan-remote jars. If your sessions contain attributes that use application classes, you will also need to also put those classes onto the classpath. If your session has been authenticated, you may also need to include the jetty-security and jetty-http jars on the classpath. - -Parameters:: -When used with no arguments the usage message is printed. When used with the `cache-name` parameter the conversion is performed. When used with both `cache-name` and `check` parameters, sessions are checked for whether or not they are converted. --Dhost::: you can optionally provide a system property with the address of your remote Infinispan server. Defaults to the localhost. --Dverbose::: defaults to false. If true, prints more comprehensive stacktrace information about failures. Useful to diagnose why a session is not converted. -cache-name::: the name of the remote cache containing your sessions. This is mandatory. -check::: the optional check command will verify sessions have been converted. Use it _after_ doing the conversion. - -To perform the conversion, run the InfinispanSessionLegacyConverter with just the `cache-name`, and optionally the `host` system property. -The following command will attempt to convert all sessions in the cached named `my-remote-cache` on the machine `myhost`, ensuring that application classes in the `/my/custom/classes` directory are on the classpath: - ----- -java -cp jetty-servlet-api-4.0.2.jar:jetty-util-{VERSION}.jar:jetty-server-{VERSION}.jar:infinispan-remote-9.1.0.Final.jar:jetty-infinispan-{VERSION}.jar:/my/custom/classes org.eclipse.jetty.session.infinispan.InfinispanSessionLegacyConverter -Dhost=myhost my-remote-cache ----- - -If the converter fails to convert a session, an error message and stacktrace will be printed and the conversion will abort. The failed session should be untouched, however _it is prudent to take a backup of your cache before attempting the conversion_. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-jdbc.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-jdbc.adoc deleted file mode 100644 index b1f304e9dc14..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-jdbc.adoc +++ /dev/null @@ -1,136 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-jdbc]] -==== Modules for Persistent HTTP Sessions: JDBC - -Enabling the `session-store-jdbc` module configures Jetty to persist session data in a relational database. - -===== Configuration - -After enabling the module, the `$JETTY_BASE/start.d/session-store-jdbc.ini` file contains the following customizable properties: - -jetty.session.gracePeriod.seconds:: -Integer, default 3600. -Used during session xref:og-session-base-scavenge[scavenging]. -Multiples of this period are used to define how long ago a stored session must have expired before it should be xref:og-session-base-scavenge[scavenged]. - -jetty.session.savePeriod.seconds:: -Integer, in seconds, default is `0`. -Whenever a session is accessed by a request, its `lastAccessTime` and `expiry` are updated. -Even if your sessions are read-mostly, the `lastAccessTime` and `expiry` will always change. -For heavily-used, read-mostly sessions you can save some time by skipping some writes for sessions for which only these fields have changed (ie no session attributes changed). -The value of this property is used to skip writes for these kinds of sessions: the session will only be written out if the time since the last write exceeds the value of this property. - -[WARNING] -==== -You should be careful in the use of this property in clustered environments: if you set too large a value for this property, the session may not be written out sufficiently often to update its `expiry` time thus making it appear to other nodes that it has expired. -Thorough consideration of the `maxIdleTime` of the session when setting the `savePeriod` is imperative - it would be undesirable to set a `savePeriod` that is larger than the `maxIdleTime`. -==== - -db-connection-type:: -Default `datasource`. -Set to either `datasource` or `driver` depending on the type of connection being used. -Depending which you select, there are additional properties available: - -`datasource`::: -jetty.session.jdbc.datasourceName:::: -Name of the remote datasource. - -`driver`::: -jetty.session.jdbc.driverClass:::: -Name of the JDBC driver that controls access to the remote database, such as `com.mysql.jdbc.Driver` -jetty.session.jdbc.driverUrl:::: -URL of the database which includes the driver type, host name and port, service name and any specific attributes unique to the database, such as a username. -As an example, here is a mysql connection with the username appended: `jdbc:mysql://127.0.0.1:3306/sessions?user=sessionsadmin`. - -jetty.session.jdbc.blobType:: -Optional. -Default `blob` or `bytea` for Postgres. -This is the keyword used by the particular database to identify the blob data type. -If netiher default is suitable you can set this value explicitly. - -jetty.session.jdbc.longType:: -Optional. -Default `bigint` or `number(20)` for Oracle. -This is the keyword used by the particular database to identify the long integer data type. -Set this explicitly if neither of the default values is appropriate. - -jetty.session.jdbc.stringType:: -Optional. -Default `varchar`. -This is the keyword used by the particular database to identify character type. -If the default is not suitable, you can set this value explicitly. - -jetty.session.jdbc.schema.schemaName:: -jetty.session.jdbc.schema.catalogName:: -Optional. -The exact meaning of these two properties is dependent on your database vendor, but can broadly be described as further scoping for the session table name. -See link:https://en.wikipedia.org/wiki/Database_schema[] and link:https://en.wikipedia.org/wiki/Database_catalog[]. -These extra scoping names can come into play at startup time when Jetty determines if the session table already exists, or otherwise creates it on-the-fly. -If you have employed either of these concepts when you pre-created the session table, or you want to ensure that Jetty uses them when it auto-creates the session table, then you have two options: either set them explicitly, or let Jetty infer them from a database connection (obtained using either a Datasource or Driver according to the `db-connection-type` you have configured). -To set them explicitly, uncomment and supply appropriate values for the `jetty.session.jdbc.schema.schemaName` and/or `jetty.session.jdbc.schema.catalogName` properties. -Alternatively, to allow Jetty to infer them from a database connection, use the special string `INFERRED` instead. -If you leave them blank or commented out, then the sessions table will not be scoped by schema or catalog name. - -jetty.session.jdbc.schema.table:: -Default `JettySessions`. -This is the name of the table in which session data is stored. - -jetty.session.jdbc.schema.accessTimeColumn:: -Default `accessTime`. -This is the name of the column that stores the time - in ms since the epoch - at which a session was last accessed - -jetty.session.jdbc.schema.contextPathColumn:: -Default `contextPath`. -This is the name of the column that stores the `contextPath` of a session. - -jetty.session.jdbc.schema.cookieTimeColumn:: -Default `cookieTime`. -This is the name of the column that stores the time - in ms since the epoch - that the cookie was last set for a session. - -jetty.session.jdbc.schema.createTimeColumn:: -Default `createTime`. -This is the name of the column that stores the time - in ms since the epoch - at which a session was created. - -jetty.session.jdbc.schema.expiryTimeColumn:: -Default `expiryTime`. -This is name of the column that stores - in ms since the epoch - the time at which a session will expire. - -jetty.session.jdbc.schema.lastAccessTimeColumn:: -Default `lastAccessTime`. -This is the name of the column that stores the time - in ms since the epoch - that a session was previously accessed. - -jetty.session.jdbc.schema.lastSavedTimeColumn:: -Default `lastSavedTime`. -This is the name of the column that stores the time - in ms since the epoch - at which a session was last written. - -jetty.session.jdbc.schema.idColumn:: -Default `sessionId`. -This is the name of the column that stores the id of a session. - -jetty.session.jdbc.schema.lastNodeColumn:: -Default `lastNode`. -This is the name of the column that stores the `workerName` of the last node to write a session. - -jetty.session.jdbc.schema.virtualHostColumn:: -Default `virtualHost`. -This is the name of the column that stores the first virtual host of the context of a session. - -jetty.session.jdbc.schema.maxIntervalColumn:: -Default `maxInterval`. -This is the name of the column that stores the interval - in ms - during which a session can be idle before being considered expired. - -jetty.session.jdbc.schema.mapColumn:: -Default `map`. -This is the name of the column that stores the serialized attributes of a session. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-memcached.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-memcached.adoc deleted file mode 100644 index 852dfec4dd04..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-memcached.adoc +++ /dev/null @@ -1,45 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-memcached]] - -==== Modules for Persistent HTTP Sessions: The L2 Session Data Cache - -If your chosen persistence technology is slow, it can be helpful to locally cache the session data. -The `CachingSessionDataStore` is a special type of `SessionDataStore` that locally caches session data, which makes reads faster. It writes-through to your chosen type of `SessionDataStore` when session data changes. - -===== MemcachedSessionDataMap - -The `MemcachedSessionDataMap` uses `memcached` to perform caching of `SessionData`. - -To enable it with the Jetty distribution, enable the `session-store-cache` module, along with your chosen `session-store-xxxx` module. - -====== Configuration - -The `$JETTY_BASE/start.d/session-store-cache.ini` contains the following configurable properties: - -jetty.session.memcached.host:: -Default value is `localhost`. -This is the host on which the memcached server resides. - -jetty.session.memcached.port:: -Default value is `11211`. -This is the port on which the memcached server is listening. - -jetty.session.memcached.expirySec:: -Default value `0`. -This is the length of time in seconds that an item can remain in the memcached cache, where 0 indicates indefinitely. - -jetty.session.memcached.heartbeats:: -Default value `true`. -Whether the memcached system should generate heartbeats. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-mongodb.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-mongodb.adoc deleted file mode 100644 index 4349db147367..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-mongodb.adoc +++ /dev/null @@ -1,73 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-mongo]] -==== Modules for Persistent HTTP Sessions: MongoDB - -Enabling the `session-store-mongo` module configures Jetty to store session data in MongoDB. - -Because MongoDB is not a technology provided by the Eclipse Foundation, you will be prompted to assent to the licenses of the external vendor (Apache in this case) during the install. -Jars needed by MongoDB are downloaded and stored into a directory named `$JETTY_BASE/lib/nosql/`. - -IMPORTANT: If you want to use updated versions of the jar files automatically downloaded by Jetty, you can place them in the associated `$JETTY_BASE/lib/` directory and use the `--skip-file-validation=` command line option to prevent errors when starting your server. - -===== Configuration - -The `$JETTY_BASE/start.d/session-store-mongo.ini` file contains these configurable properties: - -jetty.session.mongo.dbName:: -Default is "HttpSessions". -This is the name of the database in MongoDB used to store the session collection. - -jetty.session.mongo.collectionName:: -Default is "jettySessions". -This is the name of the collection in MongoDB used to store all of the sessions. - -The connection type-:: -You can connect to MongoDB either using a host/port combination, or a URI. -By default, the host/port method is selected, but you can change this by commenting out the unwanted method, and uncommenting the other one. -connection-type=address::: -Used when utilizing a direct connection to the MongoDB server. -jetty.session.mongo.host:::: -Host name or address for the remote MongoDB instance. -jetty.session.mongo.port:::: -Port number for the remote MongoDB instance. -connection-type=uri::: -Used when utilizing MongoURI for secured connections. -jetty.session.mongo.connectionString:::: -The string defining the MongoURI value, such as `+mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]+`. -More information on how to format the MongoURI string can be found in the link:https://docs.mongodb.com/manual/reference/connection-string/[official documentation for mongo]. -[NOTE] -==== -You will only use *one* `connection-type` at a time, either `address` or `uri`. -If both are utilized in your `session-store-mongo.ini`, only the _last_ `connection-type` configured in the file will be used. -==== - -jetty.session.gracePeriod.seconds:: -Integer, in seconds. -Default 3600. -Used during session xref:og-session-base-scavenge[scavenging]. -Multiples of this period are used to define how long ago a stored session must have expired before it should be xref:og-session-base-scavenge[scavenged]. - -jetty.session.savePeriod.seconds:: -Integer, in seconds, default is `0`. -Whenever a session is accessed by a request, its `lastAccessTime` and `expiry` are updated. -Even if your sessions are read-mostly, the `lastAccessTime` and `expiry` will always change. -For heavily-used, read-mostly sessions you can save some time by skipping some writes for sessions for which only these fields have changed (ie no session attributes changed). -The value of this property is used to skip writes for these kinds of sessions: the session will only be written out if the time since the last write exceeds the value of this property. - -[WARNING] -==== -You should be careful in the use of this property in clustered environments: if you set too large a value for this property, the session may not be written out sufficiently often to update its `expiry` time thus making it appear to other nodes that it has expired. -Thorough consideration of the `maxIdleTime` of the session when setting the `savePeriod` is imperative - it would be undesirable to set a `savePeriod` that is larger than the `maxIdleTime`. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-overview.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-overview.adoc deleted file mode 100644 index aa84cd9238fc..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-overview.adoc +++ /dev/null @@ -1,81 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-overview]] -==== HTTP Session Overview - -===== Terminology - -Before diving into the specifics of how to plug-in and configure various alternative HTTP session management modules, let's review some useful terminology: - -Session:: -is a means of retaining information across requests for a particular user. -The Servlet Specification defines the semantics of sessions. -Some of the most important characteristics of sessions is that they have a unique id and that their contents cannot be shared between different contexts (although the id can be): if a session is invalidated in one context, then all other sessions that share the same id in other contexts will also be invalidated. -Sessions can expire or they can be explicitly invalidated. - -SessionIdManager:: -is responsible for allocating session ids. -A Jetty server can have at most 1 SessionIdManager. - -HouseKeeper:: -is responsible for periodically orchestrating the removal of expired sessions. -This process is referred to as xref:og-session-base-scavenge["scavenging"]. - -SessionHandler:: -is responsible for managing the lifecycle of sessions. -A context can have at most 1 `SessionHandler`. - -SessionCache:: -is a L1 cache of in-use session objects. -The `SessionCache` is used by the `SessionHandler`. - -SessionDataStore:: -is responsible for all clustering/persistence operations on sessions. -A `SessionCache` uses a `SessionDataStore` as a backing store. - -CachingSessionDataStore:: -is an L2 cache of session data. -A `SessionCache` can use a `CachingSessionDataStore` as its backing store. - -More details on these concepts can be found in the xref:{prog-guide}#pg-server-session[Programming Guide]. - -[NOTE] -==== -``SessionDataStore``s implementations interact with other, usually third party, systems responsible for storing and/or distributing session information. -Sessions can be distributed without being persisted. -They can also be persisted without being distributed. -Because persisting session information to a shared store is a very common way of distributing (also known as "clustering") sessions, in the documentation we will often refer to just "persisting". -==== - -[[og-session-modules]] -===== Session Modules - -There are a number of modules that offer pluggable alternatives for http session management. -You can design how you want to cache and store http sessions by selecting alternative combinations of session modules. - -For example, Jetty ships with two alternative implementations of the `SessionCache`: - -* one that caches sessions in memory: xref:og-session-cache-hash[`session-cache-hash`] -* one that does not actually cache: xref:og-session-cache-null[`session-cache-null`] - -There are at least 6 alternative implementations of the `SessionDataStore` that you can use to persist/distribute your http sessions: - -* file system storage: xref:og-session-filesystem[`session-store-file`] -* relational database storage: xref:og-session-jdbc[`session-store-jdbc`] -* NoSQL database storage: xref:og-session-mongo[`session-store-mongo`] -* Google Cloud datastore storage: xref:og-session-gcloud[`session-store-gcloud`] -* Hazelcast: xref:og-session-hazelcast-remote[`session-store-hazelcast-remote`] or xref:og-session-hazelcast-embedded[`session-store-hazelcast-embedded`] -* Infinispan: xref:og-session-infinispan[`session-store-infinispan-remote`] or xref:og-session-infinispan-embedded[`session-store-infinispan-embedded`] - -TIP: It is worth noting that if you do not configure _any_ session modules, Jetty will still provide HTTP sessions that are cached in memory but are never persisted. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-usecases.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-usecases.adoc deleted file mode 100644 index 866905392502..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-usecases.adoc +++ /dev/null @@ -1,65 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-session-usecases]] -==== Session Scenarios - -===== Minimizing Support for Sessions - -The standard support for webapps in Jetty will use sessions cached in memory, but not persisted/clustered, with a scavenge for expired sessions that occurs every 10 minutes. -If you wish to pare back support for sessions because you know your app doesn't use them (or use JSPs that use them), then you can do the following: - -* enable the xref:og-session-base[base sessions module] and xref:og-session-base[configure the scavenge interval] to 0 to prevent scavenging -* enable the xref:og-session-cache-null[null session cache module] to prevent sessions being cached in memory - -If you wish to do any further minimization, you should consult the xref:{prog-guide}#pg-server-session[Programming Guide]. - -===== Clustering with a Sticky Load Balancer - -Preferably, your cluster will utilize a sticky load balancer. -This will route requests for the same session to the same Jetty instance. -In this case, the xref:og-session-cache-hash[`DefaultSessionCache`] can be used to keep in-use session objects xref:og-session-cache-hash[in memory]. -You can fine-tune the cache by controlling how long session objects remain in memory with the xref:og-session-cache-hash[eviction policy settings]. - -If you have a large number of sessions or very large session objects, then you may want to manage your memory allocation by controlling the amount of time session objects spend in the cache. -The `EVICT_ON_SESSION_EXIT` eviction policy will remove a session object from the cache as soon as the last simultaneous request referencing it exits. -Alternatively, the `EVICT_ON_INACTIVITY` policy will remove a session object from the cache after a configurable amount of time has passed without a request referencing it. - -If your sessions are very long lived and infrequently referenced, you might use the `EVICT_ON_INACTIVITY_POLICY` to control the size of the cache. - -If your sessions are small, or relatively few or stable in number or they are read-mostly, then you might select the `NEVER_EVICT` policy. -With this policy, session objects will remain in the cache until they either expire or are explicitly invalidated. - -If you have a high likelihood of simultaneous requests for the same session object, then the `EVICT_ON_SESSION_EXIT` policy will ensure the session object stays in the cache as long as it is needed. - -===== Clustering Without a Sticky Load Balancer - -Without a sticky load balancer requests for the same session may arrive on any node in the cluster. -This means it is likely that the copy of the session object in any `SessionCache` is likely to be out-of-date, as the session was probably last accessed on a different node. -In this case, your choices are to use either the xref:og-session-cache-null[`NullSessionCache`] or to de-tune the xref:og-session-cache-hash[`DefaultSessionCache`]. -If you use the `NullSessionCache` all session object caching is avoided. -This means that every time a request references a session it must be read in from persistent storage. -It also means that there can be no sharing of session objects for multiple requests for the same session: each will have their own independent session object. -Furthermore, the outcome of session writes are indeterminate because the Servlet Specification does not mandate ACID transactions for sessions. - -If you use the `DefaultSessionCache`, there is a risk that the caches on some nodes will contain out-of-date session information as simultaneous requests for the same session are scattered over the cluster. -To mitigate this somewhat you can use the `EVICT_ON_SESSION_EXIT` eviction policy: this will ensure that the session is removed from the cache as soon as the last simultaneous request for it exits. -Again, due to the lack of session transactionality, the ordering outcome of write operations cannot be guaranteed. -As the session is cached while at least one request is accessing it, it is possible for multiple simultaneous requests to share the same session object. - -===== Handling Corrupted or Unreadable Session Data - -For various reasons it might not be possible for the `SessionDataStore` to re-read a stored session. -One scenario is that the session stores a serialized object in its attributes, and after a re-deployment there in an incompatible class change. -Setting the `$JETTY_BASE/start.d/session-cache-hash.ini` or `$JETTY_BASE/start.d/session-cache-null.ini` property `jetty.session.removeUnloadableSessions` to `true` will allow the unreadable session to be removed from persistent storage. -This can be useful for preventing the xref:og-session-base-scavenge[scavenger] from continually generating errors on the same expired, but un-readable session. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-xml.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-xml.adoc deleted file mode 100644 index 256f32d29bcb..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/sessions/session-xml.adoc +++ /dev/null @@ -1,47 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -TODO : decide whether to keep this info - -==== Configuring Sessions via Jetty XML - -With the provided session modules, there is no need to configure a context xml or `jetty-web.xml` file for sessions. -That said, if a user wishes to configure sessions this way, it is possible using xref:jetty-xml-syntax[Jetty IoC XML format.] - -Below is an example of how you could configure a the xref:og-session-filesystem[`FileSessionDataStore`], but the same concept would apply to any of the *SessionDataStores discussed in this chapter: - -[source,xml] ----- - - - - - - - - /tmp/sessions - - - - - - ----- - -The example above functions in either a `jetty-web.xml` file or a xref:using-basic-descriptor-files[context xml descriptor file.] - -[NOTE] -==== -If you explicitly configure the `SessionCache` and `SessionDataStore` for a `SessionHandler` in a context xml file or `jetty-web.xml` file, any session modules you already have enabled are ignored. -So, for example, if you had enabled the `session-store-gcloud module` for your sever, you could force a particular webapp to use the `FileSessionDataStore` by explicitly configuring it in either a context xml file or a `jetty-web.xml` file as shown above. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/chapter.adoc deleted file mode 100644 index 903bf2e68c7c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/chapter.adoc +++ /dev/null @@ -1,73 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-start]] -=== Jetty Start Mechanism - -NOTE: Make sure you have read the xref:og-arch[Jetty architecture section] if you are not familiar with the terms used in this section. - -The Jetty start mechanism is invoked by executing `$JETTY_HOME/start.jar`, from within a `$JETTY_BASE` directory, with zero or more command line options: - ----- -$ cd $JETTY_BASE -$ java -jar $JETTY_HOME/start.jar ... ----- - -The Jetty start mechanism has two main modes of operation: - -* The _tool_ mode, detailed in xref:og-start-configure[this section], when it is used as a command line tool to configure the `$JETTY_BASE` directory by enabling modules, creating sub-directories and files, downloading files, etc. -In this mode, the JVM started with `java -jar $JETTY_HOME/start.jar` performs the specified command and then exits. -* The _start_ mode, detailed in xref:og-start-start[this section], when it is used to start the JVM that runs Jetty with the specified configuration. -In this mode, the JVM started with `java -jar $JETTY_HOME/start.jar` starts Jetty and does not exit until stopped, for example by hitting kbd:[Ctrl+C] on the terminal. - -Refer to the xref:og-start-reference[Jetty start mechanism reference section] for the complete list of the available command line options. - -You want to use the Jetty start mechanism to xref:og-start-configure[configure your $JETTY_BASE] and then to xref:og-start-start[start Jetty]. - -include::start-configure.adoc[] -include::start-start.adoc[] -include::start-jpms.adoc[] -include::start-stop.adoc[] - -==== Start Mechanism Logging - -The steps performed by the Jetty start mechanism are logged by the `StartLog` class, that outputs directly, by default, to `System.err`. - -This is necessary to avoid that the Jetty start mechanism depend on logging libraries that may clash with those defined by Jetty logging modules, when Jetty is started in-VM. - -[NOTE] -==== -This section is about the logging performed by the Jetty start mechanism _before_ it configures and starts Jetty. -See the xref:og-server-logging[logging section] for information about logging when Jetty starts. -==== - -You can enable DEBUG level logging with the `--debug` command line option, for both the _tool_ and _start_ modes: - ----- -$ java -jar $JETTY_HOME/start.jar --debug ... ----- - -You can send the start log output to a file, by default relative to `$JETTY_BASE`, with the `--start-log-file=` option: - ----- -$ java -jar $JETTY_HOME/start.jar --debug --start-log-file=start.log ... ----- - -This is useful for capturing startup issues where the Jetty-specific logger has not yet kicked in due to a possible startup configuration error. - -[[og-start-reference]] -==== Usage Reference - ----- -include::../../../../../../../jetty-start/src/main/resources/org/eclipse/jetty/start/usage.txt[] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/jpms.mod b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/jpms.mod deleted file mode 100644 index 6d261a6eb542..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/jpms.mod +++ /dev/null @@ -1,8 +0,0 @@ -[description] -JPMS Configuration Module - -[ini] ---jpms - -[jpms] -# Additional JPMS configuration. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/jvm.mod b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/jvm.mod deleted file mode 100644 index e8b2fc51d0a9..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/jvm.mod +++ /dev/null @@ -1,6 +0,0 @@ -[description] -JVM Options Module - -[exec] --Xmx1g --Xlog:gc*,gc+stats=off:file=logs/gc.log:time,level,tags diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/postgresql.mod b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/postgresql.mod deleted file mode 100644 index aadffda2ca90..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/postgresql.mod +++ /dev/null @@ -1,15 +0,0 @@ -[description] -Postgres JDBC Driver Module - -[lib] -lib/postgresql-${postgresql-version}.jar - -[files] -maven://org.postgresql/postgresql/${postgresql-version}|lib/postgresql-${postgresql-version}.jar - -[ini] -postgresql-version?=42.2.18 - -[ini-template] -## Postgres JDBC version. -# postgresql-version=42.2.18 diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-configure.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-configure.adoc deleted file mode 100644 index f041576a892b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-configure.adoc +++ /dev/null @@ -1,371 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-start-configure]] -==== Configuring $JETTY_BASE - -Within the Jetty start mechanism, the source of configurations is layered in this order, from higher priority to lower priority: - -* The command line options. -* The `$JETTY_BASE` directory, and its files. -* The directory specified with the `--include-jetty-dir` option, and its files. -* The `$JETTY_HOME` directory, and its files. - -[[og-start-configure-enable]] -===== Enabling Modules - -You can enable Jetty modules persistently across restarts with the `--add-modules` command: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=server,http ----- - -The Jetty start mechanism will look for the specified modules following the order specified above. -In the common case (without a `--include-jetty-dir` directory), it will look in `$JETTY_BASE/modules/` first and then in `$JETTY_HOME/modules/`. - -Since the `server` and `http` modules are standard Jetty modules, they are present in `$JETTY_HOME/modules/` and loaded from there. - -When you enable a Jetty module, the Jetty start mechanism: - -* Creates the correspondent `+$JETTY_BASE/start.d/*.ini+` module configuration file. -The content of these `+*.ini+` files is copied from the `[ini-template]` section of the correspondent `+*.mod+` file. -* Executes the directives specified in `[files]` section (if present) of the `+*.mod+` file. -This may simply create a file or a directory, or download files from the Internet. -This step is performed transitively for all module dependencies. - -For example, enabling the `server` and `http` modules results in the `$JETTY_BASE` directory to have the following structure: - ----- -$JETTY_BASE -├── resources -│ └── jetty-logging.properties -└── start.d - ├── http.ini - └── server.ini ----- - -The `$JETTY_BASE/resources/jetty-logging.properties` is created by the `[files]` directives of the `logging-jetty` module, which is a transitive dependency of the `server` module. - -[[og-start-configure-disable]] -===== Disabling Modules - -A module is enabled because the correspondent `+$JETTY_BASE/start.d/*.ini+` file contains a `--module=` directive. - -Commenting out the `--module=` directive effectively disables the module. - -Deleting the correspondent `+$JETTY_BASE/start.d/*.ini+` file also disables the module. - -[[og-start-configure-edit-ini]] -===== Editing `+*.ini+` Files - -You can now edit the `+$JETTY_BASE/start.d/*.ini+` configuration files, typically by uncommenting properties to change their default value. - -The `+$JETTY_BASE/start.d/*.ini+` configuration file may be missing, if the correspondent module is a transitive dependency. -You can easily generate the configuration file by explicitly enabling the module, for example to generate the `$JETTY_BASE/start.d/logging-jetty.ini` configuration file you would issue the following command (the module order does not matter): - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=server,http,logging-jetty ----- - -The `$JETTY_BASE` directory structure is now: - -[source,subs=quotes] ----- -$JETTY_BASE -├── resources -│ └── jetty-logging.properties -└── start.d - ├── http.ini - ├── ##logging-jetty.ini## - └── server.ini ----- - -You want to edit the `+$JETTY_BASE/start.d/*.ini+` configuration files so that the configuration is applied every time Jetty is started (or re-started). - -For example, `$JETTY_BASE/start.d/http.ini` contains the following property, commented out: - -.http.ini ----- -# jetty.http.port=8080 ----- - -You can change the clear-text HTTP port Jetty listens to by uncommenting that property and changing its value: - -.http.ini ----- -jetty.http.port=9876 ----- - -When Jetty is started (or re-started) this configuration is applied and Jetty will listen for clear-text HTTP/1.1 on port `9876`. - -[[og-start-configure-enable-command-line]] -===== Enabling Modules on Command Line - -You can also enable a module transiently, only for the current execution of the `java -jar $JETTY_HOME/start.jar` command. - -If you have an empty `$JETTY_BASE`, the following command enables the `server` and `http` modules, but does not create any `+$JETTY_BASE/start.d/*.ini+` files. - ----- -$ java -jar $JETTY_HOME/start.jar --module=server,http ----- - -Since there are no `+$JETTY_BASE/start.d/*.ini+` files, you can only customize the properties via the command line, for example: - ----- -$ java -jar $JETTY_HOME/start.jar --module=server,http jetty.http.port=9876 ----- - -Enabling modules on the command line is useful to verify that the modules work as expected, or to try different configurations. - -NOTE: It is possible to enable some module persistently via `--add-modules` and some other module transiently via `--module`. - -Remember that once the current execution terminates, the modules enabled transiently on the command line via `--module` and their configuration are not saved and will not be enabled on the next execution (unless you specify them again on the command line). - -[[og-start-configure-custom-module]] -===== Adding Your Own Modules - -NOTE: Refer to the xref:og-modules-custom[custom module section] for the details about how to create your own modules. - -You can add your own modules by adding a `+$JETTY_BASE/modules/*.mod+` file. - -For example, you may want to add a Postgres JDBC driver to the server class-path, to avoid that each deployed web application bring its own version. This allows you to control the exact Postgres JDBC driver version for all web applications. - -Create the `$JETTY_BASE/modules/postgresql.mod` file: - -.postgresql.mod ----- -include::postgresql.mod[] ----- - -Then enable it: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=postgresql ----- - -Enabling the `postgresql` module will execute the `[files]` directive (downloading the `+*.jar+` file from Maven Central if not already present) and create the `$JETTY_BASE/start.d/postgresql.ini` with the content of the `[ini-template]` section. - -The `[lib]` section ensures that the specified file is in the server class-path when Jetty is started. - -You can xref:og-start-configure-display[display the Jetty configuration] to verify that the server class-path is correct. - -[[og-start-configure-custom-module-exec]] -===== Custom Module with JVM Options - -Using a custom Jetty module, you can customize the JVM startup options. - -This is useful if you need to start Jetty and want to specify JVM options such as: - -* `+-Xmx+`, to specify the max heap size -* `+-Xlog:gc+`, to specify the GC log file and options -* `+-javaagent+`, to specify Java agents -* `+-XX:+` options, for example to specify the GC implementation -* `+--enable-preview+`, to enable Java preview features - -Start by creating `$JETTY_BASE/modules/jvm.mod`: - -.jvm.mod ----- -include::jvm.mod[] ----- - -Enable it: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=jvm ----- - -Since the module defines an `[exec]` section, it will fork _another_ JVM when Jetty is started. - -This means that when you start Jetty, there will be _two_ JVMs running: one created by you when you run `java -jar $JETTY_HOME/start.jar`, and another forked by the Jetty start mechanism with the JVM options you specified (that cannot be applied to an already running JVM). - -Again, you can xref:og-start-configure-dry-run[display the JVM command line] to verify that it is correct. - -[TIP] -==== -The second JVM forked by the Jetty start mechanism when one of the modules requires forking, for example a module that contains an `[exec]` section, may not be desirable, and may be avoided as explained in xref:og-start-configure-dry-run[this section]. -==== - -[[og-start-configure-display]] -===== Displaying the Configuration - -Once you have enabled and configured the `$JETTY_BASE`, you can display the configuration to verify that it is correct. - -Using the standard `server` and `http` Jetty modules, and the `postgresql` and `jvm` custom Jetty module defined above, you obtain: - ----- -$ java -jar $JETTY_HOME/start.jar --list-config ----- - -[source,options=nowrap] ----- -include::jetty[setupModules="src/main/asciidoc/operations-guide/start/jvm.mod,src/main/asciidoc/operations-guide/start/postgresql.mod",setupArgs="--add-modules=server,http,postgresql,jvm",args="--list-config"] ----- - -Note how the configuration displayed above includes: - -* In the list of enabled modules, the `postgresql` and `jvm` modules -* In the list of JVM arguments, those specified by the `jvm` module -* In the server class-path, the `+*.jar+` file specified by the `postgresql` module - -[[og-start-configure-dry-run]] -===== Displaying the JVM Command Line - -The Jetty start mechanism can display a full JVM command line that will start Jetty with the configuration you specified, with the `--dry-run` option: - ----- -$ java -jar $JETTY_HOME/start.jar --dry-run ----- - -The full JVM command line generated by `--dry-run` can be split in various parts that can be used individually, for example in scripts. - -Furthermore, Jetty modules may specify the `--exec` option that will fork a second JVM to start Jetty, which may not be desirable. -Some option, such as `--jpms`, imply `--exec`, as it won't be possible to modify the module-path in the already started JVM. - -To start Jetty without forking a second JVM, the `--dry-run` option can be used to generate a command line that is then executed so that starting Jetty only spawns one JVM. - -IMPORTANT: You can use the `--dry-run` option as explained below to avoid forking a second JVM when using modules that have the `[exec]` section, or the `--exec` option, or when using the `--jpms` option. - -For example, using the `--dry-run` option with the `jvm.mod` introduced in xref:og-start-configure-custom-module-exec[this section] produces the following command line: - ----- -$ java -jar $JETTY_HOME/start.jar --dry-run ----- - -[source,options=nowrap] ----- -include::jetty[setupModules="src/main/asciidoc/operations-guide/start/jvm.mod",setupArgs="--add-modules=http,jvm",args="--dry-run",replace="( ),$1\\\n"] ----- - -You can then run the generated command line. - -For example, in the Linux `bash` shell you can run it by wrapping it into `$(\...)`: - ----- -$ $(java -jar $JETTY_HOME/start.jar --dry-run) ----- - -The `--dry-run` option is quite flexible and below you can find a few examples of how to use it to avoid forking a second JVM, or generating scripts or creating an arguments file that can be passed to (a possibly alternative) `java` executable. - -To display the `java` executable used to start Jetty: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar --dry-run=##java## ----- - -[source,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=http",args="--dry-run=java"] ----- - -To display the JVM options: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar --dry-run=##opts## ----- - -[source,options=nowrap] ----- -include::jetty[setupModules="src/main/asciidoc/operations-guide/start/jvm.mod",setupArgs="--add-modules=http,jvm",args="--dry-run=opts",replace="( ),$1\\\n"] ----- - -To display the JVM class-path: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar --dry-run=##path## ----- - -[source,options=nowrap] ----- -include::jetty[setupModules="src/main/asciidoc/operations-guide/start/postgresql.mod",setupArgs="--add-modules=http,jvm",args="--dry-run=path",replace="( |:),$1\\\n"] ----- - -To display the JVM class-path and module-path, if you want to xref:og-start-start-jpms[start Jetty using JPMS] with the `--jpms` option: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar ##--jpms## --dry-run=##path## ----- - -[source,options=nowrap] ----- -include::jetty[setupModules="src/main/asciidoc/operations-guide/start/postgresql.mod",setupArgs="--add-modules=http,jvm",args="--jpms --dry-run=path",replace="( |:),$1\\\n"] ----- - -To display the JVM main class: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar --dry-run=##main## ----- - -[source,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=http",args="--dry-run=main"] ----- - -To display the JVM main class when xref:og-start-start-jpms[starting Jetty using JPMS]: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar --jpms --dry-run=##main## ----- - -[source,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=http",args="--jpms --dry-run=main"] ----- - -The main class is typically Jetty's `XmlConfiguration` class that accepts, as program arguments, a list of properties and a list of Jetty XML files to process. -The Jetty XML files compose together the Jetty components that are then configured with the values from the command line properties. - -To display the program arguments passed to the main class: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar --dry-run=##args## ----- - -[source,options=nowrap] ----- -include::jetty[setupModules="src/main/asciidoc/operations-guide/start/postgresql.mod",setupArgs="--add-modules=http",args="--dry-run=args",replace="( ),$1\\\n"] ----- - -Note how the program arguments are a list of properties in the form `=` and a list of Jetty XML files. - -The various parts of the full JVM command line can be combined to leverage the arguments file feature (that is, specify the JVM options in a file rather than on the command line) that is built-in in the `java` executable: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar --dry-run=##opts,path,main,args## > /tmp/jvm_cmd_line.txt -$ /some/other/java @/tmp/jvm_cmd_line.txt ----- - -Using `--dry-run=opts,path,main,args` can be used to avoid that the Jetty start mechanism forks a second JVM when using modules that require forking: - ----- -$ java $(java -jar $JETTY_HOME/start.jar --dry-run=opts,path,main,args) ----- - -The output of different `--dry-run` executions can be creatively combined in a shell script: - -[source,subs=quotes] ----- -$ OPTS=$(java -jar start.jar --dry-run=##opts,path##) -$ MAIN=$(java -jar start.jar --dry-run=##main##) -$ ARGS=$(java -jar start.jar --dry-run=##args##) -$ java $OPTS -Dextra=opt $MAIN $ARGS extraProp=value extra.xml ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-jpms.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-jpms.adoc deleted file mode 100644 index 4e2834dd4bf7..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-jpms.adoc +++ /dev/null @@ -1,95 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-start-start-jpms]] -==== Starting Jetty using JPMS - -Jetty modules are proper link:https://en.wikipedia.org/wiki/Java_Platform_Module_System[JPMS] modules: each Jetty module has a `module-info.class` file. -This makes possible to run Jetty from the module-path, rather than the class-path. - -To start Jetty on the module-path rather than the class-path, it is enough to add the `--jpms` option to the command line, for example: - ----- -$ java -jar $JETTY_HOME/start.jar --jpms ----- - -[NOTE] -==== -The `--jpms` option implies the `--exec` option. - -When running on the module-path using the `--jpms` option, the Jetty start mechanism will fork a second JVM passing it the right JVM options to run on the module-path. - -Therefore, you will have two JVMs running: one that runs `start.jar` and one that runs Jetty on the module-path. -==== - -When Jetty is started in JPMS mode, all JPMS modules in the module-path are added to the set of JPMS _root modules_ through the JVM option `--add-modules ALL_MODULE_PATH`. - -For a `+*.jar+` file that is not a JPMS module, but is on the module-path, the JVM will assume internally it is an automatic JPMS module, with a JPMS module name derived from the `+*.jar+` file name. - -Rather than adding the `--jpms` option to the command line, you can use a custom Jetty module to centralize your JPMS configuration, where you can specify additional JPMS directives. - -Create the `$JETTY_BASE/modules/jpms.mod` file: - -.jpms.mod ----- -include::jpms.mod[] ----- - -The `[ini]` section with `--jpms` is equivalent to passing the `--jpms` option to the command line (see also xref:og-modules-directive-ini[this section]). - -The `[jpms]` section allows you to specify additional JPMS configuration, for example additional `--add-modules` options, or `--add-opens` options, etc. (see also xref:og-modules-directive-jpms[this section]). - -Then enable it: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=jpms ----- - -Now you can start Jetty without extra command line options, and it will start in JPMS mode because you have enabled the `jpms` module. - -[[og-start-start-jpms-advanced]] -===== Advanced JPMS Configuration - -Web applications may need additional services from the Servlet Container, such as JDBC `DataSource` references or JTA `UserTransaction` references. - -For example, for JDBC it is typical to store, in JNDI, a reference to the connection pool's `DataSource` or directly a reference to the JDBC driver's `DataSource` (for example, `org.postgresql.ds.PGConnectionPoolDataSource`). -Jetty needs to be able to instantiate those classes and therefore needs to be able to load those classes and all their super-classes, among which includes `javax.sql.DataSource`. - -When Jetty runs on the class-path, this is easily achieved by using a xref:og-modules-custom[custom module] as explained in xref:og-start-configure-custom-module[this section]. - -However, when running on the module-path, things are quite different. - -When Jetty tries to load, for example, class `org.postgresql.ds.PGConnectionPoolDataSource`, it must be in a JPMS module that is resolved in the run-time module graph. -Furthermore, any dependency, for example classes from the `java.sql` JPMS module, must also be in a module present in the resolved module graph. - -Thanks to the fact that when Jetty starts in JPMS mode the `--add-modules ALL_MODULE_PATH` option is added to the JVM command line, every `+*.jar+` file in the module-path is also present in the module graph. - -There are now two cases for the `postgresql-.jar` file: either it is a proper JPMS module, or it is an automatic JPMS module (either an explicit automatic JPMS module with the `Automatic-Module-Name` attribute in the manifest, or an implicit automatic JPMS module whose name is derived from the `+*.jar+` file name). - -If the `postgresql-.jar` file is a proper JPMS module, then there is nothing more that you should do: the `postgresql-.jar` file is in the module-path, and all the modules in the module-path are in the module graph, and any dependency declared in the `module-info.class` will be added to the module graph. - -Otherwise, `postgresql-.jar` file is an automatic module, and will likely have a dependency on the JDK-bundled `java.sql` JPMS module. -However, the `java.sql` JPMS module is not in the module graph, because automatic modules do not have a way to declare their dependencies. - -For this reason, you have to manually add the `java.sql` dependency to the module graph. -Using the `postgresql.mod` introduced in xref:og-start-configure-custom-module[this section] as an example, modify your custom module in the following way: - -.postgresql.mod ----- -... - -[jpms] -add-modules: java.sql ----- - -The `[jpms]` section is only used when Jetty is started on the module-path. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-start.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-start.adoc deleted file mode 100644 index 55604a313a48..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-start.adoc +++ /dev/null @@ -1,108 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-start-start]] -==== Starting Jetty - -After you have configured the `$JETTY_BASE` directory, as explained in xref:og-start-configure[this section], you can start Jetty as a standalone server. - -In the _start_ mode, the Jetty start mechanism computes a JVM command line with JVM options, system properties, class-path, module-path, main class and program arguments, and then executes it, forking a new JVM if necessary. - -The Jetty start mechanism performs these steps: - -. Loads all the Jetty modules files (that have extension `+*.mod+`) from the `modules/` subdirectory of each configuration source directory (see xref:og-start-configure[this section] for the list of configuration sources). -In this way, a Jetty module graph can be built in memory, where the module dependencies form the edges of the graph and each node contains the metadata information declared by each module (for example, the libraries that it needs, the XML files to process, and so on), in preparation for the next step. -. Reads the Jetty module configuration files (that have extension `+*.ini+`) from the `start.d/` subdirectory of each configuration source directory and from the command line. -This step produces a list of _enabled_ modules; for each enabled module all its dependencies are transitively resolved by navigating the graph built in the previous steps. -. Processes the list of enabled (explicitly and transitively) modules, gathering the list of libraries to add to the class-path, the JPMS directives to add to the command line, the properties and XML files to add as program arguments, etc., so that a full JVM command line can be generated. -. Executes the command line, either in-JVM or by forking a second JVM (if the `--exec` option is present or implied by other options such as `--jpms`), and waits for the JVM, or the forked JVM, to exit. - -[[og-start-start-class-path]] -===== Server Class-Path - -When the Jetty server is started in-JVM, the server class-path gathered by processing the enabled modules is organized in a `URLClassLoader`, the Jetty Start ClassLoader, that is a child of the System ClassLoader: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam roundCorner 10 - -rectangle "Jetty Start JVM" { - rectangle "System ClassLoader" as system - rectangle "Jetty Start ClassLoader" as start - - note right of system: start.jar - note right of start: jetty-server.jar\njetty-http.jar\njetty-io.jar\njetty-util.jar\njetty-xml.jar\netc. - - system <-- start -} ----- - -The System ClassLoader only has `$JETTY_HOME/start.jar` in its class-path, since the JVM was started with `java -jar $JETTY_HOME/start.jar`. -The Jetty Start ClassLoader has in its class-path the `+*.jar+` files gathered by processing the enabled modules, typically from `+$JETTY_HOME/lib/jetty-*.jar+`, but possibly also from `+$JETTY_BASE/lib/*.jar+` if custom modules extend the server class-path with their own `+*.jar+` files. - -When the Jetty server is started in a forked JVM, there will be two JVMs: one started by you with `java -jar $JETTY_HOME/start.jar` and one forked by the Jetty start mechanism. -In the forked JVM, the System ClassLoader has the server class-path and/or module-path in its class-path, since the forked JVM is started with `+java --class-path $JETTY_HOME/lib/jetty-server-.jar:...+`: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam roundCorner 10 - -rectangle "Jetty Start JVM" as startJVM { - rectangle "System ClassLoader" as system1 - note right of system1: start.jar -} - -rectangle "Forked JVM" as forkedJVM { - rectangle "System ClassLoader" as system2 - - note right of system2: jetty-server.jar\njetty-http.jar\njetty-io.jar\njetty-util.jar\njetty-xml.jar\netc. -} - -startJVM --> forkedJVM: " waits for" ----- - -It is worth mentioning that there are two standard Jetty modules that allow you to easily add entries to the Jetty server class-path: - -* The `resources` module, that adds the `$JETTY_BASE/resources/` directory to the server class-path. -This is useful if you have third party libraries that lookup resources from the class-path: just put those resources in the `$JETTY_BASE/resources/` directory. + -Logging libraries often perform class-path lookup of their configuration files (for example, `log4j.properties`, `log4j.xml`, `logging.properties`, and `logback.xml`), so `$JETTY_BASE/resources/` is the ideal place to add those files. + -* The the `ext` module, that adds all the `+*.jar+` files under the `$JETTY_BASE/lib/ext/` directory, and subdirectories recursively, to the server class-path. + -+ -[CAUTION] -==== -On one hand, the `ext` module provides a handy place to put third party libraries and their dependencies; on the other hand, the `$JETTY_BASE/lib/ext/` directory may become a confused mixture of many `+*.jar+` files from different third party libraries. - -Prefer to group third party libraries and their dependencies into their own directories using xref:og-modules-custom[custom modules], or at least group them into `$JETTY_BASE/lib/ext/` subdirectories such as `$JETTY_BASE/lib/ext/util/` or `$JETTY_BASE/lib/ext/acme/`. -==== - -[[og-start-start-xml]] -===== Assembling Jetty Components - -The Jetty start mechanism eventually invokes, by default, main class `org.eclipse.jetty.xml.XmlConfiguration`, passing properties and xref:og-xml[Jetty XML files] as program arguments. - -The Jetty XML files are nothing more than Java code in XML format. - -The XML files are processed to instantiate Jetty components such as `org.eclipse.jetty.server.Server` or `org.eclipse.jetty.util.ssl.SslContextFactory`. -The components are then assembled together to provide the configured Jetty features. - -The Jetty XML files are parametrized using properties; a property is just a name/value pair. - -This parametrization of the XML files allows an XML file that resides in `$JETTY_HOME/etc/` to _declare_ a property such as `jetty.http.port`, and allow this property to be set in a `$JETTY_BASE/start.d/http.ini` file, so that you don't need to change the XML files in `$JETTY_HOME`, but only change files in your `$JETTY_BASE`. - -You can write your own xref:og-modules-custom[custom modules] with your own Jetty XML files, and your own properties, to further customize Jetty. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-stop.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-stop.adoc deleted file mode 100644 index cc06b2fb3168..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/start/start-stop.adoc +++ /dev/null @@ -1,78 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-start-stop]] -==== Stopping Jetty - -When Jetty is started, the Jetty components that you have configured by enabling Jetty modules are assembled and started. - -If you have started Jetty from a terminal, you can exit the Jetty JVM by hitting kbd:[Ctrl+C] on the same terminal. - -Similarly, from a different terminal, you can exit the Jetty JVM using `kill -INT ` or `kill -TERM `. - -In the three cases above, the JVM is exited, but by default Jetty components are not stopped. -If you want to stop the Jetty components, to stop Jetty more gracefully, you can start Jetty with this property: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar ##jetty.server.stopAtShutdown=true## ----- - -This property can also be set in `$JETTY_BASE/start.d/server.ini` so that it is persistently configured across Jetty restarts (see also xref:og-module-server[the `server` module]). - -The `jetty.server.stopAtShutdown` property configures a JVM shutdown hook that is run, stopping the `Server` instance, when the JVM exits. - -Obviously, the JVM can also be stopped with `kill -KILL ` that exits the process abruptly without running the JVM shutdown hooks. - -[[og-start-stop-remote]] -===== Stopping Jetty from Remote - -You can configure a Jetty server so that it can be stopped by remote clients using a command sent through a TCP socket. - -You can start Jetty with the following properties: - -* `stop.host`, the host name Jetty will bind to listen for stop commands. Defaults to `127.0.0.1` which means that the stop command can be issued only clients that run on the same host as Jetty. -* `stop.port`, the port number Jetty will listen to for stop commands. Defaults to `-1`, which means that Jetty will not listen to any port. -* `stop.key`, the password to verify when a stop command is received. Defaults to a password that is randomly generated and printed when Jetty starts. - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar ##stop.port=8181## ----- - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=http",args="stop.port=8181",highlight="(?i)stop.key"] ----- - -In the example above, Jetty is started with just the `stop.port` property, and the `stop.key` is printed on the terminal when Jetty starts. - -CAUTION: You can choose your own `stop.key`, but make sure it's a strong password. - -A remote client can now use the Jetty start mechanism to stop the remote Jetty server: - -[source,subs=normal] ----- -$ java -jar $JETTY_HOME/start.jar ##--stop## stop.port=8181 stop.key= ----- - -Note the `--stop` command along with the `stop.port` and `stop.key` properties. -The `stop.key` must be the same as the one of remote Jetty server, either the one you chose, or the one printed on the terminal when Jetty starts. - -Remote clients can wait for the remote Jetty server to shut down by specifying the `stop.wait` property with the number of seconds to wait: - ----- -$ java -jar $JETTY_HOME/start.jar --stop stop.port=8181 stop.key= stop.wait=15 ----- - -If the time specified elapses, without the confirmation that the remote Jetty server stopped, then the `--stop` command exits with a non-zero return code. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/chapter.adoc deleted file mode 100644 index 81a17733b12a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/chapter.adoc +++ /dev/null @@ -1,38 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-troubleshooting]] -=== Troubleshooting - -To troubleshoot Jetty when used as a production server, there are two main tools: the Jetty Server Dump and enabling DEBUG level logging. - -Jetty is based on components organized as a tree, with the `Server` instance at the root of the tree. - -As explained in the xref:og-jmx[JMX section], these components can be exported as JMX MBeans and therefore be accessible from JMX Consoles such as Java Missions Control (JMC). - -Being able to take a snapshot of the state of Jetty while it is running is the most useful information that can be attached when reporting an issue. -Such state includes: - -* The thread pool configuration and its current state, including how many threads are in use, and their stack trace. -* The TLS configuration. -* The I/O configuration and its current state, including the ports Jetty listens to, how many connections are currently open, and he state of each connection, and the state of the request/response handling for each connection. -* The `Handler` structure and its configuration. -* The web applications deployed and their configurations, including the class loader information. - -The prerequisite for troubleshooting is to enable JMX, so that Jetty -- possibly a production server -- can be accessed from a remote location to obtain the information exported via JMX, and possibly be able to reconfigure Jetty to solve the issue. - -IMPORTANT: Make sure you read about how to secure the access to Jetty when using xref:og-jmx-remote[remote JMX]. - -include::troubleshooting-dump.adoc[] -include::troubleshooting-logging.adoc[] -include::troubleshooting-debugging.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/remote-debug.mod b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/remote-debug.mod deleted file mode 100644 index 9cae360e33f5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/remote-debug.mod +++ /dev/null @@ -1,5 +0,0 @@ -[description] -Enables remote debugging - -[exec] --agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-debugging.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-debugging.adoc deleted file mode 100644 index b46842a4fa0a..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-debugging.adoc +++ /dev/null @@ -1,74 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-troubleshooting-debugging]] -==== Remote Debugging - -The Java Virtual Machines allows remote processes on different hosts to connect for debugging purposes, by using specific command line options. - -[CAUTION] -==== -While it is possible to enable remote debugging on a Jetty server, it is typically not recommended for security and performance reasons. -Only enable remote debugging on a Jetty server as a last resort to troubleshoot issues that could not be troubleshot otherwise. -==== - -You can easily create a custom Jetty module (see xref:og-modules-custom[this section]) with the following content: - -.remote-debug.mod ----- -include::remote-debug.mod[] ----- - -The `[exec]` directive (documented xref:og-modules-directive-exec[here]) is necessary to pass the `-agentlib:jdwp` JVM option to the forked JVM that runs Jetty, so that you can attach with a debugger. - -[NOTE] -==== -The `address` parameter of the `-agentlib:jdwp` command line option specifies the network address and port the Jetty JVM listens on for remote debugging. - -Please refer to the link:https://docs.oracle.com/en/java/javase/17/docs/specs/jpda/conninv.html[Java Debug Wire Protocol documentation] for additional information about the `-agentlib:jdwp` command line option and its parameters. -==== - -You can now enable the `remote-debug` Jetty module with the following command issued from the `$JETTY_BASE` directory: - ----- -$ java -jar $JETTY_HOME/start.jar --add-modules=server,remote-debug ----- - -The command above minimally adds a Jetty server without connectors (via the `server` Jetty module) and the `remote-debug` Jetty module, and produces the following `$JETTY_BASE` directory structure: - -[source,subs=normal] ----- -$JETTY_BASE -├── modules -│ └── remote-debug.mod -├── resources -│ └── jetty-logging.properties -└── start.d - ├── ##remote-debug.ini## - └── server.ini ----- - -You can easily disable the `remote-debug` Jetty module as explained in xref:og-start-configure-disable[this section]. - -Alternatively, you can enable the `remote-debug` module on the command line, as explained in xref:og-start-configure-enable-command-line[this section]. - -Starting the Jetty server with the `remote-debug` module enabled yields: - -[source,subs=quotes,options=nowrap] ----- -include::jetty[setupModules="src/main/asciidoc/operations-guide/troubleshooting/remote-debug.mod",setupArgs="--add-modules=server,remote-debug",highlight="5005"] ----- - -Note how the JVM is listening on port `5005` to allow remote debuggers to connect. - -If you want to avoid to fork a second JVM to pass the `-agentlib:jdwp` JVM option, please read xref:og-start-configure-dry-run[this section]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-dump.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-dump.adoc deleted file mode 100644 index 9eb56e7fb051..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-dump.adoc +++ /dev/null @@ -1,85 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-troubleshooting-dump]] -==== Server Dump - -The Jetty Server Dump is obtained by invoking, via JMX, the `Server.dump()` operation, as shown below. - -image::jmc-server-dump.png[] - -Find the `Server` MBean in the MBean Tree, under `org.eclipse.jetty.server:type=server,id=0`. -Then click on the "Operations" tab, select the `dump()` operation, and then click the `Execute` button. -In the bottom panel you will see the result of the invocation, that you can copy into a text editor and save to your file system. - -[CAUTION] -==== -Taking a Jetty Server Dump is a relatively expensive operation, as it dumps the state of all connections (which can be thousands), and the state of all threads. - -The result of the invocation may produce a large string, possibly few MiB, that may impact the server memory usage. - -Furthermore, dumping the state of the I/O Jetty components takes a little CPU time off the handling of the actual I/O, possibly slowing it down temporarily. - -While the slow-down caused by taking the Jetty Server Dump may be noticeable on highly loaded systems, it is typically a very small price to pay to obtain the information about the Jetty state that may be critical to the resolution of an issue. -==== - -[NOTE] -==== -The format of the Jetty Server Dump output is subject to change at any time, as Jetty developers modify the Jetty code and decide to include more state, or remove state that is no longer relevant. - -The Jetty Server Dump is organized in a tree whose structure is similar to the runtime Jetty component tree. - -At the end of the dump output there is a legend that explains the type of tree node: whether it is a node that represent a _managed_ component, or an _array_ node (or a _map_ node) that represent some component state, etc. -==== - -[[og-troubleshooting-dump-start-stop]] -===== Dump at Server Start/Stop - -The `Server.dump()` operation may also be invoked just after the `Server` starts (to log the state of the freshly started server), and just before the `Server` stops (which may be useful to log the state of server that is not working properly). - -You can temporarily enable the Jetty Server Dump at start time by overriding the `jetty.server.dumpAfterStart` property on the command line: - -[source,subs=quotes] ----- -$ java -jar $JETTY_HOME/start.jar *jetty.server.dumpAfterStart=true* ----- - -To make this change persistent across server restarts, see the xref:og-module-server[`server` module] configuration for more information about how to configure the server to dump at start/stop time. - -[[og-troubleshooting-dump-detailed]] -===== Detailed ThreadPool Information - -By default, the dump of the thread pool will only dump the topmost stack frame of each thread. -It is possible to configure the thread pool to dump the whole stack trace for each thread; while this may be a little more expensive, it provides complete information about the state of each thread, which may be important to diagnose the issue. - -See the xref:og-module-threadpool[`threadpool` module] configuration for more information about how to configure the thread pool to dump detailed thread information. - -Detailed thread pool information can also be turned on/off on-the-fly via JMX, by finding the `ThreadPool` MBean under `org.eclipse.jetty.util.thread:type=queuedthreadpool,id=0`, then selecting the `detailedDump` attribute and setting it to `true`. You can now perform the `Server.dump()` operation as explained above, and then set `detailedDump` back to `false`. - -[[og-troubleshooting-dump-example]] -===== Dump Example - -Below you can find a simple example of a Jetty Server Dump, with annotations for the principal components: - -[source,subs=verbatim,role=small,options=nowrap] ----- -include::jetty[setupArgs="--add-modules=http",args="jetty.http.selectors=1 jetty.http.acceptors=1 jetty.threadPool.minThreads=4 jetty.server.dumpAfterStart=true",delete="^[0-9]{4}",callouts=" <$N>,Server@,= QueuedThreadPool,HandlerList@,= ServerConnector,ManagedSelector@,keys @,startJarLoader@,unmanaged"] ----- -<1> The `Server` instance at the root of the tree -<2> The thread pool component -<3> The root of the `Handler` structure -<4> The connector listening on port `8080` for the HTTP/1.1 protocol -<5> A selector component that manages connections -<6> The connections currently managed by the selector component -<7> The server `ClassLoader` and its classpath -<8> The legend for the dump nodes diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-logging.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-logging.adoc deleted file mode 100644 index 01360eda3753..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/troubleshooting/troubleshooting-logging.adoc +++ /dev/null @@ -1,67 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-troubleshooting-logging]] -==== Enabling DEBUG Logging - -Enabling DEBUG level logging for the `org.eclipse.jetty` logger name provides the maximum amount of information to troubleshoot Jetty issues. - -Refer to the xref:og-server-logging[logging section] for more information about how to configure logging in Jetty. - -[CAUTION] -==== -Enabling DEBUG level logging for `org.eclipse.jetty` is very, *very* expensive. - -Your server could be slowed down to almost a halt, especially if it is under heavy load. -Furthermore, the log file could quickly fill up the entire filesystem (unless configured to roll over), so you want to be really careful using DEBUG logging. - -For production servers, consider using the xref:og-troubleshooting-dump[Jetty Server Dump] first, and enable DEBUG logging only as a last resort. -==== - -However, sometimes issues are such that only DEBUG logging can really tell what's going on in the system, and enabling DEBUG logging is your best chance to figure the issue out. -Below you can find few suggestions that can help you reduce the impact when you have to enable DEBUG logging. - -[[og-troubleshooting-logging-backend]] -===== Jetty Behind a Load Balancer - -If Jetty instances are behind a load balancer, you may configure the load balancer to send less load to a particular Jetty instance, and enable DEBUG logging in that instance only. - -[[og-troubleshooting-logging-jmx]] -===== Enabling DEBUG Logging for a Short Time - -In certain cases the issue can be reproduced reliably, but only in the production environment. - -You can use JMX to temporarily enable DEBUG logging, reproduce the issue, and then disable DEBUG logging. - -Alternatively, if you cannot reliably reproduce the issue, but you _know_ it is happening, you can temporarily enable DEBUG logging for a small period of time, let's say 10-60 seconds, and then disable DEBUG logging. - -Changing the log level at runtime is a feature of the logging implementation that you are using. - -The Jetty SLF4J implementation, used by default, exposes via JMX method `boolean JettyLoggerFactoryMBean.setLoggerLevel(String loggerName, String levelName)` that you can invoke via a JMX console to change the level for the specified logger name. -The method returns `true` if the logger level was successfully changed. - -For example, you can pass the string `org.eclipse.jetty` as the first parameter, and the string `DEBUG` (upper case) as the second parameter. -You can then use the string `INFO` or `WARN` (upper case) to restore the logging level to its previous value. - -[[og-troubleshooting-logging-subpackages]] -===== Enabling DEBUG Logging for SubPackages - -Enabling DEBUG logging for the `org.eclipse.jetty` logger name implies that all children logger names, recursively, inherit the DEBUG level. - -Processing a single HTTP request involves many Jetty components: the I/O subsystem (under `org.eclipse.jetty.io`), the thread pool (under `org.eclipse.jetty.util`), the HTTP/1.1 parsing (under `org.eclipse.jetty.http`), etc. - -If you can cut the amount of DEBUG logging to just what you need to troubleshoot the issue, the impact of enabling DEBUG logging will be much less than enabling it for all Jetty components. - -For example, if you need to troubleshoot a client that sends bad HTTP/1.1 requests, it may be enough to enable only the `org.eclipse.jetty.http` logger name, therefore saving the large amount of DEBUG logging produced by the I/O subsystem and by the thread pool. - -In another case, you may need to troubleshoot only HTTP/2 requests, and therefore enabling only the `org.eclipse.jetty.http2` logger name could be enough. diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/xml/chapter.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/xml/chapter.adoc deleted file mode 100644 index 683976da34f8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/xml/chapter.adoc +++ /dev/null @@ -1,27 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-xml]] -=== Jetty XML - -// TODO: merge this small section into the syntax and maybe call it "Jetty XML Reference". - -The Jetty XML format is a straightforward mapping of XML elements to Java APIs so that any object can be instantiated and getters, setters, and methods can be called. - -The Jetty XML format is very similar to that of frameworks like Spring or Plexus, although it predates all of them and it's typically more powerful as it can invoke any Java API. - -The Jetty XML format is used in xref:og-modules[Jetty modules] to create the Jetty server components, as well as in xref:og-deploy[Jetty XML context files] to configure web applications, but it can be used to call any Java API. - -include::xml-syntax.adoc[] - -// TODO: port the documentation from old_docs/jetty-xml/*.adoc diff --git a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/xml/xml-syntax.adoc b/documentation/jetty-documentation/src/main/asciidoc/operations-guide/xml/xml-syntax.adoc deleted file mode 100644 index ebf21db61aa5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/operations-guide/xml/xml-syntax.adoc +++ /dev/null @@ -1,506 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[og-xml-syntax]] -==== Jetty XML Syntax - -The Jetty XML syntax defines XML element that allow you to call any Java API and that allow you to interact in a simpler way with the xref:og-modules[Jetty module system] and the xref:og-deploy[Jetty deploy system]. - -The Jetty XML elements define attributes such as `id`, `name`, `class`, etc. that may be replaced by correspondent elements, so that these XML documents are equivalent: - -[source,xml] ----- - - - - - - - - ----- - -[source,xml] ----- - - - - - - stderr - err - java.lang.System - - println - HELLO - - - ----- - -The version using attributes is typically shorter and nicer to read, but sometimes the attribute value cannot be a literal string (for example, it could be the value of a system property) and that's where elements gives you the required flexibility. - -[[og-xml-syntax-configure]] -===== `` - -Element `Configure` must be the root element of the XML document. - -The following Jetty XML creates an empty `String` and assigns it the id `mystring`: - -[source,xml] ----- - - - - ----- - -This is equivalent to the following Java code: - -[source,java] ----- -var mystring = new String(); ----- - -If an object with the id `mystring` already exists, then it is not created again but rather just referenced. - -Within element ``, the created object (if any) is in xref:og-xml-syntax-scope[scope] and may be the implicit target of other, nested, elements. - -Typically the `` element is used to configure a `Server` instance or `ContextHandler` subclasses such as `WebAppContext` that represent web applications. - -[[og-xml-syntax-arg]] -===== `` - -Element `Arg` is used to pass arguments to xref:og-xml-syntax-new[constructors] and xref:og-xml-syntax-call[method calls]. - -The following example creates a minimal Jetty `Server`: - -[source,xml] ----- - - - - - 8080 - ----- - -Arguments may have a `type` attribute that explicitly performs xref:og-xml-syntax-types[type coercion]. - -Arguments may also have a `name` attribute, which is matched with the corresponding Java annotation in the source class, that helps to identify arguments: - -[source,xml] ----- - - - - - 8080 - ----- - -[[og-xml-syntax-new]] -===== `` - -Element `` creates a new object of the type specified by the mandatory `class` attribute. -A sequence of `Arg` elements, that must be contiguous and before other elements, may be present to specify the constructor arguments. - -Within element `` the newly created object is in xref:og-xml-syntax-scope[scope] and may be the implicit target of other, nested, elements. - -The following example creates an `ArrayList`: - -[source,xml] ----- - - - - - - 16 - - ----- - -This is equivalent to the following Java code: - -[source,java] ----- -var mylist = new ArrayList(16); ----- - -[[og-xml-syntax-call]] -===== `` - -Element `` invokes a method specified by the mandatory `name` attribute. -A sequence of `Arg` elements, that must be contiguous and before other elements, may be present to specify the method arguments. - -Within element `` the return value, if the return type is not `void`, is in xref:og-xml-syntax-scope[scope] and may be the implicit target of other, nested, elements. - -[source,xml] ----- - - - - - - - 0 - - - - ----- - -This is equivalent to the following Java code: - -[source,java] ----- -new ArrayList().listIterator(0).next(); ----- - -It is possible to call `static` methods by specifying the `class` attribute: - -[source,xml] ----- - - - - - - jdk.java.net - - ----- - -This is equivalent to the following Java code: - -[source,java] ----- -var myhost = InetAddress.getByName("jdk.java.net"); ----- - -The `class` attribute (or `` element) can also be used to specify the Java class or interface to use to lookup the non-``static`` method name. -This is necessary when the object in scope, onto which the `` would be applied, is an instance of a class that is not visible to Jetty classes, or not accessible because it is not `public`. -For example: - -[source,xml,subs=normal] ----- - - - - - - ## - - ----- - -In the example above, `Executors.newSingleThreadScheduledExecutor()` returns an object whose class is a private JDK implementation class. -Without an explicit `class` attribute (or `` element), it is not possible to invoke the method `shutdown()` when it is obtained via reflection from the private JDK implementation class, because while the method is `public`, the private JDK implementation class is not, therefore this exception is thrown: - -[source] ----- -java.lang.IllegalAccessException: class org.eclipse.jetty.xml.XmlConfiguration$JettyXmlConfiguration (in module org.eclipse.jetty.xml) cannot access a member of class java.util.concurrent.Executors$DelegatedExecutorService (in module java.base) with modifiers "public" ----- - -The solution is to explicitly use the `class` attribute (or `` element) of the `` element that is invoking the `shutdown()` method, specifying a publicly accessible class or interface that the object in scope extends or implements (in the example above `java.util.concurrent.ExecutorService`). - -[[og-xml-syntax-get]] -===== `` - -Element `` retrieves the value of a JavaBean property specified by the mandatory `name` attribute. - -If the JavaBean property is `foo` (or `Foo`), `` first attempts to invoke _method_ `getFoo()` or _method_ `isFoo()`; failing that, attempts to retrieve the value from _field_ `foo` (or `Foo`). - -[source,xml] ----- - - - - - - - - - - - Jetty - - - ----- - -The `class` attribute (or `` element) allows to perform `static` calls, or to lookup the getter method from the specified class, as described in the xref:og-xml-syntax-call[`` section]. - -[[og-xml-syntax-set]] -===== `` - -Element `` stores the value of a JavaBean property specified by the mandatory `name` attribute. - -If the JavaBean property is `foo` (or `Foo`), `` first attempts to invoke _method_ `setFoo(...)` with the value in the xref:og-xml-syntax-scope[scope] as argument; failing that, attempts to store the value in the scope to _field_ `foo` (or `Foo`). - -[source,xml] ----- - - - - - - true - - - - - - ----- - -The `class` attribute (or `` element) allows to perform `static` calls, or to lookup the setter method from the specified class, as described in the xref:og-xml-syntax-call[`` section]. - -[[og-xml-syntax-map]] -===== `` and `` - -Element `` allows the creation of a new `java.util.Map` implementation, specified by the `class` attribute -- by default a `HashMap`. - -The map entries are specified with a sequence of `` elements, each with exactly 2 `` elements, for example: - -[source,xml] ----- - - - - - - - host - - - localhost - - - - - ----- - -[[og-xml-syntax-put]] -===== `` - -Element `` is a convenience element that puts a key/value pair into objects that implement `java.util.Map`. -You can only specify the key value via the `name` attribute, so the key can only be a literal string (for keys that are not literal strings, use the `` element). - -[source,xml] ----- - - - - - - - - localhost - - - - ----- - -[[og-xml-syntax-array]] -===== `` and `` - -Element `` creates a new array, whose component type may be specified by the `type` attribute, or by a `Type` child element. - -[source,xml] ----- - - - - - - - literalString - - 1.0D - - - - - ----- - -[[og-xml-syntax-ref]] -===== `` - -Element `` allows you to reference an object via the `refid` attribute`, putting it into xref:og-xml-syntax-scope[scope] so that nested elements can operate on it. -You must give a unique `id` attribute to the objects you want to reference. - -[source,xml] ----- - - - - - - - - - - - - - - - Server version is: - - - ----- - -[[og-xml-syntax-property]] -===== `` - -Element `` retrieves the value of the Jetty module property specified by the `name` attribute, and it is mostly used when creating xref:og-modules-custom[custom Jetty modules] or when using xref:og-deploy-jetty[Jetty context XML files]. - -The `deprecated` attribute allows you to specify a comma separated list of old, deprecated, property names for backward compatibility. - -The `default` attribute allows you to specify a default value for the property, if it has not been explicitly defined. - -For example, you may want to configure the context path of your web application in this way: - -[source,xml,subs=normal] ----- - - - - - - ## - - /opt/myapps/mywiki.war - ----- - -The `contextPath` value is resolved by looking for the Jetty module property `com.myapps.mywiki.context.path`; if this property is not set, then the default value of `/wiki` is used. - -[[og-xml-syntax-system-property]] -===== `` - -Element `` retrieves the value of the JVM system property specified by the `name` attribute, via `System.getProperty(...)`. - -The `deprecated` attribute allows you to specify a comma separated list of old, deprecated, system property names for backward compatibility. - -The `default` attribute allows you to specify a default value for the system property value, if it has not been explicitly defined. - -The following example creates a minimal Jetty `Server` that listens on a port specified by the `com.acme.http.port` system property: - -[source,xml] ----- - - - - - - - - ----- - -[[og-xml-syntax-env]] -===== `` - -Element `` retrieves the value of the environment variable specified by the `name` attribute, via `System.getenv(...)`. - -The `deprecated` attribute allows you to specify a comma separated list of old, deprecated, environment variable names for backward compatibility. - -The `default` attribute allows you to specify a default value for the environment variable value, if it has not been explicitly defined. - -The following example creates a minimal Jetty `Server` that listens on a port specified by the `COM_ACME_HTTP_PORT` environment variable: - -[source,xml] ----- - - - - - - - - ----- - -[[og-xml-syntax-types]] -===== Type Coercion - -Elements that have the `type` attribute explicitly perform the type coercion of the string value present in the XML document to the Java type specified by the `type` attribute. - -Supported types are the following: - -* all primitive types and their boxed equivalents, for example `type="int"` but also `type="Integer"` (short form) and `type="java.lang.Integer"` (fully qualified form) -* `java.lang.String`, in both short form and fully qualified form -* `java.net.URL`, in both short form and fully qualified form -* `java.net.InetAddress`, in both short form and fully qualified form - -[[og-xml-syntax-scope]] -===== Scopes - -Elements that create new objects or that return a value create a _scope_. -Within these elements there may be nested elements that will operate on that scope, i.e. on the new object or returned value. - -The following example illustrates how scopes work: - -[source,xml] ----- - - - - - 8080 - - - - 5000 - - - - - - - https - - - - - - - - 256 - - - - - - - - - - - - - - - Server version is: - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/.asciidoctorconfig b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/.asciidoctorconfig deleted file mode 100644 index 32851d8dfbdb..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/.asciidoctorconfig +++ /dev/null @@ -1,5 +0,0 @@ -// Asciidoctor IDE configuration file. -// See https://github.com/asciidoctor/asciidoctor-intellij-plugin/wiki/Support-project-specific-configurations -:experimental: -:imagesdir: images -:doc_code: ../../java diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-bean.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-bean.adoc deleted file mode 100644 index 3eaa8d7888f6..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-bean.adoc +++ /dev/null @@ -1,161 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-arch-bean]] -=== Jetty Component Architecture - -Applications that use the Jetty libraries (both client and server) create objects from Jetty classes and compose them together to obtain the desired functionalities. - -A client application creates a `ClientConnector` instance, a `HttpClientTransport` instance and an `HttpClient` instance and compose them to have a working HTTP client that uses to call third party services. - -A server application creates a `ThreadPool` instance, a `Server` instance, a `ServerConnector` instance, a `Handler` instance and compose them together to expose an HTTP service. - -Internally, the Jetty libraries create even more instances of other components that also are composed together with the main ones created by applications. - -The end result is that an application based on the Jetty libraries is a _tree_ of components. -In server application the root of the component tree is a `Server` instance, while in client applications the root of the component tree is an `HttpClient` instance. - -Having all the Jetty components in a tree is beneficial in a number of use cases. -It makes possible to register the components in the tree as xref:pg-arch-jmx[JMX MBeans] so that a JMX console can look at the internal state of the components. -It also makes possible to xref:pg-troubleshooting-component-dump[dump the component tree] (and therefore each component's internal state) to a log file or to the console for xref:pg-troubleshooting[troubleshooting purposes]. -// TODO: add a section on Dumpable? - -[[pg-arch-bean-lifecycle]] -==== Jetty Component Lifecycle - -Jetty components typically have a life cycle: they can be started and stopped. -The Jetty components that have a life cycle implement the `org.eclipse.jetty.util.component.LifeCycle` interface. - -Jetty components that contain other components implement the `org.eclipse.jetty.util.component.Container` interface and typically extend the `org.eclipse.jetty.util.component.ContainerLifeCycle` class. -`ContainerLifeCycle` can contain these type of components, also called __bean__s: - -* _managed_ beans, `LifeCycle` instances whose life cycle is tied to the life cycle of their container -* _unmanaged_ beans, `LifeCycle` instances whose life cycle is _not_ tied to the life cycle of their container -* _POJO_ (Plain Old Java Object) beans, instances that do not implement `LifeCycle` - -`ContainerLifeCycle` uses the following logic to determine if a bean should be _managed_, _unmanaged_ or _POJO_: - -* the bean implements `LifeCycle` -** the bean is not started, add it as _managed_ -** the bean is started, add it as _unmanaged_ -* the bean does not implement `LifeCycle`, add it as _POJO_ - -When a `ContainerLifeCycle` is started, it also starts recursively all its managed beans (if they implement `LifeCycle`); unmanaged beans are not started during the `ContainerLifeCycle` start cycle. -Likewise, stopping a `ContainerLifeCycle` stops recursively and in reverse order all its managed beans; unmanaged beans are not stopped during the `ContainerLifeCycle` stop cycle. - -Components can also be started and stopped individually, therefore activating or deactivating the functionalities that they offer. - -Applications should first compose components in the desired structure, and then start the root component: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/ComponentDocs.java[tags=start] ----- - -The component tree is the following: - -[source,screen] ----- -Root -├── Monitor (MANAGED) -└── Service (MANAGED) - └── ScheduledExecutorService (POJO) ----- - -When the `Root` instance is created, also the `Monitor` instance is created and added as bean, so `Monitor` is the first bean of `Root`. -`Monitor` is a _managed_ bean, because it has been explicitly added to `Root` via `ContainerLifeCycle.addManaged(...)`. - -Then, the application creates a `Service` instance and adds it to `Root` via `ContainerLifeCycle.addBean(...)`, so `Service` is the second bean of `Root`. -`Service` is a _managed_ bean too, because it is a `LifeCycle` and at the time it was added to `Root` is was not started. - -The `ScheduledExecutorService` within `Service` does not implement `LifeCycle` so it is added as a _POJO_ to `Service`. - -It is possible to stop and re-start any component in a tree, for example: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/ComponentDocs.java[tags=restart] ----- - -`Service` can be stopped independently of `Root`, and re-started. -Starting and stopping a non-root component does not alter the structure of the component tree, just the state of the subtree starting from the component that has been stopped and re-started. - -`Container` provides an API to find beans in the component tree: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/ComponentDocs.java[tags=getBeans] ----- - -You can add your own beans to the component tree at application startup time, and later find them from your application code to access their services. - -[TIP] -==== -The component tree should be used for long-lived or medium-lived components such as thread pools, web application contexts, etc. - -It is not recommended adding to, and removing from, the component tree short-lived objects such as HTTP requests or TCP connections, for performance reasons. - -If you need component tree features such as automatic xref:pg-arch-jmx[export to JMX] or xref:pg-troubleshooting-component-dump[dump capabilities] for short-lived objects, consider having a long-lived container in the component tree instead. -You can make the long-lived container efficient at adding/removing the short-lived components using a data structure that is not part of the component tree, and make the long-lived container handle the JMX and dump features for the short-lived components. -==== - -[[pg-arch-bean-listener]] -==== Jetty Component Listeners - -A component that extends `AbstractLifeCycle` inherits the possibility to add/remove event _listeners_ for various events emitted by components. - -A component that implements `java.util.EventListener` that is added to a `ContainerLifeCycle` is also registered as an event listener. - -The following sections describe in details the various listeners available in the Jetty component architecture. - -[[pg-arch-bean-listener-lifecycle]] -===== LifeCycle.Listener - -A `LifeCycle.Listener` emits events for life cycle events such as starting, stopping and failures: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/ComponentDocs.java[tags=lifecycleListener] ----- - -For example, a life cycle listener attached to a `Server` instance could be used to create (for the _started_ event) and delete (for the _stopped_ event) a file containing the process ID of the JVM that runs the `Server`. - -[[pg-arch-bean-listener-container]] -===== Container.Listener - -A component that implements `Container` is a container for other components and `ContainerLifeCycle` is the typical implementation. - -A `Container` emits events when a component (also called _bean_) is added to or removed from the container: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/ComponentDocs.java[tags=containerListener] ----- - -A `Container.Listener` added as a bean will also be registered as a listener: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/ComponentDocs.java[tags=containerSiblings] ----- - -[[pg-arch-bean-listener-inherited]] -===== Container.InheritedListener - -A `Container.InheritedListener` is a listener that will be added to all descendants that are also ``Container``s. - -Listeners of this type may be added to the component tree root only, but will be notified of every descendant component that is added to or removed from the component tree (not only first level children). - -The primary use of `Container.InheritedListener` within the Jetty Libraries is `MBeanContainer` from the xref:pg-arch-jmx[Jetty JMX support]. - -`MBeanContainer` listens for every component added to the tree, converts it to an MBean and registers it to the MBeanServer; for every component removed from the tree, it unregisters the corresponding MBean from the MBeanServer. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-io.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-io.adoc deleted file mode 100644 index b142faa738ac..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-io.adoc +++ /dev/null @@ -1,202 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-arch-io]] -=== Jetty I/O Architecture - -Jetty libraries (both client and server) use Java NIO to handle I/O, so that at its core Jetty I/O is completely non-blocking. - -[[pg-arch-io-selector-manager]] -==== Jetty I/O: `SelectorManager` - -The core class of Jetty I/O is link:{javadoc-url}/org/eclipse/jetty/io/SelectorManager.html[`SelectorManager`]. - -`SelectorManager` manages internally a configurable number of link:{javadoc-url}/org/eclipse/jetty/io/ManagedSelector.html[`ManagedSelector`]s. -Each `ManagedSelector` wraps an instance of `java.nio.channels.Selector` that in turn manages a number of `java.nio.channels.SocketChannel` instances. - -NOTE: TODO: add image - -`SocketChannel` instances can be created by clients when connecting to a server and by a server when accepting connections from clients. -In both cases the `SocketChannel` instance is passed to `SelectorManager` (which passes it to `ManagedSelector` and eventually to `java.nio.channels.Selector`) to be registered for use within Jetty. - -It is possible for an application to create the `SocketChannel` instances outside Jetty, even perform some initial network traffic also outside Jetty (for example for authentication purposes), and then pass the `SocketChannel` instance to `SelectorManager` for use within Jetty. - -This example shows how a client can connect to a server: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/SelectorManagerDocs.java[tags=connect] ----- - -This example shows how a server accepts a client connection: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/SelectorManagerDocs.java[tags=accept] ----- - -[[pg-arch-io-endpoint-connection]] -==== Jetty I/O: `EndPoint` and `Connection` - -``SocketChannel``s that are passed to `SelectorManager` are wrapped into two related components: an link:{javadoc-url}/org/eclipse/jetty/io/EndPoint.html[`EndPoint`] and a link:{javadoc-url}/org/eclipse/jetty/io/Connection.html[`Connection`]. - -`EndPoint` is the Jetty abstraction for a `SocketChannel` or a `DatagramChannel`: you can read bytes from an `EndPoint`, you can write bytes to an `EndPoint` , you can close an `EndPoint`, etc. - -`Connection` is the Jetty abstraction that is responsible to read bytes from the `EndPoint` and to deserialize the read bytes into objects. -For example, an HTTP/1.1 server-side `Connection` implementation is responsible to deserialize HTTP/1.1 request bytes into an HTTP request object. -Conversely, an HTTP/1.1 client-side `Connection` implementation is responsible to deserialize HTTP/1.1 response bytes into an HTTP response object. - -`Connection` is the abstraction that implements the reading side of a specific protocol such as HTTP/1.1, or HTTP/2, or HTTP/3, or WebSocket: it is able to read incoming communication in that protocol. - -The writing side for a specific protocol _may_ be implemented in the `Connection` but may also be implemented in other components, although eventually the bytes to be written will be written through the `EndPoint`. - -While there are primarily only two implementations of `EndPoint`,link:{javadoc-url}/org/eclipse/jetty/io/SocketChannelEndPoint.html[`SocketChannelEndPoint`] for TCP and link:{javadoc-url}/org/eclipse/jetty/io/DatagramChannelEndPoint.html[`DatagramChannelEndPoint`] for UDP (used both on the client-side and on the server-side), there are many implementations of `Connection`, typically two for each protocol (one for the client-side and one for the server-side). - -The `EndPoint` and `Connection` pairs can be chained, for example in case of encrypted communication using the TLS protocol. -There is an `EndPoint` and `Connection` TLS pair where the `EndPoint` reads the encrypted bytes from the socket and the `Connection` decrypts them; next in the chain there is an `EndPoint` and `Connection` pair where the `EndPoint` "reads" decrypted bytes (provided by the previous `Connection`) and the `Connection` deserializes them into specific protocol objects (for example HTTP/2 frame objects). - -Certain protocols, such as WebSocket, start the communication with the server using one protocol (for example, HTTP/1.1), but then change the communication to use another protocol (for example, WebSocket). -`EndPoint` supports changing the `Connection` object on-the-fly via `EndPoint.upgrade(Connection)`. -This allows to use the HTTP/1.1 `Connection` during the initial communication and later to replace it with a WebSocket `Connection`. - -// TODO: add a section on `UpgradeFrom` and `UpgradeTo`? - -`SelectorManager` is an abstract class because while it knows how to create concrete `EndPoint` instances, it does not know how to create protocol specific `Connection` instances. - -Creating `Connection` instances is performed on the server-side by link:{javadoc-url}/org/eclipse/jetty/server/ConnectionFactory.html[`ConnectionFactory`]s and on the client-side by link:{javadoc-url}/org/eclipse/jetty/io/ClientConnectionFactory.html[`ClientConnectionFactory`]s. - -On the server-side, the component that aggregates a `SelectorManager` with a set of ``ConnectionFactory``s is link:{javadoc-url}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`] for TCP sockets, link:{javadoc-url}/org/eclipse/jetty/quic/server/QuicServerConnector.html[`QuicServerConnector`] for QUIC sockets, and link:{JDURL}/org/eclipse/jetty/unixdomain/server/UnixDomainServerConnector.html[`UnixDomainServerConnector`] for Unix-Domain sockets (see the xref:pg-server-io-arch[server-side architecture section] for more information). - -On the client-side, the components that aggregates a `SelectorManager` with a set of ``ClientConnectionFactory``s are link:{javadoc-url}/org/eclipse/jetty/client/HttpClientTransport.html[`HttpClientTransport`] subclasses (see the xref:pg-client-io-arch[client-side architecture section] for more information). - -[[pg-arch-io-endpoint]] -==== Jetty I/O: `EndPoint` - -The Jetty I/O library use Java NIO to handle I/O, so that I/O is non-blocking. - -At the Java NIO level, in order to be notified when a `SocketChannel` or `DatagramChannel` has data to be read, the `SelectionKey.OP_READ` flag must be set. - -In the Jetty I/O library, you can call `EndPoint.fillInterested(Callback)` to declare interest in the "read" (also called "fill") event, and the `Callback` parameter is the object that is notified when such an event occurs. - -At the Java NIO level, a `SocketChannel` or `DatagramChannel` is always writable, unless it becomes congested. -In order to be notified when a channel uncongests and it is therefore writable again, the `SelectionKey.OP_WRITE` flag must be set. - -In the Jetty I/O library, you can call `EndPoint.write(Callback, ByteBuffer...)` to write the ``ByteBuffer``s and the `Callback` parameter is the object that is notified when the whole write is finished (i.e. _all_ ``ByteBuffer``s have been fully written, even if they are delayed by congestion/uncongestion). - -The `EndPoint` APIs abstract out the Java NIO details by providing non-blocking APIs based on `Callback` objects for I/O operations. -The `EndPoint` APIs are typically called by `Connection` implementations, see xref:pg-arch-io-connection[this section]. - -[[pg-arch-io-connection]] -==== Jetty I/O: `Connection` - -`Connection` is the abstraction that deserializes incoming bytes into objects, for example an HTTP request object or a WebSocket frame object, that can be used by more abstract layers. - -`Connection` instances have two lifecycle methods: - -* `Connection.onOpen()`, invoked when the `Connection` is associated with the `EndPoint` -* `Connection.onClose(Throwable)`, invoked when the `Connection` is disassociated from the `EndPoint`, where the `Throwable` parameter indicates whether the disassociation was normal (when the parameter is `null`) or was due to an error (when the parameter is not `null`) - -When a `Connection` is first created, it is not registered for any Java NIO event. -It is therefore typical to implement `onOpen()` to call `EndPoint.fillInterested(Callback)` so that the `Connection` declares interest for read events and it is invoked (via the `Callback`) when the read event happens. - -Abstract class `AbstractConnection` partially implements `Connection` and provides simpler APIs. -The example below shows a typical implementation that extends `AbstractConnection`: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/SelectorManagerDocs.java[tags=connection] ----- - -[[pg-arch-io-connection-listener]] -===== Jetty I/O: `Connection.Listener` - -TODO - -[[pg-arch-io-echo]] -==== Jetty I/O: TCP Network Echo - -With the concepts above it is now possible to write a simple, fully non-blocking, `Connection` implementation that simply echoes the bytes that it reads back to the other peer. - -A naive, but wrong, implementation may be the following: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/SelectorManagerDocs.java[tags=echo-wrong] ----- - -WARNING: The implementation above is wrong and leads to `StackOverflowError`. - -The problem with this implementation is that if the writes always complete synchronously (i.e. without being delayed by TCP congestion), you end up with this sequence of calls: - ----- -Connection.onFillable() - EndPoint.write() - Connection.succeeded() - Connection.onFillable() - EndPoint.write() - Connection.succeeded() - ... ----- - -which leads to `StackOverflowError`. - -This is a typical side effect of asynchronous programming using non-blocking APIs, and happens in the Jetty I/O library as well. - -NOTE: The callback is invoked synchronously for efficiency reasons. -Submitting the invocation of the callback to an `Executor` to be invoked in a different thread would cause a context switch and make simple writes extremely inefficient. - -This side effect of asynchronous programming leading to `StackOverflowError` is so common that the Jetty libraries have a generic solution for it: a specialized `Callback` implementation named `org.eclipse.jetty.util.IteratingCallback` that turns recursion into iteration, therefore avoiding the `StackOverflowError`. - -`IteratingCallback` is a `Callback` implementation that should be passed to non-blocking APIs such as `EndPoint.write(Callback, ByteBuffer...)` when they are performed in a loop. - -`IteratingCallback` works by starting the loop with `IteratingCallback.iterate()`. -In turn, this calls `IteratingCallback.process()`, an abstract method that must be implemented with the code that should be executed for each loop. - -Method `process()` must return: - -* `Action.SCHEDULED`, to indicate whether the loop has performed a non-blocking, possibly asynchronous, operation -* `Action.IDLE`, to indicate that the loop should temporarily be suspended to be resumed later -* `Action.SUCCEEDED` to indicate that the loop exited successfully - -Any exception thrown within `process()` exits the loops with a failure. - -Now that you know how `IteratingCallback` works, a correct implementation for the echo `Connection` is the following: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/SelectorManagerDocs.java[tags=echo-correct] ----- - -When `onFillable()` is called, for example the first time that bytes are available from the network, the iteration is started. -Starting the iteration calls `process()`, where a buffer is allocated and filled with bytes read from the network via `EndPoint.fill(ByteBuffer)`; the buffer is subsequently written back via `EndPoint.write(Callback, ByteBuffer...)` -- note that the callback passed to `EndPoint.write()` is `this`, i.e. the `IteratingCallback` itself; finally `Action.SCHEDULED` is returned, returning from the `process()` method. - -At this point, the call to `EndPoint.write(Callback, ByteBuffer...)` may have completed synchronously; `IteratingCallback` would know that and call `process()` again; within `process()`, the buffer has already been allocated so it will be reused, saving further allocations; the buffer will be filled and possibly written again; `Action.SCHEDULED` is returned again, returning again from the `process()` method. - -At this point, the call to `EndPoint.write(Callback, ByteBuffer...)` may have not completed synchronously, so `IteratingCallback` will not call `process()` again; the processing thread is free to return to the Jetty I/O system where it may be put back into the thread pool. -If this was the only active network connection, the system would now be idle, with no threads blocked, waiting that the `write()` completes. This thread-less wait is one of the most important features that make non-blocking asynchronous servers more scalable: they use less resources. - -Eventually, the Jetty I/O system will notify that the `write()` completed; this notifies the `IteratingCallback` that can now resume the loop and call `process()` again. - -When `process()` is called, it is possible that zero bytes are read from the network; in this case, you want to deallocate the buffer since the other peer may never send more bytes for the `Connection` to read, or it may send them after a long pause -- in both cases we do not want to retain the memory allocated by the buffer; next, you want to call `fillInterested()` to declare again interest for read events, and return `Action.IDLE` since there is nothing to write back and therefore the loop may be suspended. -When more bytes are again available to be read from the network, `onFillable()` will be called again and that will start the iteration again. - -Another possibility is that during `process()` the read returns `-1` indicating that the other peer has closed the connection; this means that there will not be more bytes to read and the loop can be exited, so you return `Action.SUCCEEDED`; `IteratingCallback` will then call `onCompleteSuccess()` where you can close the `EndPoint`. - -The last case is that during `process()` an exception is thrown, for example by `EndPoint.fill(ByteBuffer)` or, in more advanced implementations, by code that parses the bytes that have been read and finds them unacceptable; any exception thrown within `process()` will be caught by `IteratingCallback` that will exit the loop with a failure and call `onCompleteFailure(Throwable)` with the exception that has been thrown, where you can close the `EndPoint`, passing the exception that is the reason for closing prematurely the `EndPoint`. - -[IMPORTANT] -==== -Asynchronous programming is hard. - -Rely on the Jetty classes to implement `Connection` to avoid mistakes that will be difficult to diagnose and reproduce. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-jmx.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-jmx.adoc deleted file mode 100644 index fb621056b539..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-jmx.adoc +++ /dev/null @@ -1,301 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-arch-jmx]] -=== Jetty JMX Support - -The Java Management Extensions (JMX) APIs are standard API for managing and monitoring resources such as applications, devices, services, and the Java Virtual Machine itself. - -The JMX API includes remote access, so a remote management console such as link:https://openjdk.java.net/projects/jmc/[Java Mission Control] can interact with a running application for these purposes. - -Jetty architecture is based on xref:pg-arch-bean[components] organized in a tree. Every time a component is added to or removed from the component tree, an event is emitted, and xref:pg-arch-bean-listener-container[Container.Listener] implementations can listen to those events and perform additional actions. - -`org.eclipse.jetty.jmx.MBeanContainer` listens to those events and registers/unregisters the Jetty components as MBeans into the platform MBeanServer. - -The Jetty components are annotated with xref:pg-arch-jmx-annotation[Jetty JMX annotations] so that they can provide specific JMX metadata such as attributes and operations that should be exposed via JMX. - -Therefore, when a component is added to the component tree, `MBeanContainer` is notified, it creates the MBean from the component POJO and registers it to the `MBeanServer`. -Similarly, when a component is removed from the tree, `MBeanContainer` is notified, and unregisters the MBean from the `MBeanServer`. - -The Maven coordinates for the Jetty JMX support are: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty - jetty-jmx - {version} - ----- - -==== Enabling JMX Support - -Enabling JMX support is always recommended because it provides valuable information about the system, both for monitoring purposes and for troubleshooting purposes in case of problems. - -To enable JMX support on the server: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=server] ----- - -Similarly on the client: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=client] ----- - -[NOTE] -==== -The MBeans exported to the platform MBeanServer can only be accessed locally (from the same machine), not from remote machines. - -This means that this configuration is enough for development, where you have easy access (with graphical user interface) to the machine where Jetty runs, but it is typically not enough when the machine where Jetty runs is remote, or only accessible via SSH or otherwise without graphical user interface support. -In these cases, you have to enable xref:pg-arch-jmx-remote[JMX Remote Access]. -==== - -// TODO: add a section about how to expose logging once #4830 is fixed. - -[[pg-arch-jmx-remote]] -==== Enabling JMX Remote Access - -There are two ways of enabling remote connectivity so that JMC can connect to the remote JVM to visualize MBeans. - -* Use the `com.sun.management.jmxremote` system property on the command line. -Unfortunately, this solution does not work well with firewalls and is not flexible. -* Use Jetty's `ConnectorServer` class. - -`org.eclipse.jetty.jmx.ConnectorServer` will use by default RMI to allow connection from remote clients, and it is a wrapper around the standard JDK class `JMXConnectorServer`, which is the class that provides remote access to JMX clients. - -Connecting to the remote JVM is a two step process: - -* First, the client will connect to the RMI _registry_ to download the RMI stub for the `JMXConnectorServer`; this RMI stub contains the IP address and port to connect to the RMI server, i.e. the remote `JMXConnectorServer`. -* Second, the client uses the RMI stub to connect to the RMI _server_ (i.e. the remote `JMXConnectorServer`) typically on an address and port that may be different from the RMI registry address and port. - -The host and port configuration for the RMI registry and the RMI server is specified by a `JMXServiceURL`. -The string format of an RMI `JMXServiceURL` is: - -[source,screen] ----- -service:jmx:rmi://:/jndi/rmi://:/jmxrmi ----- - -Default values are: - -[source,screen] ----- -rmi_server_host = localhost -rmi_server_port = 1099 -rmi_registry_host = localhost -rmi_registry_port = 1099 ----- - -With the default configuration, only clients that are local to the server machine can connect to the RMI registry and RMI server - this is done for security reasons. -With this configuration it would still be possible to access the MBeans from remote using a xref:pg-arch-jmx-remote-ssh-tunnel[SSH tunnel]. - -By specifying an appropriate `JMXServiceURL`, you can fine tune the network interfaces the RMI registry and the RMI server bind to, and the ports that the RMI registry and the RMI server listen to. -The RMI server and RMI registry hosts and ports can be the same (as in the default configuration) because RMI is able to multiplex traffic arriving to a port to multiple RMI objects. - -If you need to allow JMX remote access through a firewall, you must open both the RMI registry and the RMI server ports. - -`JMXServiceURL` common examples: - -[source,screen] ----- -service:jmx:rmi:///jndi/rmi:///jmxrmi - rmi_server_host = local host address - rmi_server_port = randomly chosen - rmi_registry_host = local host address - rmi_registry_port = 1099 - -service:jmx:rmi://0.0.0.0:1099/jndi/rmi://0.0.0.0:1099/jmxrmi - rmi_server_host = any address - rmi_server_port = 1099 - rmi_registry_host = any address - rmi_registry_port = 1099 - -service:jmx:rmi://localhost:1100/jndi/rmi://localhost:1099/jmxrmi - rmi_server_host = loopback address - rmi_server_port = 1100 - rmi_registry_host = loopback address - rmi_registry_port = 1099 ----- - -[NOTE] -==== -When `ConnectorServer` is started, its RMI stub is exported to the RMI registry. -The RMI stub contains the IP address and port to connect to the RMI object, but the IP address is typically the machine host name, not the host specified in the `JMXServiceURL`. - -To control the IP address stored in the RMI stub you need to set the system property `java.rmi.server.hostname` with the desired value. -This is especially important when binding the RMI server host to the loopback address for security reasons. See also xref:pg-arch-jmx-remote-ssh-tunnel[JMX Remote Access via SSH Tunnel.] -==== - -To allow JMX remote access, create and configure a `ConnectorServer`: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=remote] ----- - -[[pg-arch-jmx-remote-authorization]] -===== JMX Remote Access Authorization - -The standard `JMXConnectorServer` provides several options to authorize access, for example via JAAS or via configuration files. -For a complete guide to controlling authentication and authorization in JMX, see https://docs.oracle.com/en/java/javase/11/management/[the official JMX documentation]. - -In the sections below we detail one way to setup JMX authentication and authorization, using configuration files for users, passwords and roles: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=remoteAuthorization] ----- - -The `users.access` file format is defined in the `$JAVA_HOME/conf/management/jmxremote.access` file. -A simplified version is the following: - -.users.access -[source,screen] ----- -user1 readonly -user2 readwrite ----- - -The `users.password` file format is defined in the `$JAVA_HOME/conf/management/jmxremote.password.template` file. -A simplified version is the following: - -.users.password -[source,screen] ----- -user1 password1 -user2 password2 ----- - -CAUTION: The `users.access` and `users.password` files are not standard `*.properties` files -- the user must be separated from the role or password by a space character. - -===== Securing JMX Remote Access with TLS - -The JMX communication via RMI happens by default in clear-text. - -It is possible to configure the `ConnectorServer` with a `SslContextFactory` so that the JMX communication via RMI is encrypted: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=tlsRemote] ----- - -It is possible to use the same `SslContextFactory.Server` used to configure the Jetty `ServerConnector` that supports TLS also for the JMX communication via RMI. - -The keystore must contain a valid certificate signed by a Certification Authority. - -The RMI mechanic is the usual one: the RMI client (typically a monitoring console) will connect first to the RMI registry (using TLS), download the RMI server stub that contains the address and port of the RMI server to connect to, then connect to the RMI server (using TLS). - -This also mean that if the RMI registry and the RMI server are on different hosts, the RMI client must have available the cryptographic material to validate both hosts. - -Having certificates signed by a Certification Authority simplifies by a lot the configuration needed to get the JMX communication over TLS working properly. - -If that is not the case (for example the certificate is self-signed), then you need to specify the required system properties that allow RMI (especially when acting as an RMI client) to retrieve the cryptographic material necessary to establish the TLS connection. - -For example, trying to connect using the JDK standard `JMXConnector` with both the RMI server and the RMI registry via TLS to `domain.com` with a self-signed certificate: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=tlsJMXConnector] ----- - -Similarly, to launch JMC: - -[source,screen] ----- -$ jmc -vmargs -Djavax.net.ssl.trustStore=/path/to/trustStore -Djavax.net.ssl.trustStorePassword=secret ----- - -IMPORTANT: These system properties are required when launching the `ConnectorServer` too, on the server, because it acts as an RMI client with respect to the RMI registry. - -[[pg-arch-jmx-remote-ssh-tunnel]] -===== JMX Remote Access with Port Forwarding via SSH Tunnel - -You can access JMX MBeans on a remote machine when the RMI ports are not open, for example because of firewall policies, but you have SSH access to the machine using local port forwarding via an SSH tunnel. - -In this case you want to configure the `ConnectorServer` with a `JMXServiceURL` that binds the RMI server and the RMI registry to the loopback interface only: `service:jmx:rmi://localhost:1099/jndi/rmi://localhost:1099/jmxrmi`. - -Then you setup the local port forwarding with the SSH tunnel: - -[source,screen] ----- -$ ssh -L 1099:localhost:1099 @ ----- - -Now you can use JConsole or JMC to connect to `localhost:1099` on your local computer. -The traffic will be forwarded to `machine_host` and when there, SSH will forward the traffic to `localhost:1099`, which is exactly where the `ConnectorServer` listens. - -When you configure `ConnectorServer` in this way, you must set the system property `-Djava.rmi.server.hostname=localhost`, on the server. -This is required because when the RMI server is exported, its address and port are stored in the RMI stub. You want the address in the RMI stub to be `localhost` so that when the RMI stub is downloaded to the remote client, the RMI communication will go through the SSH tunnel. - -[[pg-arch-jmx-annotation]] -==== Jetty JMX Annotations - -The Jetty JMX support, and in particular `MBeanContainer`, is notified every time a bean is added to the component tree. - -The bean is scanned for Jetty JMX annotations to obtain JMX metadata: the JMX attributes and JMX operations. - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=jmxAnnotation] ----- - -The JMX metadata and the bean are wrapped by an instance of `org.eclipse.jetty.jmx.ObjectMBean` that exposes the JMX metadata and, upon request from JMX consoles, invokes methods on the bean to get/set attribute values and perform operations. - -You can provide a custom subclass of `ObjectMBean` to further customize how the bean is exposed to JMX. - -The custom `ObjectMBean` subclass must respect the following naming convention: `.jmx.MBean`. -For example, class `com.acme.Foo` may have a custom `ObjectMBean` subclass named `com.acme.**jmx**.Foo**MBean**`. - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=jmxCustomMBean] ----- - -The custom `ObjectMBean` subclass is also scanned for Jetty JMX annotations and overrides the JMX metadata obtained by scanning the bean class. -This allows to annotate only the custom `ObjectMBean` subclass and keep the bean class free of the Jetty JMX annotations. - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/JMXDocs.java[tags=jmxCustomMBeanOverride] ----- - -The scan for Jetty JMX annotations is performed on the bean class and all the interfaces implemented by the bean class, then on the super-class and all the interfaces implemented by the super-class and so on until `java.lang.Object` is reached. -For each type -- class or interface, the corresponding `+*.jmx.*MBean+` is looked up and scanned as well with the same algorithm. -For each type, the scan looks for the class-level annotation `@ManagedObject`. -If it is found, the scan looks for method-level `@ManagedAttribute` and `@ManagedOperation` annotations; otherwise it skips the current type and moves to the next type to scan. - -===== @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. - -===== @ManagedAttribute - -The `@ManagedAttribute` annotation is used to indicate that a given method is exposed as a JMX attribute. -This annotation is placed always on the getter method of a given attribute. -Unless the `readonly` attribute is set to `true` in the annotation, a corresponding setter is looked up following normal naming conventions. -For example if this annotation is on a method called `String getFoo()` then a method called `void setFoo(String)` would be looked up, and if found wired as the setter for the JMX attribute. - -===== @ManagedOperation - -The `@ManagedOperation` annotation is used to indicate that a given method is exposed as a JMX operation. -A JMX operation has an _impact_ that can be `INFO` if the operation returns a value without modifying the object, `ACTION` if the operation does not return a value but modifies the object, and "ACTION_INFO" if the operation both returns a value and modifies the object. -If the _impact_ is not specified, it has the default value of `UNKNOWN`. - -===== @Name - -The `@Name` annotation is used to assign a name and description to parameters in method signatures so that when rendered by JMX consoles it is clearer what the parameter meaning is. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-listener.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-listener.adoc deleted file mode 100644 index a6dbe5596fa5..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-listener.adoc +++ /dev/null @@ -1,28 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-arch-listener]] -=== Jetty Listeners - -The Jetty architecture is based on xref:pg-arch-bean[components], typically organized in a component tree. -These components have an internal state that varies with the component life cycle (that is, whether the component is started or stopped), as well as with the component use at runtime. -The typical example is a thread pool, whose internal state -- such as the number of pooled threads or the job queue size -- changes as the thread pool is used by the running client or server. - -In many cases, the component state change produces an event that is broadcast to listeners. -Applications can register listeners to these components to be notified of the events they produce. - -This section lists the listeners available in the Jetty components, but the events and listener APIs are discussed in the component specific sections. - -* xref:pg-arch-bean-listener[] -* xref:pg-arch-io-connection-listener[] -* xref:pg-server-http-channel-events[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-threads.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-threads.adoc deleted file mode 100644 index a2accfc04ebf..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch-threads.adoc +++ /dev/null @@ -1,230 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-arch-threads]] -=== Jetty Threading Architecture - -Writing a performant client or server is difficult, because it should: - -* Scale well with the number of processors. -* Be efficient at using processor caches to avoid link:https://en.wikipedia.org/wiki/Parallel_slowdown[parallel slowdown]. -* Support multiple network protocols that may have very different requirements; for example, multiplexed protocols such as HTTP/2 introduce new challenges that are not present in non-multiplexed protocols such as HTTP/1.1. -* Support different application threading models; for example, if a Jetty server invokes server-side application code that is allowed to call blocking APIs, then the Jetty server should not be affected by how long the blocking API call takes, and should be able to process other connections or other requests in a timely fashion. - -[[pg-arch-threads-execution-strategy]] -==== Execution Strategies - -The Jetty threading architecture can be modeled with a producer/consumer pattern, where produced tasks needs to be consumed efficiently. - -For example, Jetty produces (among others) these tasks: - -* A task that wraps a NIO selection event, see the xref:pg-arch-io[Jetty I/O architecture]. -* A task that wraps the invocation of application code that may block (for example, the invocation of a Servlet to handle an HTTP request). - -A task is typically a `Runnable` object that may implement `org.eclipse.jetty.util.thread.Invocable` to indicate the behavior of the task (in particular, whether the task may block or not). - -Once a task has been produced, it may be consumed using these modes: - -* xref:pg-arch-threads-execution-strategy-pc[`Produce-Consume`] -* xref:pg-arch-threads-execution-strategy-pec[`Produce-Execute-Consume`] -* xref:pg-arch-threads-execution-strategy-epc[`Execute-Produce-Consume`] - -[[pg-arch-threads-execution-strategy-pc]] -===== Produce-Consume -In the `Produce-Consume` mode, the producer thread loops to produce a task that is run directly by the `Producer Thread`. - -[plantuml] ----- -skinparam backgroundColor transparent - -compact concise "Producer Thread" as PT -hide time-axis - -@PT -0 is T1 #lightgreen -1 is "Run T1" #dodgerblue -5 is T2 #lightgreen -6 is "Run T2" #dodgerblue -8 is T3 #lightgreen -9 is "Run T3" #dodgerblue -12 is {hidden} ----- - -If the task is a NIO selection event, then this mode is the thread-per-selector mode which is very CPU core cache efficient, but suffers from the link:http://en.wikipedia.org/wiki/Head-of-line_blocking[head-of-line blocking]: if one of the tasks blocks or runs slowly, then subsequent tasks cannot be produced (and therefore cannot be consumed either) and will pay in latency the cost of running previous, possibly unrelated, tasks. - -This mode should only be used if the produced task is known to never block, or if the system tolerates well (or does not care about) head-of-line blocking. - -[[pg-arch-threads-execution-strategy-pec]] -===== Produce-Execute-Consume -In the `Produce-Execute-Consume` mode, the `Producer Thread` loops to produce tasks that are submitted to a `java.util.concurrent.Executor` to be run by ``Worker Thread``s different from the `Producer Thread`. - -[plantuml] ----- -skinparam backgroundColor transparent - -compact concise "Producer Thread" as PT -compact concise "Worker Thread 1" as WT1 -compact concise "Worker Thread 2" as WT2 -compact concise "Worker Thread 3" as WT3 -hide time-axis - -@PT -0 is T1 #lightgreen -1 is T2 #lightgreen -2 is T3 #lightgreen -3 is T4 #lightgreen -4 is {hidden} - -@WT1 -1 is "Run T1" #dodgerblue -5 is {hidden} - -@WT2 -2 is "Run T2" #dodgerblue -4 is "Run T4" #dodgerblue -8 is {hidden} - -@WT3 -3 is "Run T3" #dodgerblue -6 is {hidden} ----- - -The `Executor` implementation typically adds the task to a queue, and dequeues the task when there is a worker thread available to run it. - -This mode solves the head-of-line blocking discussed in the xref:pg-arch-threads-execution-strategy-pc[`Produce-Consume` section], but suffers from other issues: - -* It is not CPU core cache efficient, as the data available to the producer thread will need to be accessed by another thread that likely is going to run on a CPU core that will not have that data in its caches. -* If the tasks take time to be run, the `Executor` queue may grow indefinitely. -* A small latency is added to every task: the time it waits in the `Executor` queue. - -[[pg-arch-threads-execution-strategy-epc]] -===== Execute-Produce-Consume -In the `Execute-Produce-Consume` mode, the producer thread `Thread 1` loops to produce a task, then submits one internal task to an `Executor` to take over production on thread `Thread 2`, and then runs the task in `Thread 1`, and so on. - -[plantuml] ----- -skinparam backgroundColor transparent - -compact concise "Thread 1" as WT1 -compact concise "Thread 2" as WT2 -compact concise "Thread 3" as WT3 -compact concise "Thread 4" as WT4 -hide time-axis - -@WT1 -0 is T1 #lightgreen -1 is "Run T1" #dodgerblue -5 is {hidden} - -@WT2 -1 is T2 #lightgreen -2 is "Run T2" #dodgerblue -4 is T5 #lightgreen -5 is "Run T5" #dodgerblue -10 is {hidden} - -@WT3 -2 is T3 #lightgreen -3 is "Run T3" #dodgerblue -6 is {hidden} - -@WT4 -3 is T4 #lightgreen -4 is "Run T4" #dodgerblue -8 is {hidden} - ----- - -This mode may operate like xref:pg-arch-threads-execution-strategy-pc[`Produce-Consume`] when the take over production task run, for example, by thread `Thread 3` takes time to be executed (for example, in a busy server): then thread `Thread 2` will produce one task and run it, then produce another task and run it, etc. -- `Thread 2` behaves exactly like the `Produce-Consume` mode. -By the time thread `Thread 3` takes over task production from `Thread 2`, all the work might already be done. - -This mode may also operate similarly to xref:pg-arch-threads-execution-strategy-pec[`Produce-Execute-Consume`] when the take over production task always finds a free CPU core immediately (for example, in a mostly idle server): thread `Thread 1` will produce a task, yield production to `Thread 2` while `Thread 1` is running the task; `Thread 2` will produce a task, yield production to `Thread 3` while `Thread 2` is running the task, etc. - -Differently from `Produce-Execute-Consume`, here production happens on different threads, but the advantage is that the task is run by the same thread that produced it (which is CPU core cache efficient). - -[[pg-arch-threads-execution-strategy-adaptive]] -===== Adaptive Execution Strategy -The modes of task consumption discussed above are captured by the `org.eclipse.jetty.util.thread.ExecutionStrategy` interface, with an additional implementation that also takes into account the behavior of the task when the task implements `Invocable`. - -For example, a task that declares itself as non-blocking can be consumed using the `Produce-Consume` mode, since there is no risk to stop production because the task will not block. - -Conversely, a task that declares itself as blocking will stop production, and therefore must be consumed using either the `Produce-Execute-Consume` mode or the `Execute-Produce-Consume` mode. -Deciding between these two modes depends on whether there is a free thread immediately available to take over production, and this is captured by the `org.eclipse.jetty.util.thread.TryExecutor` interface. - -An implementation of `TryExecutor` can be asked whether a thread can be immediately and exclusively allocated to run a task, as opposed to a normal `Executor` that can only queue the task in the expectation that there will be a thread available in the near future to run the task. - -The concept of task consumption modes, coupled with `Invocable` tasks that expose their own behavior, coupled with a `TryExecutor` that guarantees whether production can be immediately taken over are captured by the default Jetty execution strategy, named `org.eclipse.jetty.util.thread.AdaptiveExecutionStrategy`. - -[NOTE] -==== -`AdaptiveExecutionStrategy` was previously named `EatWhatYouKill`, named after a hunting proverb in the sense that one should produce (kill) only what it consumes (eats). -==== - -[[pg-arch-threads-thread-pool]] -==== Thread Pool -Jetty's xref:pg-arch-threads[threading architecture] requires a more sophisticated thread pool than what offered by Java's `java.util.concurrent.ExecutorService`. - -Jetty's default thread pool implementation is link:{javadoc-url}/org/eclipse/jetty/util/thread/QueuedThreadPool.html[`QueuedThreadPool`]. - -`QueuedThreadPool` integrates with the xref:pg-arch-bean[Jetty component model], implements `Executor`, provides a `TryExecutor` implementation (discussed in the xref:pg-arch-threads-execution-strategy-adaptive[adaptive execution strategy section]), and supports xref:pg-arch-threads-thread-pool-virtual-threads[virtual threads] (introduced as a preview feature in Java 19 and Java 20, and as an official feature since Java 21). - -`QueuedThreadPool` can be configured with a `maxThreads` value. - -However, some of the Jetty components (such as the xref:pg-arch-io-selector-manager[selectors]) permanently steal threads for their internal use, or rather `QueuedThreadPool` leases some threads to these components. -These threads are reported by `QueuedThreadPool.leasedThreads` and are not available to run application code. - -`QueuedThreadPool` can be configured with a `reservedThreads` value. -This value represents the maximum number of threads that can be reserved and used by the `TryExecutor` implementation. -A negative value for `QueuedThreadPool.reservedThreads` means that the actual value will be heuristically derived from the number of CPU cores and `QueuedThreadPool.maxThreads`. -A value of zero for `QueuedThreadPool.reservedThreads` means that reserved threads are disabled, and therefore the xref:pg-arch-threads-execution-strategy-epc[`Execute-Produce-Consume` mode] is never used -- the xref:pg-arch-threads-execution-strategy-pec[`Produce-Execute-Consume` mode] is always used instead. - -`QueuedThreadPool` always maintains the number of threads between `QueuedThreadPool.minThreads` and `QueuedThreadPool.maxThreads`; during load spikes the number of thread grows to meet the load demand, and when the load on the system diminishes or the system goes idle, the number of threads shrinks. - -Shrinking `QueuedThreadPool` is important in particular in containerized environments, where typically you want to return the memory occupied by the threads to the operative system. -The shrinking of the `QueuedThreadPool` is controlled by two parameters: `QueuedThreadPool.idleTimeout` and `QueuedThreadPool.maxEvictCount`. - -`QueuedThreadPool.idleTimeout` indicates how long a thread should stay around when it is idle, waiting for tasks to execute. -The longer the threads stay around, the more ready they are in case of new load spikes on the system; however, they consume resources: a Java platform thread typically allocates 1 MiB of native memory. - -`QueuedThreadPool.maxEvictCount` controls how many idle threads are evicted for one `QueuedThreadPool.idleTimeout` period. -The larger this value is, the quicker the threads are evicted when the `QueuedThreadPool` is idle or has less load, and their resources returned to the operative system; however, large values may result in too much thread thrashing: the `QueuedThreadPool` shrinks too fast and must re-create a lot of threads in case of a new load spike on the system. - -A good balance between `QueuedThreadPool.idleTimeout` and `QueuedThreadPool.maxEvictCount` depends on the load profile of your system, and it is often tuned via trial and error. - -[[pg-arch-threads-thread-pool-virtual-threads]] -===== Virtual Threads -Virtual threads have been introduced in Java 19 and Java 20 as a preview feature, and have become an official feature since Java 21. - -NOTE: In Java versions where virtual threads are a preview feature, remember to add `+--enable-preview+` to the JVM command line options to use virtual threads. - -`QueuedThreadPool` can be configured to use virtual threads by specifying the virtual threads `Executor`: - -[source,java] ----- -QueuedThreadPool threadPool = new QueuedThreadPool(); -threadPool.setVirtualThreadsExecutor(Executors.newVirtualThreadPerTaskExecutor()); ----- - -[CAUTION] -==== -Jetty cannot enforce that the `Executor` passed to `setVirtualThreadsExecutor(Executor)` uses virtual threads, so make sure to specify a _virtual_ threads `Executor` and not a normal `Executor` that uses platform threads. -==== - -`AdaptiveExecutionStrategy` makes use of this setting when it determines that a task should be run with the xref:pg-arch-threads-execution-strategy-pec[`Produce-Execute-Consume` mode]: rather than submitting the task to `QueuedThreadPool` to be run in a platform thread, it submits the task to the virtual threads `Executor`. - -[NOTE] -==== -Enabling virtual threads in `QueuedThreadPool` will default the number of reserved threads to zero, unless the number of reserved threads is explicitly configured to a positive value. - -Defaulting the number of reserved threads to zero ensures that the xref:pg-arch-threads-execution-strategy-pec[Produce-Execute-Consume mode] is always used, which means that virtual threads will always be used for blocking tasks. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch.adoc deleted file mode 100644 index 0af3d31c0b5f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/arch.adoc +++ /dev/null @@ -1,22 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[appendix] -[[pg-arch]] -== Jetty Architecture - -include::arch-bean.adoc[] -include::arch-threads.adoc[] -include::arch-io.adoc[] -include::arch-listener.adoc[] -include::arch-jmx.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/client-io-arch.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/client-io-arch.adoc deleted file mode 100644 index c009af61d40e..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/client-io-arch.adoc +++ /dev/null @@ -1,149 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-io-arch]] -=== I/O Architecture - -The Jetty client libraries provide the basic components and APIs to implement a network client. - -They build on the common xref:pg-arch-io[Jetty I/O Architecture] and provide client specific concepts (such as establishing a connection to a server). - -There are conceptually two layers that compose the Jetty client libraries: - -. xref:pg-client-io-arch-network[The network layer], that handles the low level I/O and deals with buffers, threads, etc. -. xref:pg-client-io-arch-protocol[The protocol layer], that handles the parsing of bytes read from the network and the generation of bytes to write to the network. - -[[pg-client-io-arch-network]] -==== Network Layer - -The Jetty client libraries use the common I/O design described in xref:pg-arch-io[this section]. -The main client-side component is the link:{javadoc-url}/org/eclipse/jetty/io/ClientConnector.html[`ClientConnector`]. - -The `ClientConnector` primarily wraps the link:{javadoc-url}/org/eclipse/jetty/io/SelectorManager.html[`SelectorManager`] and aggregates other four components: - -* a thread pool (in form of an `java.util.concurrent.Executor`) -* a scheduler (in form of `org.eclipse.jetty.util.thread.Scheduler`) -* a byte buffer pool (in form of `org.eclipse.jetty.io.ByteBufferPool`) -* a TLS factory (in form of `org.eclipse.jetty.util.ssl.SslContextFactory.Client`) - -The `ClientConnector` is where you want to set those components after you have configured them. -If you don't explicitly set those components on the `ClientConnector`, then appropriate defaults will be chosen when the `ClientConnector` starts. - -The simplest example that creates and starts a `ClientConnector` is the following: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java[tags=simplest] ----- - -A more typical example: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java[tags=typical] ----- - -A more advanced example that customizes the `ClientConnector` by overriding some of its methods: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java[tags=advanced] ----- - -Since `ClientConnector` is the component that handles the low-level network, it is also the component where you want to configure the low-level network configuration. - -The most common parameters are: - -* `ClientConnector.selectors`: the number of ``java.nio.Selector``s components (defaults to `1`) that are present to handle the ``SocketChannel``s opened by the `ClientConnector`. -You typically want to increase the number of selectors only for those use cases where each selector should handle more than few hundreds _concurrent_ socket events. -For example, one selector typically runs well for `250` _concurrent_ socket events; as a rule of thumb, you can multiply that number by `10` to obtain the number of opened sockets a selector can handle (`2500`), based on the assumption that not all the `2500` sockets will be active _at the same time_. -* `ClientConnector.idleTimeout`: the duration of time after which `ClientConnector` closes a socket due to inactivity (defaults to `30` seconds). -This is an important parameter to configure, and you typically want the client idle timeout to be shorter than the server idle timeout, to avoid race conditions where the client attempts to use a socket just before the client-side idle timeout expires, but the server-side idle timeout has already expired and the is already closing the socket. -* `ClientConnector.connectBlocking`: whether the operation of connecting a socket to the server (i.e. `SocketChannel.connect(SocketAddress)`) must be a blocking or a non-blocking operation (defaults to `false`). -For `localhost` or same datacenter hosts you want to set this parameter to -`true` because DNS resolution will be immediate (and likely never fail). -For generic Internet hosts (e.g. when you are implementing a web spider) you want to set this parameter to `false`. -* `ClientConnector.connectTimeout`: the duration of time after which `ClientConnector` aborts a connection attempt to the server (defaults to `5` seconds). -This time includes the DNS lookup time _and_ the TCP connect time. - -Please refer to the `ClientConnector` link:{javadoc-url}/org/eclipse/jetty/io/ClientConnector.html[javadocs] for the complete list of configurable parameters. - -[[pg-client-io-arch-unix-domain]] -===== Unix-Domain Support - -link:https://openjdk.java.net/jeps/380[JEP 380] introduced Unix-Domain sockets support in Java 16, on all operative systems. - -`ClientConnector` can be configured to support Unix-Domain sockets in the following way: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java[tags=unixDomain] ----- - -[IMPORTANT] -==== -You can use Unix-Domain sockets support only when you run your client application with Java 16 or later. -==== - -[[pg-client-io-arch-protocol]] -==== Protocol Layer - -The protocol layer builds on top of the network layer to generate the bytes to be written to the network and to parse the bytes read from the network. - -Recall from xref:pg-arch-io-connection[this section] that Jetty uses the `Connection` abstraction to produce and interpret the network bytes. - -On the client side, a `ClientConnectionFactory` implementation is the component that creates `Connection` instances based on the protocol that the client wants to "speak" with the server. - -Applications use `ClientConnector.connect(SocketAddress, Map)` to establish a TCP connection to the server, and must tell `ClientConnector` how to create the `Connection` for that particular TCP connection, and how to notify back the application when the connection creation succeeds or fails. - -This is done by passing a link:{javadoc-url}/org/eclipse/jetty/io/ClientConnectionFactory.html[`ClientConnectionFactory`] (that creates `Connection` instances) and a link:{javadoc-url}/org/eclipse/jetty/util/Promise.html[`Promise`] (that is notified of connection creation success or failure) in the context `Map` as follows: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java[tags=connect] ----- - -When a `Connection` is created successfully, its `onOpen()` method is invoked, and then the promise is completed successfully. - -It is now possible to write a super-simple `telnet` client that reads and writes string lines: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java[tags=telnet] ----- - -Note how a very basic "telnet" API that applications could use is implemented in the form of the `onLine(Consumer)` for the non-blocking receiving side and `writeLine(String, Callback)` for the non-blocking sending side. -Note also how the `onFillable()` method implements some basic "parsing" by looking up the `\n` character in the buffer. - -NOTE: The "telnet" client above looks like a super-simple HTTP client because HTTP/1.0 can be seen as a line-based protocol. -HTTP/1.0 was used just as an example, but we could have used any other line-based protocol such as link:https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol[SMTP], provided that the server was able to understand it. - -This is very similar to what the Jetty client implementation does for real network protocols. -Real network protocols are of course more complicated and so is the implementation code that handles them, but the general ideas are similar. - -The Jetty client implementation provides a number of `ClientConnectionFactory` implementations that can be composed to produce and interpret the network bytes. - -For example, it is simple to modify the above example to use the TLS protocol so that you will be able to connect to the server on port `443`, typically reserved for the encrypted HTTP protocol. - -The differences between the clear-text version and the TLS encrypted version are minimal: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java[tags=tlsTelnet] ----- - -The differences with the clear-text version are only: - -* Change the port from `80` to `443`. -* Wrap the `ClientConnectionFactory` with `SslClientConnectionFactory`. -* Unwrap the `SslConnection` to access `TelnetConnection`. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/client.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/client.adoc deleted file mode 100644 index cd103907e756..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/client.adoc +++ /dev/null @@ -1,37 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client]] -== Client Libraries - -The Eclipse Jetty Project provides client-side libraries that allow you to embed a client in your applications. -A typical example is a client application that needs to contact a third party service via HTTP (for example a REST service). -Another example is a proxy application that receives HTTP requests and forwards them as FCGI requests to a PHP application such as WordPress, or receives HTTP/1.1 requests and converts them to HTTP/2 or HTTP/3. -Yet another example is a client application that needs to receive events from a WebSocket server. - -The client libraries are designed to be non-blocking and offer both synchronous and asynchronous APIs and come with many configuration options. - -These are the available client libraries: - -* xref:pg-client-http[The High-Level HTTP Client Library] for HTTP/1.1, HTTP/2 and FastCGI -* xref:pg-client-http2[The Low-Level HTTP/2 Client Library] for low-level HTTP/2 -* xref:pg-client-http3[The Low-Level HTTP/3 Client Library] for low-level HTTP/3 -* xref:pg-client-websocket[The WebSocket client library] - -If you are interested in the low-level details of how the Eclipse Jetty client libraries work, or are interested in writing a custom protocol, look at the xref:pg-client-io-arch[Client I/O Architecture]. - -include::client-io-arch.adoc[] -include::http/client-http.adoc[] -include::http2/client-http2.adoc[] -include::http3/client-http3.adoc[] -include::websocket/client-websocket.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-api.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-api.adoc deleted file mode 100644 index 459b666b8669..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-api.adoc +++ /dev/null @@ -1,260 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http-api]] -==== HttpClient API Usage - -`HttpClient` provides two types of APIs: a blocking API and a non-blocking API. - -[[pg-client-http-blocking]] -===== HttpClient Blocking APIs - -The simpler way to perform a HTTP request is the following: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=simpleBlockingGet] ----- - -The method `HttpClient.GET(...)` performs a HTTP `GET` request to the given URI and returns a `ContentResponse` when the request/response conversation completes successfully. - -The `ContentResponse` object contains the HTTP response information: status code, headers and possibly content. -The content length is limited by default to 2 MiB; for larger content see xref:pg-client-http-content-response[the section on response content handling]. - -If you want to customize the request, for example by issuing a `HEAD` request instead of a `GET`, and simulating a browser user agent, you can do it in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=headFluent] ----- - -This is a shorthand for: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=headNonFluent] ----- - -You first create a request object using `httpClient.newRequest(...)`, and then you customize it using the fluent API style (that is, a chained invocation of methods on the request object). -When the request object is customized, you call `request.send()` that produces the `ContentResponse` when the request/response conversation is complete. - -IMPORTANT: The `Request` object, despite being mutable, cannot be reused for other requests. -This is true also when trying to send two or more identical requests: you have to create two or more `Request` objects. - -Simple `POST` requests also have a shortcut method: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=postFluent] ----- - -The `POST` parameter values added via the `param()` method are automatically URL-encoded. - -Jetty's `HttpClient` automatically follows redirects, so it handles the typical web pattern link:http://en.wikipedia.org/wiki/Post/Redirect/Get[POST/Redirect/GET], and the response object contains the content of the response of the `GET` request. -Following redirects is a feature that you can enable/disable on a per-request basis or globally. - -File uploads also require one line, and make use of `java.nio.file` classes: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=fileFluent] ----- - -It is possible to impose a total timeout for the request/response conversation using the `Request.timeout(...)` method as follows: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=totalTimeout] ----- - -In the example above, when the 5 seconds expire, the request/response cycle is aborted and a `java.util.concurrent.TimeoutException` is thrown. - -[[pg-client-http-non-blocking]] -===== HttpClient Non-Blocking APIs - -So far we have shown how to use Jetty HTTP client in a blocking style -- that is, the thread that issues the request blocks until the request/response conversation is complete. - -This section will look at Jetty's `HttpClient` non-blocking, asynchronous APIs that are perfectly suited for large content downloads, for parallel processing of requests/responses and in cases where performance and efficient thread and resource utilization is a key factor. - -The asynchronous APIs rely heavily on listeners that are invoked at various stages of request and response processing. -These listeners are implemented by applications and may perform any kind of logic. -The implementation invokes these listeners in the same thread that is used to process the request or response. -Therefore, if the application code in these listeners takes a long time to execute, the request or response processing is delayed until the listener returns. - -If you need to execute application code that takes long time inside a listener, you must spawn your own thread. - -Request and response processing are executed by two different threads and therefore may happen concurrently. -A typical example of this concurrent processing is an echo server, where a large upload may be concurrent with the large download echoed back. - -NOTE: Remember that responses may be processed and completed _before_ requests; a typical example is a large upload that triggers a quick response, for example an error, by the server: the response may arrive and be completed while the request content is still being uploaded. - -The application thread that calls `Request.send(Response.CompleteListener)` performs the xref:pg-client-http-request-processing[processing of the request] until either the request is fully sent over the network or until it would block on I/O, then it returns (and therefore never blocks). -If it would block on I/O, the thread asks the I/O system to emit an event when the I/O will be ready to continue, then returns. -When such an event is fired, a thread taken from the `HttpClient` thread pool will resume the processing of the request. - -Response are processed from the I/O thread taken from the `HttpClient` thread pool that processes the event that bytes are ready to be read. -Response processing continues until either the response is fully processed or until it would block for I/O. -If it would block for I/O, the thread asks the I/O system to emit an event when the I/O will be ready to continue, then returns. -When such an event is fired, a (possibly different) thread taken from the `HttpClient` thread pool will resume the processing of the response. - -When the request and the response are both fully processed, the thread that finished the last processing (usually the thread that processes the response, but may also be the thread that processes the request -- if the request takes more time than the response to be processed) is used to dequeue the next request for the same destination and to process it. - -A simple non-blocking `GET` request that discards the response content can be written in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=simpleNonBlocking] ----- - -Method `Request.send(Response.CompleteListener)` returns `void` and does not block; the `Response.CompleteListener` lambda provided as a parameter is notified when the request/response conversation is complete, and the `Result` parameter allows you to access the request and response objects as well as failures, if any. - -You can impose a total timeout for the request/response conversation in the same way used by the synchronous API: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=nonBlockingTotalTimeout] ----- - -The example above will impose a total timeout of 3 seconds on the request/response conversation. - -The HTTP client APIs use listeners extensively to provide hooks for all possible request and response events: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=listeners] ----- - -This makes Jetty HTTP client suitable for HTTP load testing because, for example, you can accurately time every step of the request/response conversation (thus knowing where the request/response time is really spent). - -Have a look at the link:{javadoc-url}/org/eclipse/jetty/client/api/Request.Listener.html[`Request.Listener`] class to know about request events, and to the link:{javadoc-url}/org/eclipse/jetty/client/api/Response.Listener.html[`Response.Listener`] class to know about response events. - -[[pg-client-http-content-request]] -===== Request Content Handling - -Jetty's `HttpClient` provides a number of utility classes off the shelf to handle request content. - -You can provide request content as `String`, `byte[]`, `ByteBuffer`, `java.nio.file.Path`, `InputStream`, and provide your own implementation of `org.eclipse.jetty.client.api.Request.Content`. -Here’s an example that provides the request content using `java.nio.file.Paths`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=pathRequestContent] ----- - -Alternatively, you can use `FileInputStream` via the `InputStreamRequestContent` utility class: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=inputStreamRequestContent] ----- - -Since `InputStream` is blocking, then also the send of the request will block if the input stream blocks, even in case of usage of the non-blocking `HttpClient` APIs. - -If you have already read the content in memory, you can pass it as a `byte[]` (or a `String`) using the `BytesRequestContent` (or `StringRequestContent`) utility class: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=bytesStringRequestContent] ----- - -If the request content is not immediately available, but your application will be notified of the content to send, you can use `AsyncRequestContent` in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=asyncRequestContent] ----- - -While the request content is awaited and consequently uploaded by the client application, the server may be able to respond (at least with the response headers) completely asynchronously. -In this case, `Response.Listener` callbacks will be invoked before the request is fully sent. -This allows fine-grained control of the request/response conversation: for example the server may reject contents that are too big, send a response to the client, which in turn may stop the content upload. - -Another way to provide request content is by using an `OutputStreamRequestContent`, which allows applications to write request content when it is available to the `OutputStream` provided by `OutputStreamRequestContent`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=outputStreamRequestContent] ----- - -[[pg-client-http-content-response]] -===== Response Content Handling - -Jetty's `HttpClient` allows applications to handle response content in different ways. - -You can buffer the response content in memory; this is done when using the xref:pg-client-http-blocking[blocking APIs] and the content is buffered within a `ContentResponse` up to 2 MiB. - -If you want to control the length of the response content (for example limiting to values smaller than the default of 2 MiB), then you can use a `org.eclipse.jetty.client.util.FutureResponseListener` in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=futureResponseListener] ----- - -If the response content length is exceeded, the response will be aborted, and an exception will be thrown by method `get(...)`. - -You can buffer the response content in memory also using the xref:pg-client-http-non-blocking[non-blocking APIs], via the `BufferingResponseListener` utility class: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=bufferingResponseListener] ----- - -If you want to avoid buffering, you can wait for the response and then stream the content using the `InputStreamResponseListener` utility class: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=inputStreamResponseListener] ----- - -Finally, let's look at the advanced usage of the response content handling. - -The response content is provided by the `HttpClient` implementation to application listeners following a reactive model similar to that of `java.util.concurrent.Flow`. - -The listener that follows this model is `Response.DemandedContentListener`. - -After the response headers have been processed by the `HttpClient` implementation, `Response.DemandedContentListener.onBeforeContent(response, demand)` is invoked. -This allows the application to control whether to demand the first content or not. -The default implementation of this method calls `demand.accept(1)`, which demands one chunk of content to the implementation. -The implementation will deliver the chunk of content as soon as it is available. - -The chunks of content are delivered to the application by invoking `Response.DemandedContentListener.onContent(response, demand, buffer, callback)`. -Applications implement this method to process the content bytes in the `buffer`. -Succeeding the `callback` signals to the implementation that the application has consumed the `buffer` so that the implementation can dispose/recycle the `buffer`. -Failing the `callback` signals to the implementation to fail the response (no more content will be delivered, and the _response failed_ event will be emitted). - -IMPORTANT: Succeeding the `callback` must be done only after the `buffer` bytes have been consumed. -When the `callback` is succeeded, the `HttpClient` implementation may reuse the `buffer` and overwrite the bytes with different bytes; if the application looks at the `buffer` _after_ having succeeded the `callback` is may see other, unrelated, bytes. - -The application uses the `demand` object to demand more content chunks. -Applications will typically demand for just one more content via `demand.accept(1)`, but may decide to demand for more via `demand.accept(2)` or demand "infinitely" once via `demand.accept(Long.MAX_VALUE)`. -Applications that demand for more than 1 chunk of content must be prepared to receive all the content that they have demanded. - -Demanding for content and consuming the content are orthogonal activities. - -An application can demand "infinitely" and store aside the pairs `(buffer, callback)` to consume them later. -If not done carefully, this may lead to excessive memory consumption, since the ``buffer``s are not consumed. -Succeeding the ``callback``s will result in the ``buffer``s to be disposed/recycled and may be performed at any time. - -An application can also demand one chunk of content, consume it (by succeeding the associated `callback`) and then _not_ demand for more content until a later time. - -Subclass `Response.AsyncContentListener` overrides the behavior of `Response.DemandedContentListener`; when an application implementing its `onContent(response, buffer, callback)` succeeds the `callback`, it will have _both_ the effect of disposing/recycling the `buffer` _and_ the effect of demanding one more chunk of content. - -Subclass `Response.ContentListener` overrides the behavior of `Response.AsyncContentListener`; when an application implementing its `onContent(response, buffer)` returns from the method itself, it will _both_ the effect of disposing/recycling the `buffer` _and_ the effect of demanding one more chunk of content. - -Previous examples of response content handling were inefficient because they involved copying the `buffer` bytes, either to accumulate them aside so that the application could use them when the request was completed, or because they were provided to an API such as `InputStream` that made use of `byte[]` (and therefore a copy from `ByteBuffer` to `byte[]` is necessary). - -An application that implements a forwarder between two servers can be implemented efficiently by handling the response content without copying the `buffer` bytes as in the following example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=demandedContentListener] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-authentication.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-authentication.adoc deleted file mode 100644 index 31697ccad658..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-authentication.adoc +++ /dev/null @@ -1,80 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http-authentication]] -==== HttpClient Authentication Support - -Jetty's `HttpClient` supports the `BASIC` and `DIGEST` authentication mechanisms defined by link:https://tools.ietf.org/html/rfc7235[RFC 7235], as well as the SPNEGO authentication mechanism defined in link:https://tools.ietf.org/html/rfc4559[RFC 4559]. - -The HTTP _conversation_, the sequence of related HTTP requests, for a request that needs authentication is the following: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant Application -participant HttpClient -participant Server - -Application -> Server : GET /path -Server -> HttpClient : 401 + WWW-Authenticate -HttpClient -> Server : GET + Authentication -Server -> Application : 200 OK ----- - -Upon receiving a HTTP 401 response code, `HttpClient` looks at the `WWW-Authenticate` response header (the server _challenge_) and then tries to match configured authentication credentials to produce an `Authentication` header that contains the authentication credentials to access the resource. - -You can configure authentication credentials in the `HttpClient` instance as follows: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=addAuthentication] ----- - -``Authentication``s are matched against the server challenge first by mechanism (e.g. `BASIC` or `DIGEST`), then by realm and then by URI. - -If an `Authentication` match is found, the application does not receive events related to the HTTP 401 response. -These events are handled internally by `HttpClient` which produces another (internal) request similar to the original request but with an additional `Authorization` header. - -If the authentication is successful, the server responds with a HTTP 200 and `HttpClient` caches the `Authentication.Result` so that subsequent requests for a matching URI will not incur in the additional rountrip caused by the HTTP 401 response. - -It is possible to clear ``Authentication.Result``s in order to force authentication again: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=clearResults] ----- - -Authentication results may be preempted to avoid the additional roundtrip due to the server challenge in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=preemptedResult] ----- - -In this way, requests for the given URI are enriched immediately with the `Authorization` header, and the server should respond with HTTP 200 (and the resource content) rather than with the 401 and the challenge. - -It is also possible to preempt the authentication for a single request only, in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=requestPreemptedResult] ----- - -See also the xref:pg-client-http-proxy-authentication[proxy authentication section] for further information about how authentication works with HTTP proxies. - -[[pg-client-http-authentication-spnego]] -===== HttpClient SPNEGO Authentication Support -TODO diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-configuration.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-configuration.adoc deleted file mode 100644 index 62e47d66c1ad..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-configuration.adoc +++ /dev/null @@ -1,77 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http-configuration]] -==== HttpClient Configuration - -`HttpClient` has a quite large number of configuration parameters. -Please refer to the `HttpClient` link:{javadoc-url}/org/eclipse/jetty/client/HttpClient.html[javadocs] for the complete list of configurable parameters. - -The most common parameters are: - -* `HttpClient.idleTimeout`: same as `ClientConnector.idleTimeout` described in xref:pg-client-io-arch-network[this section]. -* `HttpClient.connectBlocking`: same as `ClientConnector.connectBlocking` described in xref:pg-client-io-arch-network[this section]. -* `HttpClient.connectTimeout`: same as `ClientConnector.connectTimeout` described in xref:pg-client-io-arch-network[this section]. -* `HttpClient.maxConnectionsPerDestination`: the max number of TCP connections that are opened for a particular destination (defaults to 64). -* `HttpClient.maxRequestsQueuedPerDestination`: the max number of requests queued (defaults to 1024). - -[[pg-client-http-configuration-tls]] -===== HttpClient TLS Configuration - -`HttpClient` supports HTTPS requests out-of-the-box like a browser does. - -The support for HTTPS request is provided by a `SslContextFactory.Client` instance, typically configured in the `ClientConnector`. -If not explicitly configured, the `ClientConnector` will allocate a default one when started. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=tlsExplicit] ----- - -The default `SslContextFactory.Client` verifies the certificate sent by the server by verifying the validity of the certificate with respect to the certificate chain, the expiration date, the server host name, etc. -This means that requests to public websites that have a valid certificate (such as `+https://google.com+`) will work out-of-the-box, without the need to specify a KeyStore or a TrustStore. - -However, requests made to sites that return an invalid or a self-signed certificate will fail (like they will in a browser). -An invalid certificate may be expired or have the wrong server host name; a self-signed certificate has a certificate chain that cannot be verified. - -The validation of the server host name present in the certificate is important, to guarantee that the client is connected indeed with the intended server. - -The validation of the server host name is performed at two levels: at the TLS level (in the JDK) and, optionally, at the application level. - -By default, the validation of the server host name at the TLS level is enabled, while it is disabled at the application level. - -You can configure the `SslContextFactory.Client` to skip the validation of the server host name at the TLS level: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=tlsNoValidation] ----- - -When you disable the validation of the server host name at the TLS level, you are strongly recommended to enable it at the application level, otherwise you may risk to connect to a server different from the one you intend to connect to: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=tlsAppValidation] ----- - -You may have the validation of the server host name enabled at both the TLS level and application level, typically when you want to further restrict the client to connect only to a smaller set of server hosts than those allowed in the certificate sent by the server. - -Please refer to the `SslContextFactory.Client` link:{javadoc-url}/org/eclipse/jetty/util/ssl/SslContextFactory.Client.html[javadocs] for the complete list of configurable parameters. - -[[pg-client-http-configuration-tls-truststore]] -====== HttpClient TLS TrustStore Configuration -TODO - -[[pg-client-http-configuration-tls-client-certs]] -====== HttpClient TLS Client Certificates Configuration -TODO diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-cookie.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-cookie.adoc deleted file mode 100644 index 979753e53396..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-cookie.adoc +++ /dev/null @@ -1,100 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http-cookie]] -==== HttpClient Cookie Support - -Jetty's `HttpClient` supports cookies out of the box. - -The `HttpClient` instance receives cookies from HTTP responses and stores them in a `java.net.CookieStore`, a class that is part of the JDK. -When new requests are made, the cookie store is consulted and if there are matching cookies (that is, cookies that are not expired and that match domain and path of the request) then they are added to the requests. - -Applications can programmatically access the cookie store to find the cookies that have been set: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=getCookies] ----- - -Applications can also programmatically set cookies as if they were returned from a HTTP response: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=setCookie] ----- - -Cookies may be added explicitly only for a particular request: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=requestCookie] ----- - -You can remove cookies that you do not want to be sent in future HTTP requests: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=removeCookie] ----- - -If you want to totally disable cookie handling, you can install a `HttpCookieStore.Empty`. -This must be done when `HttpClient` is used in a proxy application, in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=emptyCookieStore] ----- - -You can enable cookie filtering by installing a cookie store that performs the filtering logic in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=filteringCookieStore] ----- - -The example above will retain only cookies that come from the `google.com` domain or sub-domains. - -// TODO: move this section to server-side -===== Special Characters in Cookies - -Jetty is compliant with link:https://tools.ietf.org/html/rfc6265[RFC6265], and as such care must be taken when setting a cookie value that includes special characters such as `;`. - -Previously, `Version=1` cookies defined in link:https://tools.ietf.org/html/rfc2109[RFC2109] (and continued in link:https://tools.ietf.org/html/rfc2965[RFC2965]) allowed for special/reserved characters to be enclosed within double quotes when declared in a `Set-Cookie` response header: - -[source,screen] ----- -Set-Cookie: foo="bar;baz";Version=1;Path="/secur" ----- - -This was added to the HTTP Response as follows: - -[source,java] ----- -protected void service(HttpServletRequest request, HttpServletResponse response) -{ - javax.servlet.http.Cookie cookie = new Cookie("foo", "bar;baz"); - cookie.setPath("/secure"); - response.addCookie(cookie); -} ----- - -The introduction of RFC6265 has rendered this approach no longer possible; users are now required to encode cookie values that use these special characters. -This can be done utilizing `javax.servlet.http.Cookie` as follows: - -[source,java] ----- -javax.servlet.http.Cookie cookie = new Cookie("foo", URLEncoder.encode("bar;baz", "UTF-8")); ----- - -Jetty validates all cookie names and values being added to the `HttpServletResponse` via the `addCookie(Cookie)` method. -If an illegal value is discovered Jetty will throw an `IllegalArgumentException` with the details. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-intro.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-intro.adoc deleted file mode 100644 index 6a86e7e5c324..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-intro.adoc +++ /dev/null @@ -1,208 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http-intro]] -==== HttpClient Introduction - -The Jetty HTTP client module provides easy-to-use APIs and utility classes to perform HTTP (or HTTPS) requests. - -Jetty's HTTP client is non-blocking and asynchronous. -It offers an asynchronous API that never blocks for I/O, making it very efficient in thread utilization and well suited for high performance scenarios such as load testing or parallel computation. - -However, when all you need to do is to perform a `GET` request to a resource, Jetty's HTTP client offers also a synchronous API; a programming interface where the thread that issued the request blocks until the request/response conversation is complete. - -Jetty's HTTP client supports different xref:pg-client-http-transport[transports protocols]: HTTP/1.1, HTTP/2, HTTP/3 and FastCGI. This means that the semantic of an HTTP request such as: " ``GET`` the resource ``/index.html`` " can be carried over the network in different formats. -The most common and default format is HTTP/1.1. That said, Jetty's HTTP client can carry the same request using the HTTP/2 format, the HTTP/3 format, or the FastCGI format. - -Furthermore, every transport protocol can be sent either over the network or via Unix-Domain sockets. -Supports for Unix-Domain sockets requires Java 16 or later, since Unix-Domain sockets support has been introduced in OpenJDK with link:https://openjdk.java.net/jeps/380[JEP 380]. - -The xref:pg-client-http-transport-fcgi[FastCGI transport] is heavily used in Jetty's xref:pg-server-fastcgi[FastCGI support] that allows Jetty to work as a reverse proxy to PHP (exactly like Apache or Nginx do) and therefore be able to serve, for example, WordPress websites, often in conjunction with Unix-Domain sockets (although it's possible to use FastCGI via network too). - -The HTTP/2 transport allows Jetty's HTTP client to perform requests using HTTP/2 to HTTP/2 enabled web sites, see also Jetty's xref:pg-client-http2[HTTP/2 support]. - -The HTTP/3 transport allows Jetty's HTTP client to perform requests using HTTP/3 to HTTP/3 enabled web sites, see also Jetty's xref:pg-client-http3[HTTP/3 support]. - -Out of the box features that you get with the Jetty HTTP client include: - -* Redirect support -- redirect codes such as 302 or 303 are automatically followed. -* Cookies support -- cookies sent by servers are stored and sent back to servers in matching requests. -* Authentication support -- HTTP "Basic", "Digest" and "SPNEGO" authentications are supported, others are pluggable. -* Forward proxy support -- HTTP proxying and SOCKS4 proxying. - -[[pg-client-http-start]] -==== Starting HttpClient - -The Jetty artifact that provides the main HTTP client implementation is `jetty-client`. -The Maven artifact coordinates are the following: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty - jetty-client - {version} - ----- - -The main class is named `org.eclipse.jetty.client.HttpClient`. - -You can think of a `HttpClient` instance as a browser instance. -Like a browser it can make requests to different domains, it manages redirects, cookies and authentication, you can configure it with a proxy, and it provides you with the responses to the requests you make. - -In order to use `HttpClient`, you must instantiate it, configure it, and then start it: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=start] ----- - -You may create multiple instances of `HttpClient`, but typically one instance is enough for an application. -There are several reasons for having multiple `HttpClient` instances including, but not limited to: - -* You want to specify different configuration parameters (for example, one instance is configured with a forward proxy while another is not). -* You want the two instances to behave like two different browsers and hence have different cookies, different authentication credentials, etc. -* You want to use xref:pg-client-http-transport[different transports]. - -Like browsers, HTTPS requests are supported out-of-the-box (see xref:pg-client-http-configuration-tls[this section] for the TLS configuration), as long as the server provides a valid certificate. -In case the server does not provide a valid certificate (or in case it is self-signed) you want to customize ``HttpClient``'s TLS configuration as described in xref:pg-client-http-configuration-tls[this section]. - -[[pg-client-http-stop]] -==== Stopping HttpClient - -It is recommended that when your application stops, you also stop the `HttpClient` instance (or instances) that you are using. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=stop] ----- - -Stopping `HttpClient` makes sure that the memory it holds (for example, authentication credentials, cookies, etc.) is released, and that the thread pool and scheduler are properly stopped allowing all threads used by `HttpClient` to exit. - -[NOTE] -==== -You cannot call `HttpClient.stop()` from one of its own threads, as it would cause a deadlock. -It is recommended that you stop `HttpClient` from an unrelated thread, or from a newly allocated thread, for example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=stopFromOtherThread] ----- -==== - -[[pg-client-http-arch]] -==== HttpClient Architecture - -A `HttpClient` instance can be thought as a browser instance, and it manages the following components: - -* a `CookieStore` (see xref:pg-client-http-cookie[this section]). -* a `AuthenticationStore` (see xref:pg-client-http-authentication[this section]). -* a `ProxyConfiguration` (see xref:pg-client-http-proxy[this section]). -* a set of _destinations_. - -A _destination_ is the client-side component that represents an _origin_ server, and manages a queue of requests for that origin, and a xref:pg-client-http-connection-pool[pool of TCP connections] to that origin. - -An _origin_ may be simply thought as the tuple `(scheme, host, port)` and it is where the client connects to in order to communicate with the server. -However, this is not enough. - -If you use `HttpClient` to write a proxy you may have different clients that want to contact the same server. -In this case, you may not want to use the same proxy-to-server connection to proxy requests for both clients, for example for authentication reasons: the server may associate the connection with authentication credentials and you do not want to use the same connection for two different users that have different credentials. -Instead, you want to use different connections for different clients and this can be achieved by "tagging" a destination with a tag object that represents the remote client (for example, it could be the remote client IP address). - -Two origins with the same `(scheme, host, port)` but different `tag` create two different destinations and therefore two different connection pools. -However, also this is not enough. - -It is possible for a server to speak different protocols on the same `port`. -A connection may start by speaking one protocol, for example HTTP/1.1, but then be upgraded to speak a different protocol, for example HTTP/2. After a connection has been upgraded to a second protocol, it cannot speak the first protocol anymore, so it can only be used to communicate using the second protocol. - -Two origins with the same `(scheme, host, port)` but different `protocol` create two different destinations and therefore two different connection pools. - -Therefore an origin is identified by the tuple `(scheme, host, port, tag, protocol)`. - -[[pg-client-http-connection-pool]] -==== HttpClient Connection Pooling - -A destination manages a `org.eclipse.jetty.client.ConnectionPool`, where connections to a particular origin are pooled for performance reasons: -opening a connection is a costly operation and it's better to reuse them for multiple requests. - -NOTE: Remember that to select a specific destination you must select a specific origin, and that an origin is identified by the tuple `(scheme, host, port, tag, protocol)`, so you can have multiple destinations for the same `host` and `port`. - -You can access the `ConnectionPool` in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=getConnectionPool] ----- - -Jetty's client library provides the following `ConnectionPool` implementations: - -* `DuplexConnectionPool`, historically the first implementation, only used by the HTTP/1.1 transport. -* `MultiplexConnectionPool`, the generic implementation valid for any transport where connections are reused with a MRU (most recently used) algorithm (that is, the connections most recently returned to the connection pool are the more likely to be used again). -* `RoundRobinConnectionPool`, similar to `MultiplexConnectionPool` but where connections are reused with a round-robin algorithm. - -The `ConnectionPool` implementation can be customized for each destination in by setting a `ConnectionPool.Factory` on the `HttpClientTransport`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tags=setConnectionPool] ----- - -[[pg-client-http-request-processing]] -==== HttpClient Request Processing - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant Application -participant Request -participant HttpClient -participant Destination -participant ConnectionPool -participant Connection - -Application -> HttpClient : newRequest() -HttpClient -> Request ** -Application -> Request : send() -Request -> HttpClient : send() -HttpClient -> Destination ** : get or create -Destination -> ConnectionPool ** : create -HttpClient -> Destination : send(Request) -Destination -> Destination : enqueue(Request) -Destination -> ConnectionPool : acquire() -ConnectionPool -> Connection ** : create -Destination -> Destination : dequeue(Request) -Destination -> Connection : send(Request) ----- - -When a request is sent, an origin is computed from the request; `HttpClient` uses that origin to find (or create if it does not exist) the correspondent destination. -The request is then queued onto the destination, and this causes the destination to ask its connection pool for a free connection. -If a connection is available, it is returned, otherwise a new connection is created. -Once the destination has obtained the connection, it dequeues the request and sends it over the connection. - -The first request to a destination triggers the opening of the first connection. -A second request with the same origin sent _after_ the first request/response cycle is completed may reuse the same connection, depending on the connection pool implementation. -A second request with the same origin sent _concurrently_ with the first request will likely cause the opening of a second connection, depending on the connection pool implementation. -The configuration parameter `HttpClient.maxConnectionsPerDestination` (see also the xref:pg-client-http-configuration[configuration section]) controls the max number of connections that can be opened for a destination. - -NOTE: If opening connections to a given origin takes a long time, then requests for that origin will queue up in the corresponding destination until the connections are established. - -Each connection can handle a limited number of concurrent requests. -For HTTP/1.1, this number is always `1`: there can only be one outstanding request for each connection. -For HTTP/2 this number is determined by the server `max_concurrent_stream` setting (typically around `100`, i.e. there can be up to `100` outstanding requests for every connection). - -When a destination has maxed out its number of connections, and all connections have maxed out their number of outstanding requests, more requests sent to that destination will be queued. -When the request queue is full, the request will be failed. -The configuration parameter `HttpClient.maxRequestsQueuedPerDestination` (see also the xref:pg-client-http-configuration[configuration section]) controls the max number of requests that can be queued for a destination. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-proxy.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-proxy.adoc deleted file mode 100644 index 45d1e360fa24..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-proxy.adoc +++ /dev/null @@ -1,92 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http-proxy]] -==== HttpClient Proxy Support - -Jetty's `HttpClient` can be configured to use proxies to connect to destinations. - -These types of proxies are available out of the box: - -* HTTP proxy (provided by class `org.eclipse.jetty.client.HttpProxy`) -* SOCKS 4 proxy (provided by class `org.eclipse.jetty.client.Socks4Proxy`) -* xref:pg-client-http-proxy-socks5[SOCKS 5 proxy] (provided by class `org.eclipse.jetty.client.Socks5Proxy`) - -Other implementations may be written by subclassing `ProxyConfiguration.Proxy`. - -The following is a typical configuration: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=proxy] ----- - -You specify the proxy host and proxy port, and optionally also the addresses that you do not want to be proxied, and then add the proxy configuration on the `ProxyConfiguration` instance. - -Configured in this way, `HttpClient` makes requests to the HTTP proxy (for plain-text HTTP requests) or establishes a tunnel via HTTP `CONNECT` (for encrypted HTTPS requests). - -Proxying is supported for any version of the HTTP protocol. - -[[pg-client-http-proxy-socks5]] -===== SOCKS5 Proxy Support - -SOCKS 5 (defined in link:https://datatracker.ietf.org/doc/html/rfc1928[RFC 1928]) offers choices for authentication methods and supports IPv6 (things that SOCKS 4 does not support). - -A typical SOCKS 5 proxy configuration with the username/password authentication method is the following: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=proxySocks5] ----- - -[[pg-client-http-proxy-authentication]] -===== HTTP Proxy Authentication Support - -Jetty's `HttpClient` supports HTTP proxy authentication in the same way it supports xref:pg-client-http-authentication[server authentication]. - -In the example below, the HTTP proxy requires `BASIC` authentication, but the server requires `DIGEST` authentication, and therefore: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=proxyAuthentication] ----- - -The HTTP conversation for successful authentications on both the proxy and the server is the following: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant Application -participant HttpClient -participant Proxy -participant Server - -Application -> Proxy : GET /path -Proxy -> HttpClient : 407 + Proxy-Authenticate -HttpClient -> Proxy : GET /path + Proxy-Authorization -Proxy -> Server : GET /path -Server -> Proxy : 401 + WWW-Authenticate -Proxy -> HttpClient : 401 + WWW-Authenticate -HttpClient -> Proxy : GET /path + Proxy-Authorization + Authorization -Proxy -> Server : GET /path + Authorization -Server -> Proxy : 200 OK -Proxy -> HttpClient : 200 OK -HttpClient -> Application : 200 OK ----- - -The application does not receive events related to the responses with code 407 and 401 since they are handled internally by `HttpClient`. - -Similarly to the xref:pg-client-http-authentication[authentication section], the proxy authentication result and the server authentication result can be preempted to avoid, respectively, the 407 and 401 roundtrips. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-transport.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-transport.adoc deleted file mode 100644 index 778c0438267f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http-transport.adoc +++ /dev/null @@ -1,204 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http-transport]] -==== HttpClient Pluggable Transports - -Jetty's `HttpClient` can be configured to use different transport protocols to carry the semantic of HTTP requests and responses. - -This means that the intention of a client to request resource `/index.html` using the `GET` method can be carried over the network in different formats. - -An `HttpClient` transport is the component that is in charge of converting a high-level, semantic, HTTP requests such as " ``GET`` resource ``/index.html`` " into the specific format understood by the server (for example, HTTP/2 or HTTP/3), and to convert the server response from the specific format (HTTP/2 or HTTP/3) into high-level, semantic objects that can be used by applications. - -The most common protocol format is HTTP/1.1, a textual protocol with lines separated by `\r\n`: - -[source,screen] ----- -GET /index.html HTTP/1.1\r\n -Host: domain.com\r\n -... -\r\n ----- - -However, the same request can be made using FastCGI, a binary protocol: - -[source,screen] ----- -x01 x01 x00 x01 x00 x08 x00 x00 -x00 x01 x01 x00 x00 x00 x00 x00 -x01 x04 x00 x01 xLL xLL x00 x00 -x0C x0B D O C U M E - N T _ U R I / i - n d e x . h t m - l -... ----- - -Similarly, HTTP/2 is a binary protocol that transports the same information in a yet different format via TCP, while HTTP/3 is a binary protocol that transports the same information in yet another format via UDP. - -A protocol may be _negotiated_ between client and server. -A request for a resource may be sent using one protocol (for example, HTTP/1.1), but the response may arrive in a different protocol (for example, HTTP/2). - -`HttpClient` supports these static transports, each speaking only one protocol: - -* xref:pg-client-http-transport-http11[HTTP/1.1] (both clear-text and TLS encrypted) -* xref:pg-client-http-transport-http2[HTTP/2] (both clear-text and TLS encrypted) -* xref:pg-client-http-transport-http3[HTTP/3] (only encrypted via QUIC+TLS) -* xref:pg-client-http-transport-fcgi[FastCGI] (both clear-text and TLS encrypted) - -`HttpClient` also supports one xref:pg-client-http-transport-dynamic[dynamic transport], that can speak different protocols and can select the right protocol by negotiating it with the server or by explicit indication from applications. - -Furthermore, every transport protocol can be sent either over the network or via Unix-Domain sockets. -Supports for Unix-Domain sockets requires Java 16 or later, since Unix-Domain sockets support has been introduced in OpenJDK with link:https://openjdk.java.net/jeps/380[JEP 380]. - -Applications are typically not aware of the actual protocol being used. -This allows them to write their logic against a high-level API that hides the details of the specific protocol being used over the network. - -[[pg-client-http-transport-http11]] -===== HTTP/1.1 Transport - -HTTP/1.1 is the default transport. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=defaultTransport] ----- - -If you want to customize the HTTP/1.1 transport, you can explicitly configure it in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=http11Transport] ----- - -[[pg-client-http-transport-http2]] -===== HTTP/2 Transport - -The HTTP/2 transport can be configured in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=http2Transport] ----- - -`HTTP2Client` is the lower-level client that provides an API based on HTTP/2 concepts such as _sessions_, _streams_ and _frames_ that are specific to HTTP/2. See xref:pg-client-http2[the HTTP/2 client section] for more information. - -`HttpClientTransportOverHTTP2` uses `HTTP2Client` to format high-level semantic HTTP requests (like "GET resource /index.html") into the HTTP/2 specific format. - -[[pg-client-http-transport-http3]] -===== HTTP/3 Transport - -The HTTP/3 transport can be configured in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=http3Transport] ----- - -`HTTP3Client` is the lower-level client that provides an API based on HTTP/3 concepts such as _sessions_, _streams_ and _frames_ that are specific to HTTP/3. See xref:pg-client-http3[the HTTP/3 client section] for more information. - -`HttpClientTransportOverHTTP3` uses `HTTP3Client` to format high-level semantic HTTP requests (like "GET resource /index.html") into the HTTP/3 specific format. - -[[pg-client-http-transport-fcgi]] -===== FastCGI Transport - -The FastCGI transport can be configured in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=fcgiTransport] ----- - -In order to make requests using the FastCGI transport, you need to have a FastCGI server such as link:https://en.wikipedia.org/wiki/PHP#PHPFPM[PHP-FPM] (see also link:http://php.net/manual/en/install.fpm.php). - -The FastCGI transport is primarily used by Jetty's xref:pg-server-fastcgi[FastCGI support] to serve PHP pages (WordPress for example). - -[[pg-client-http-transport-dynamic]] -===== Dynamic Transport - -The static transports work well if you know in advance the protocol you want to speak with the server, or if the server only supports one protocol (such as FastCGI). - -With the advent of HTTP/2 and HTTP/3, however, servers are now able to support multiple protocols, at least both HTTP/1.1 and HTTP/2. - -The HTTP/2 protocol is typically negotiated between client and server. -This negotiation can happen via ALPN, a TLS extension that allows the client to tell the server the list of protocol that the client supports, so that the server can pick one of the client supported protocols that also the server supports; or via HTTP/1.1 upgrade by means of the `Upgrade` header. - -Applications can configure the dynamic transport with one or more _application_ protocols such as HTTP/1.1 or HTTP/2. The implementation will take care of using TLS for HTTPS URIs, using ALPN if necessary, negotiating protocols, upgrading from one protocol to another, etc. - -By default, the dynamic transport only speaks HTTP/1.1: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=dynamicDefault] ----- - -The dynamic transport can be configured with just one protocol, making it equivalent to the corresponding static transport: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=dynamicOneProtocol] ----- - -The dynamic transport, however, has been implemented to support multiple transports, in particular both HTTP/1.1 and HTTP/2: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=dynamicH1H2] ----- - -NOTE: The order in which the protocols are specified to `HttpClientTransportDynamic` indicates what is the client preference. - -IMPORTANT: When using TLS (i.e. URIs with the `https` scheme), the application protocol is _negotiated_ between client and server via ALPN, and it is the server that decides what is the application protocol to use for the communication, regardless of the client preference. - -When clear-text communication is used (i.e. URIs with the `http` scheme) there is no application protocol negotiation, and therefore the application must know _a priori_ whether the server supports the protocol or not. -For example, if the server only supports clear-text HTTP/2, and `HttpClientTransportDynamic` is configured as in the example above, the client will send, by default, a clear-text HTTP/1.1 request to a clear-text HTTP/2 only server, which will result in a communication failure. - -Provided that the server supports both HTTP/1.1 and HTTP/2 clear-text, client applications can explicitly hint the version they want to use: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=dynamicClearText] ----- - -In case of TLS encrypted communication using the `https` scheme, things are a little more complicated. - -If the client application explicitly specifies the HTTP version, then ALPN is not used by the client. -By specifying the HTTP version explicitly, the client application has prior-knowledge of what HTTP version the server supports, and therefore ALPN is not needed. -If the server does not support the HTTP version chosen by the client, then the communication will fail. - -If the client application does not explicitly specify the HTTP version, then ALPN will be used by the client. -If the server also supports ALPN, then the protocol will be negotiated via ALPN and the server will choose the protocol to use. -If the server does not support ALPN, the client will try to use the first protocol configured in `HttpClientTransportDynamic`, and the communication may succeed or fail depending on whether the server supports the protocol chosen by the client. - -[[pg-client-http-transport-unix-domain]] -===== Unix-Domain Configuration - -All the transports can be configured with a `ClientConnector`, the component that is responsible for the transmission of the bytes generated by the transport to the server. - -By default, `ClientConnector` uses TCP networking to send bytes to the server and receive bytes from the server. - -When you are using Java 16 or later, `ClientConnector` also support xref:pg-client-io-arch-unix-domain[Unix-Domain sockets], and every transport can be configured to use Unix-Domain sockets instead of TCP networking. - -To configure Unix-Domain sockets, you can create a `ClientConnector` instance in the following way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java[tag=unixDomain] ----- - -[IMPORTANT] -==== -You can use Unix-Domain sockets support only when you run your client application with Java 16 or later. -==== - -You can configure a Jetty server to use Unix-Domain sockets, as explained in xref:pg-server-http-connector[this section]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http.adoc deleted file mode 100644 index a193a3ba52dd..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http/client-http.adoc +++ /dev/null @@ -1,24 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http]] -=== HTTP Client - -include::client-http-intro.adoc[] -include::client-http-api.adoc[] -include::client-http-configuration.adoc[] -include::client-http-cookie.adoc[] -include::client-http-authentication.adoc[] -include::client-http-proxy.adoc[] -include::client-http-transport.adoc[] - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http2/client-http2.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http2/client-http2.adoc deleted file mode 100644 index bd3ad9186816..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http2/client-http2.adoc +++ /dev/null @@ -1,181 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http2]] -=== HTTP/2 Client Library - -In the vast majority of cases, client applications should use the generic, high-level, xref:pg-client-http[HTTP client library] that also provides HTTP/2 support via the pluggable xref:pg-client-http-transport-http2[HTTP/2 transport] or the xref:pg-client-http-transport-dynamic[dynamic transport]. - -The high-level HTTP library supports cookies, authentication, redirection, connection pooling and a number of other features that are absent in the low-level HTTP/2 library. - -The HTTP/2 client library has been designed for those applications that need low-level access to HTTP/2 features such as _sessions_, _streams_ and _frames_, and this is quite a rare use case. - -See also the correspondent xref:pg-server-http2[HTTP/2 server library]. - -[[pg-client-http2-intro]] -==== Introducing HTTP2Client - -The Maven artifact coordinates for the HTTP/2 client library are the following: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.http2 - http2-client - {version} - ----- - -The main class is named `org.eclipse.jetty.http2.client.HTTP2Client`, and must be created, configured and started before use: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=start] ----- - -When your application stops, or otherwise does not need `HTTP2Client` anymore, it should stop the `HTTP2Client` instance (or instances) that were started: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=stop] ----- - -`HTTP2Client` allows client applications to connect to an HTTP/2 server. -A _session_ represents a single TCP connection to an HTTP/2 server and is defined by class `org.eclipse.jetty.http2.api.Session`. -A _session_ typically has a long life -- once the TCP connection is established, it remains open until it is not used anymore (and therefore it is closed by the idle timeout mechanism), until a fatal error occurs (for example, a network failure), or if one of the peers decides unilaterally to close the TCP connection. - -include::../../http2.adoc[tag=multiplex] - -[[pg-client-http2-flow-control]] -==== HTTP/2 Flow Control - -include::../../http2.adoc[tag=flowControl] - -How a client application should handle HTTP/2 flow control is discussed in details in xref:pg-client-http2-response[this section]. - -[[pg-client-http2-connect]] -==== Connecting to the Server - -The first thing an application should do is to connect to the server and obtain a `Session`. -The following example connects to the server on a clear-text port: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=clearTextConnect] ----- - -The following example connects to the server on an encrypted port: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=encryptedConnect] ----- - -IMPORTANT: Applications must know in advance whether they want to connect to a clear-text or encrypted port, and pass the `SslContextFactory` parameter accordingly to the `connect(...)` method. - -[[pg-client-http2-configure]] -==== Configuring the Session - -The `connect(...)` method takes a `Session.Listener` parameter. -This listener's `onPreface(...)` method is invoked just before establishing the connection to the server to gather the client configuration to send to the server. -Client applications can override this method to change the default configuration: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=configure] ----- - -The `Session.Listener` is notified of session events originated by the server such as receiving a `SETTINGS` frame from the server, or the server closing the connection, or the client timing out the connection due to idleness. -Please refer to the `Session.Listener` link:{javadoc-url}/org/eclipse/jetty/http2/api/Session.Listener.html[javadocs] for the complete list of events. - -Once a `Session` has been established, the communication with the server happens by exchanging _frames_, as specified in the link:https://tools.ietf.org/html/rfc7540#section-4[HTTP/2 specification]. - -[[pg-client-http2-request]] -==== Sending a Request - -Sending an HTTP request to the server, and receiving a response, creates a _stream_ that encapsulates the exchange of HTTP/2 frames that compose the request and the response. - -In order to send an HTTP request to the server, the client must send a `HEADERS` frame. -`HEADERS` frames carry the request method, the request URI and the request headers. -Sending the `HEADERS` frame opens the `Stream`: - -[source,java,indent=0,subs=normal] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=newStream] ----- - -Note how `Session.newStream(...)` takes a `Stream.Listener` parameter. -This listener is notified of stream events originated by the server such as receiving `HEADERS` or `DATA` frames that are part of the response, discussed in more details in the xref:pg-client-http2-response[section below]. -Please refer to the `Stream.Listener` link:{javadoc-url}/org/eclipse/jetty/http2/api/Stream.Listener.html[javadocs] for the complete list of events. - -HTTP requests may have content, which is sent using the `Stream` APIs: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=newStreamWithData] ----- - -IMPORTANT: When sending two `DATA` frames consecutively, the second call to `Stream.data(...)` must be done only when the first is completed, or a `WritePendingException` will be thrown. -Use the `Callback` APIs or `CompletableFuture` APIs to ensure that the second `Stream.data(...)` call is performed when the first completed successfully. - -[[pg-client-http2-response]] -==== Receiving a Response - -Response events are delivered to the `Stream.Listener` passed to `Session.newStream(...)`. - -An HTTP response is typically composed of a `HEADERS` frame containing the HTTP status code and the response headers, and optionally one or more `DATA` frames containing the response content bytes. - -The HTTP/2 protocol also supports response trailers (that is, headers that are sent after the response content) that also are sent using a `HEADERS` frame. - -A client application can therefore receive the HTTP/2 frames sent by the server by implementing the relevant methods in `Stream.Listener`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=responseListener] ----- - -include::../../http2.adoc[tag=apiFlowControl] - -[[pg-client-http2-reset]] -==== Resetting a Request or Response - -In HTTP/2, clients and servers have the ability to tell to the other peer that they are not interested anymore in either the request or the response, using a `RST_STREAM` frame. - -The `HTTP2Client` APIs allow client applications to send and receive this "reset" frame: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=reset] ----- - -[[pg-client-http2-push]] -==== Receiving HTTP/2 Pushes - -HTTP/2 servers have the ability to push resources related to a primary resource. -When an HTTP/2 server pushes a resource, it sends to the client a `PUSH_PROMISE` frame that contains the request URI and headers that a client would use to request explicitly that resource. - -Client applications can be configured to tell the server to never push resources, see xref:pg-client-http2-configure[this section]. - -Client applications can listen to the push events, and act accordingly: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=push] ----- - -If a client application does not want to handle a particular HTTP/2 push, it can just reset the pushed stream to tell the server to stop sending bytes for the pushed stream: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java[tags=pushReset] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http3/client-http3.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http3/client-http3.adoc deleted file mode 100644 index b3773e30d1dd..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/http3/client-http3.adoc +++ /dev/null @@ -1,175 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-http3]] -=== HTTP/3 Client Library - -In the vast majority of cases, client applications should use the generic, high-level, xref:pg-client-http[HTTP client library] that also provides HTTP/3 support via the pluggable xref:pg-client-http-transport-http3[HTTP/3 transport] or the xref:pg-client-http-transport-dynamic[dynamic transport]. - -The high-level HTTP library supports cookies, authentication, redirection, connection pooling and a number of other features that are absent in the low-level HTTP/3 library. - -The HTTP/3 client library has been designed for those applications that need low-level access to HTTP/3 features such as _sessions_, _streams_ and _frames_, and this is quite a rare use case. - -See also the correspondent xref:pg-server-http3[HTTP/3 server library]. - -[[pg-client-http3-intro]] -==== Introducing HTTP3Client - -The Maven artifact coordinates for the HTTP/3 client library are the following: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.http3 - http3-client - {version} - ----- - -The main class is named `org.eclipse.jetty.http3.client.HTTP3Client`, and must be created, configured and started before use: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=start] ----- - -When your application stops, or otherwise does not need `HTTP3Client` anymore, it should stop the `HTTP3Client` instance (or instances) that were started: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=stop] ----- - -`HTTP3Client` allows client applications to connect to an HTTP/3 server. -A _session_ represents a single connection to an HTTP/3 server and is defined by class `org.eclipse.jetty.http3.api.Session`. -A _session_ typically has a long life -- once the connection is established, it remains active until it is not used anymore (and therefore it is closed by the idle timeout mechanism), until a fatal error occurs (for example, a network failure), or if one of the peers decides unilaterally to close the connection. - -include::../../http3.adoc[tag=multiplex] - -// TODO: flow control? -//[[pg-client-http3-flow-control]] -//==== HTTP/3 Flow Control - -//include::../../http3.adoc[tag=flowControl] - -//How a client application should handle HTTP/3 flow control is discussed in details in xref:pg-client-http3-response[this section]. - -[[pg-client-http3-connect]] -==== Connecting to the Server - -The first thing an application should do is to connect to the server and obtain a `Session`. -The following example connects to the server: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=connect] ----- - -[[pg-client-http3-configure]] -==== Configuring the Session - -The `connect(...)` method takes a `Session.Client.Listener` parameter. -This listener's `onPreface(...)` method is invoked just before establishing the connection to the server to gather the client configuration to send to the server. -Client applications can override this method to change the default configuration: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=configure] ----- - -The `Session.Client.Listener` is notified of session events originated by the server such as receiving a `SETTINGS` frame from the server, or the server closing the connection, or the client timing out the connection due to idleness. -Please refer to the `Session.Client.Listener` link:{javadoc-url}/org/eclipse/jetty/http3/api/Session.Client.Listener.html[javadocs] for the complete list of events. - -Once a `Session` has been established, the communication with the server happens by exchanging _frames_. - -[[pg-client-http3-request]] -==== Sending a Request - -Sending an HTTP request to the server, and receiving a response, creates a _stream_ that encapsulates the exchange of HTTP/3 frames that compose the request and the response. - -In order to send an HTTP request to the server, the client must send a `HEADERS` frame. -`HEADERS` frames carry the request method, the request URI and the request headers. -Sending the `HEADERS` frame opens the `Stream`: - -[source,java,indent=0,subs=normal] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=newStream] ----- - -Note how `Session.newRequest(...)` takes a `Stream.Client.Listener` parameter. -This listener is notified of stream events originated by the server such as receiving `HEADERS` or `DATA` frames that are part of the response, discussed in more details in the xref:pg-client-http3-response[section below]. -Please refer to the `Stream.Client.Listener` link:{javadoc-url}/org/eclipse/jetty/http3/api/Stream.Client.Listener.html[javadocs] for the complete list of events. - -HTTP requests may have content, which is sent using the `Stream` APIs: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=newStreamWithData] ----- - -IMPORTANT: When sending two `DATA` frames consecutively, the second call to `Stream.data(...)` must be done only when the first is completed, or a `WritePendingException` will be thrown. -Use the `CompletableFuture` APIs to ensure that the second `Stream.data(...)` call is performed when the first completed successfully. - -[[pg-client-http3-response]] -==== Receiving a Response - -Response events are delivered to the `Stream.Client.Listener` passed to `Session.newRequest(...)`. - -An HTTP response is typically composed of a `HEADERS` frame containing the HTTP status code and the response headers, and optionally one or more `DATA` frames containing the response content bytes. - -The HTTP/3 protocol also supports response trailers (that is, headers that are sent after the response content) that also are sent using a `HEADERS` frame. - -A client application can therefore receive the HTTP/3 frames sent by the server by implementing the relevant methods in `Stream.Client.Listener`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=responseListener] ----- - -// TODO: flow control? -//include::../../http3.adoc[tag=apiFlowControl] - -[[pg-client-http3-reset]] -==== Resetting a Request or Response - -In HTTP/3, clients and servers have the ability to tell to the other peer that they are not interested anymore in either the request or the response, by resetting the stream. - -The `HTTP3Client` APIs allow client applications to send and receive this "reset" event: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=reset] ----- - -// TODO: push not yet implemented in HTTP/3. -//[[pg-client-http3-push]] -//==== Receiving HTTP/3 Pushes -// -//HTTP/3 servers have the ability to push resources related to a primary resource. -//When an HTTP/3 server pushes a resource, it sends to the client a `PUSH_PROMISE` frame that contains the request URI and headers that a client would use to request explicitly that resource. -// -//Client applications can be configured to tell the server to never push resources, see xref:pg-client-http3-configure[this section]. -// -//Client applications can listen to the push events, and act accordingly: -// -//[source,java,indent=0] -//---- -//include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=push] -//---- -// -//If a client application does not want to handle a particular HTTP/3 push, it can just reset the pushed stream to tell the server to stop sending bytes for the pushed stream: -// -//[source,java,indent=0] -//---- -//include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java[tags=pushReset] -//---- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/websocket/client-websocket.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/websocket/client-websocket.adoc deleted file mode 100644 index 201c2590c075..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/client/websocket/client-websocket.adoc +++ /dev/null @@ -1,209 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-client-websocket]] -=== WebSocket Client - -Jetty's `WebSocketClient` is a more powerful alternative to the WebSocket client provided by the standard JSR 356 `javax.websocket` APIs. - -Similarly to Jetty's xref:pg-client-http[`HttpClient`], the `WebSocketClient` is non-blocking and asynchronous, making it very efficient in resource utilization. -A synchronous, blocking, API is also offered for simpler cases. - -Since the first step of establishing a WebSocket communication is an HTTP request, `WebSocketClient` makes use of `HttpClient` and therefore depends on it. - -The Maven artifact coordinates are the following: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.websocket - websocket-jetty-client - {version} - ----- - -[[pg-client-websocket-start]] -==== Starting WebSocketClient - -The main class is `org.eclipse.jetty.websocket.client.WebSocketClient`; you instantiate it, configure it, and then start it like may other Jetty components. -This is a minimal example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java[tags=start] ----- - -However, it is recommended that you explicitly pass an `HttpClient` instance to `WebSocketClient` so that you can have control over the HTTP configuration as well: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java[tags=startWithHttpClient] ----- - -You may create multiple instances of `WebSocketClient`, but typically one instance is enough for most applications. -Creating multiple instances may be necessary for example when you need to specify different configuration parameters for different instances. -For example, you may need different instances when you need to configure the `HttpClient` differently: different transports, different proxies, different cookie stores, different authentications, etc. - -The configuration that is not WebSocket specific (such as idle timeout, etc.) should be directly configured on the associated `HttpClient` instance. - -The WebSocket specific configuration can be configured directly on the `WebSocketClient` instance. -Configuring the `WebSocketClient` allows to give default values to various parameters, whose values may be overridden more specifically, as described in xref:pg-websocket-session-configure[this section]. - -Refer to the `WebSocketClient` link:{javadoc-url}/org/eclipse/jetty/websocket/client/WebSocketClient.html[javadocs] for the setter methods available to customize the WebSocket specific configuration. - -[[pg-client-websocket-stop]] -==== Stopping WebSocketClient - -It is recommended that when your application stops, you also stop the `WebSocketClient` instance (or instances) that you are using. - -Similarly to xref:pg-client-http-stop[stopping `HttpClient`], you want to stop `WebSocketClient` from a thread that is not owned by `WebSocketClient` itself, for example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java[tags=stop] ----- - -[[pg-client-websocket-connect]] -==== Connecting to a Remote Host - -A WebSocket client may initiate the communication with the server either xref:pg-client-websocket-connect-http11[using HTTP/1.1] or xref:pg-client-websocket-connect-http2[using HTTP/2]. -The two mechanism are quite different and detailed in the following sections. - -[[pg-client-websocket-connect-http11]] -===== Using HTTP/1.1 - -Initiating a WebSocket communication with a server using HTTP/1.1 is detailed in link:https://tools.ietf.org/html/rfc6455#section-1.8[RFC 6455]. - -A WebSocket client first establishes a TCP connection to the server, then sends an HTTP/1.1 _upgrade_ request. - -If the server supports upgrading to WebSocket, it responds with HTTP status code `101`, and then switches the communication over that connection, either incoming or outgoing, to happen using the WebSocket protocol. - -When the client receives the HTTP status code `101`, it switches the communication over that connection, either incoming or outgoing, to happen using the WebSocket protocol. - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant ClientEndPoint -participant WebSocketClient -participant HttpClient -participant Server -participant ServerEndPoint - -WebSocketClient -> HttpClient : connect() -HttpClient -> Server : TCP/TLS connect -HttpClient -> Server : GET / HTTP/1.1\nUpgrade: websocket -Server -> ServerEndPoint ** : create -Server -> HttpClient : HTTP/1.1 101\nUpgrade: websocket -HttpClient -> WebSocketClient -WebSocketClient -> ClientEndPoint ** : create -ClientEndPoint -> WebSocketClient : WebSocket Frame A -WebSocketClient -> Server : WebSocket Frame A -Server -> ServerEndPoint : WebSocket Frame A -ServerEndPoint -> Server : WebSocket Frame B -Server -> WebSocketClient : WebSocket Frame B -WebSocketClient -> ClientEndPoint : WebSocket Frame B ----- - -In code: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java[tags=connectHTTP11] ----- - -`WebSocketClient.connect()` links the client-side WebSocket _endpoint_ to a specific server URI, and returns a `CompletableFuture` of an `org.eclipse.jetty.websocket.api.Session`. - -The endpoint offers APIs to _receive_ WebSocket data (or errors) from the server, while the session offers APIs to _send_ WebSocket data to the server. - -[[pg-client-websocket-connect-http2]] -===== Using HTTP/2 - -Initiating a WebSocket communication with a server using HTTP/1.1 is detailed in link:https://tools.ietf.org/html/rfc8441[RFC 8441]. - -A WebSocket client establishes a TCP connection to the server or reuses an existing one currently used for HTTP/2, then sends an HTTP/2 _connect_ request over an HTTP/2 stream. - -If the server supports upgrading to WebSocket, it responds with HTTP status code `200`, then switches the communication over that stream, either incoming or outgoing, to happen using HTTP/2 `DATA` frames wrapping WebSocket frames. - -When the client receives the HTTP status code `200`, it switches the communication over that stream, either incoming or outgoing, to happen using HTTP/2 `DATA` frames wrapping WebSocket frames. - -From an external point of view, it will look like client is sending chunks of an infinite HTTP/2 request upload, and the server is sending chunks of an infinite HTTP/2 response download, as they will exchange HTTP/2 `DATA` frames; but the HTTP/2 `DATA` frames will contain each one or more WebSocket frames that both client and server know how to deliver to the respective WebSocket endpoints. - -When either WebSocket endpoint decides to terminate the communication, the HTTP/2 stream will be closed as well. - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant ClientEndPoint -participant WebSocketClient -participant HttpClient -participant Server -participant ServerEndPoint - -WebSocketClient -> HttpClient : connect() -HttpClient --> Server : TCP/TLS connect -HttpClient -> Server : HEADERS\n:method: CONNECT\n:protocol: websocket -Server -> ServerEndPoint ** : create -Server -> HttpClient : HEADERS\n:status: 200\n: websocket -HttpClient -> WebSocketClient -WebSocketClient -> ClientEndPoint ** : create -ClientEndPoint -> HttpClient : WebSocket Frame A -HttpClient -> Server : DATA\nWebSocket Frame A -Server -> ServerEndPoint : WebSocket Frame A -ServerEndPoint -> Server : WebSocket Frame B -Server -> HttpClient : DATA\nWebSocket Frame B -HttpClient -> ClientEndPoint : WebSocket Frame B ----- - -In code: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java[tags=connectHTTP2] ----- - -Alternatively, you can use the xref:pg-client-http-transport-dynamic[dynamic `HttpClient` transport]: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java[tags=connectHTTP2Dynamic] ----- - -[[pg-client-websocket-connect-custom-http-request]] -===== Customizing the Initial HTTP Request - -Sometimes you need to add custom cookies, or other HTTP headers, or specify a WebSocket sub-protocol to the HTTP request that initiates the WebSocket communication. - -You can do this by using overloaded versions of the `WebSocketClient.connect(...)` method: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java[tags=customHTTPRequest] ----- - -[[pg-client-websocket-connect-inspect-http-response]] -===== Inspecting the Initial HTTP Response - -If you want to inspect the HTTP response returned by the server as a reply to the HTTP request that initiates the WebSocket communication, you may provide a `JettyUpgradeListener`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java[tags=inspectHTTPResponse] ----- - -include::../../websocket.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/http2.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/http2.adoc deleted file mode 100644 index 3c8928cd1448..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/http2.adoc +++ /dev/null @@ -1,69 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -// Snippets of HTTP/2 documentation that are common between client and server. - -tag::multiplex[] -HTTP/2 is a multiplexed protocol: it allows multiple HTTP/2 requests to be sent on the same TCP connection, or _session_. -Each request/response cycle is represented by a _stream_. -Therefore, a single _session_ manages multiple concurrent _streams_. -A _stream_ has typically a very short life compared to the _session_: a _stream_ only exists for the duration of the request/response cycle and then disappears. -end::multiplex[] - -tag::flowControl[] -The HTTP/2 protocol is _flow controlled_ (see link:https://tools.ietf.org/html/rfc7540#section-5.2[the specification]). -This means that a sender and a receiver maintain a _flow control window_ that tracks the number of data bytes sent and received, respectively. -When a sender sends data bytes, it reduces its flow control window. -When a receiver receives data bytes, it also reduces its flow control window, and then passes the received data bytes to the application. -The application consumes the data bytes and tells back the receiver that it has consumed the data bytes. -The receiver then enlarges the flow control window, and arranges to send a message to the sender with the number of bytes consumed, so that the sender can enlarge its flow control window. - -A sender can send data bytes up to its whole flow control window, then it must stop sending until it receives a message from the receiver that the data bytes have been consumed, which enlarges the flow control window, which allows the sender to send more data bytes. - -HTTP/2 defines _two_ flow control windows: one for each _session_, and one for each _stream_. -Let's see with an example how they interact, assuming that in this example the session flow control window is 120 bytes and the stream flow control window is 100 bytes. - -The sender opens a session, and then opens `stream_1` on that session, and sends `80` data bytes. -At this point the session flow control window is `40` bytes (`120 - 80`), and ``stream_1``'s flow control window is `20` bytes (`100 - 80`). -The sender now opens `stream_2` on the same session and sends `40` data bytes. -At this point, the session flow control window is `0` bytes (`40 - 40`), while ``stream_2``'s flow control window is `60` (`100 - 40`). -Since now the session flow control window is `0`, the sender cannot send more data bytes, neither on `stream_1` nor on `stream_2` despite both have their stream flow control windows greater than `0`. - -The receiver consumes ``stream_2``'s `40` data bytes and sends a message to the sender with this information. -At this point, the session flow control window is `40` (`0 40`), ``stream_1``'s flow control window is still `20` and ``stream_2``'s flow control window is `100` (`60 40`). -If the sender opens `stream_3` and would like to send 50 data bytes, it would only be able to send `40` because that is the maximum allowed by the session flow control window at this point. - -It is therefore very important that applications notify the fact that they have consumed data bytes as soon as possible, so that the implementation (the receiver) can send a message to the sender (in the form of a `WINDOW_UPDATE` frame) with the information to enlarge the flow control window, therefore reducing the possibility that sender stalls due to the flow control windows being reduced to `0`. -end::flowControl[] - -tag::apiFlowControl[] -NOTE: Returning from the `onData(...)` method implicitly demands for more `DATA` frames (unless the one just delivered was the last). -Additional `DATA` frames may be delivered immediately if they are available or later, asynchronously, when they arrive. - -Applications that consume the content buffer within `onData(...)` (for example, writing it to a file, or copying the bytes to another storage) should succeed the callback as soon as they have consumed the content buffer. -This allows the implementation to reuse the buffer, reducing the memory requirements needed to handle the content buffers. - -Alternatively, a client application may store away _both_ the buffer and the callback to consume the buffer bytes later, or pass _both_ the buffer and the callback to another asynchronous API (this is typical in proxy applications). - -IMPORTANT: Completing the `Callback` is very important not only to allow the implementation to reuse the buffer, but also tells the implementation to enlarge the stream and session flow control windows so that the sender will be able to send more `DATA` frames without stalling. - -Applications can also precisely control _when_ to demand more `DATA` frames, by implementing the `onDataDemanded(...)` method instead of `onData(...)`: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/HTTP2Docs.java[tags=dataDemanded] ----- - -IMPORTANT: Applications that implement `onDataDemanded(...)` must remember to call `Stream.demand(...)`. -If they don't, the implementation will not deliver `DATA` frames and the application will stall threadlessly until an idle timeout fires to close the stream or the session. -end::apiFlowControl[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/http3.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/http3.adoc deleted file mode 100644 index 56823eba51d1..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/http3.adoc +++ /dev/null @@ -1,70 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -// Snippets of HTTP/3 documentation that are common between client and server. - -tag::multiplex[] -HTTP/3 is a multiplexed protocol because it relies on the multiplexing capabilities of QUIC, the protocol based on UDP that transports HTTP/3 frames. -Thanks to multiplexing, multiple HTTP/3 requests are sent on the same QUIC connection, or _session_. -Each request/response cycle is represented by a _stream_. -Therefore, a single _session_ manages multiple concurrent _streams_. -A _stream_ has typically a very short life compared to the _session_: a _stream_ only exists for the duration of the request/response cycle and then disappears. -end::multiplex[] - -//tag::flowControl[] -//The HTTP/3 protocol is _flow controlled_ (see link:https://tools.ietf.org/html/rfc7540#section-5.2[the specification]). -//This means that a sender and a receiver maintain a _flow control window_ that tracks the number of data bytes sent and received, respectively. -//When a sender sends data bytes, it reduces its flow control window. -//When a receiver receives data bytes, it also reduces its flow control window, and then passes the received data bytes to the application. -//The application consumes the data bytes and tells back the receiver that it has consumed the data bytes. -//The receiver then enlarges the flow control window, and arranges to send a message to the sender with the number of bytes consumed, so that the sender can enlarge its flow control window. -// -//A sender can send data bytes up to its whole flow control window, then it must stop sending until it receives a message from the receiver that the data bytes have been consumed, which enlarges the flow control window, which allows the sender to send more data bytes. -// -//HTTP/3 defines _two_ flow control windows: one for each _session_, and one for each _stream_. -//Let's see with an example how they interact, assuming that in this example the session flow control window is 120 bytes and the stream flow control window is 100 bytes. -// -//The sender opens a session, and then opens `stream_1` on that session, and sends `80` data bytes. -//At this point the session flow control window is `40` bytes (`120 - 80`), and ``stream_1``'s flow control window is `20` bytes (`100 - 80`). -//The sender now opens `stream_2` on the same session and sends `40` data bytes. -//At this point, the session flow control window is `0` bytes (`40 - 40`), while ``stream_2``'s flow control window is `60` (`100 - 40`). -//Since now the session flow control window is `0`, the sender cannot send more data bytes, neither on `stream_1` nor on `stream_2` despite both have their stream flow control windows greater than `0`. -// -//The receiver consumes ``stream_2``'s `40` data bytes and sends a message to the sender with this information. -//At this point, the session flow control window is `40` (`0 40`), ``stream_1``'s flow control window is still `20` and ``stream_2``'s flow control window is `100` (`60 40`). -//If the sender opens `stream_3` and would like to send 50 data bytes, it would only be able to send `40` because that is the maximum allowed by the session flow control window at this point. -// -//It is therefore very important that applications notify the fact that they have consumed data bytes as soon as possible, so that the implementation (the receiver) can send a message to the sender (in the form of a `WINDOW_UPDATE` frame) with the information to enlarge the flow control window, therefore reducing the possibility that sender stalls due to the flow control windows being reduced to `0`. -//end::flowControl[] -// -//tag::apiFlowControl[] -//NOTE: Returning from the `onData(...)` method implicitly demands for more `DATA` frames (unless the one just delivered was the last). -//Additional `DATA` frames may be delivered immediately if they are available or later, asynchronously, when they arrive. -// -//Applications that consume the content buffer within `onData(...)` (for example, writing it to a file, or copying the bytes to another storage) should succeed the callback as soon as they have consumed the content buffer. -//This allows the implementation to reuse the buffer, reducing the memory requirements needed to handle the content buffers. -// -//Alternatively, a client application may store away _both_ the buffer and the callback to consume the buffer bytes later, or pass _both_ the buffer and the callback to another asynchronous API (this is typical in proxy applications). -// -//IMPORTANT: Completing the `Callback` is very important not only to allow the implementation to reuse the buffer, but also tells the implementation to enlarge the stream and session flow control windows so that the sender will be able to send more `DATA` frames without stalling. -// -//Applications can also precisely control _when_ to demand more `DATA` frames, by implementing the `onDataDemanded(...)` method instead of `onData(...)`: -// -//[source,java,indent=0] -//---- -//include::{doc_code}/org/eclipse/jetty/docs/programming/HTTP3Docs.java[tags=dataDemanded] -//---- -// -//IMPORTANT: Applications that implement `onDataDemanded(...)` must remember to call `Stream.demand(...)`. -//If they don't, the implementation will not deliver `DATA` frames and the application will stall threadlessly until an idle timeout fires to close the stream or the session. -//end::apiFlowControl[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/index-docinfo.html b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/index-docinfo.html deleted file mode 100644 index 006245974c73..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/index-docinfo.html +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/index.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/index.adoc deleted file mode 100644 index d4bcb554eae6..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/index.adoc +++ /dev/null @@ -1,27 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -:doctitle: link:https://jetty.org[Eclipse Jetty]: Programming Guide -:toc-title: Jetty Programming Guide -:idprefix: pg- -:docinfo: private-head - -include::../config.adoc[] -include::.asciidoctorconfig[] -include::introduction.adoc[] -include::client/client.adoc[] -include::server/server.adoc[] -include::maven/maven.adoc[] -include::arch.adoc[] -include::troubleshooting.adoc[] -include::migration/migration.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/introduction.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/introduction.adoc deleted file mode 100644 index 4fa9822dfe7b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/introduction.adoc +++ /dev/null @@ -1,24 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -== Eclipse Jetty Programming Guide - -The Eclipse Jetty Programming Guide targets developers who want to use the Eclipse Jetty libraries in their applications. - -The Eclipse Jetty libraries provide the client-side and server-side APIs to work with various web protocols such as HTTP/1.1, HTTP/2, HTTP/3, WebSocket and FastCGI. - -You may use the xref:pg-client[Eclipse Jetty client-side library] in your application to make calls to third party REST services, or to other REST microservices in your system. - -Likewise, you may use the xref:pg-server[Eclipse Jetty server-side library] to quickly create an HTTP or REST service without having to create a web application archive file (a `+*.war+` file) and without having to deploy it a Jetty standalone server that you would have to download and install. - -This guide will walk you through the design of the Eclipse Jetty libraries and how to use its classes to write your applications. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-jspc-maven-plugin.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-jspc-maven-plugin.adoc deleted file mode 100644 index 2e94c065aed6..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-jspc-maven-plugin.adoc +++ /dev/null @@ -1,245 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-jspc-maven-plugin]] -=== Jetty Jspc Maven Plugin - -This plugin will help you pre-compile your jsps and works in conjunction with the Maven war plugin to put them inside an assembled war. - -[[jspc-config]] -==== Configuration - -Here's the basic setup required to put the jspc plugin into your build: - -[source,xml] ----- - - org.eclipse.jetty - jetty-jspc-maven-plugin - {VERSION} - - - jspc - - jspc - - - - - - ----- - -The configurable parameters are as follows: - -webXmlFragment:: -Default value: `$\{project.basedir}/target/webfrag.xml` -+ -File into which to generate the servlet declarations. -Will be merged with an existing `web.xml`. -webAppSourceDirectory:: -Default value: `$\{project.basedir}/src/main/webapp` -+ -Root of resources directory where jsps, tags etc are located. -webXml:: -Default value: `$\{project.basedir}/src/main/webapp/WEB-INF/web.xml` -+ -The web.xml file to use to merge with the generated fragments. -includes:: -Default value: `**\/*.jsp, **\/*.jspx` -+ -The comma separated list of patterns for file extensions to be processed. -excludes:: -Default value: `**\/.svn\/**` -+ -The comma separated list of patterns for file extensions to be skipped. -classesDirectory:: -Default value: `$\{project.build.outputDirectory}` -+ -Location of classes for the webapp. -generatedClasses:: -Default value: `$\{project.build.outputDirectory}` -+ -Location to put the generated classes for the jsps. -insertionMarker:: -Default value: _none_ -+ -A marker string in the src `web.xml` file which indicates where to merge in the generated web.xml fragment. -Note that the marker string will NOT be preserved during the insertion. -Can be left blank, in which case the generated fragment is inserted just before the line containing ``. -useProvidedScope:: -Default value: false -+ -If true, jars of dependencies marked with provided will be placed on the compilation classpath. -mergeFragment:: -Default value: true -+ -Whether or not to merge the generated fragment file with the source web.xml. -The merged file will go into the same directory as the webXmlFragment. -keepSources:: -Default value: false -+ -If true, the generated .java files are not deleted at the end of processing. -scanAllDirectories:: -Default value: true -+ -Determines if dirs on the classpath should be scanned as well as jars. -If true, this allows scanning for tlds of dependent projects that -are in the reactor as unassembled jars. -scanManifest:: -Default value: true -+ -Determines if the manifest of JAR files found on the classpath should be scanned. -sourceVersion:: -Introduced in Jetty 9.3.6. -Java version of jsp source files. -Defaults to 1.7. -targetVersion:: -Introduced in Jetty 9.3.6. -Java version of class files generated from jsps. -Defaults to 1.7. -tldJarNamePatterns:: -Default value: `.*taglibs[^/]*\.jar|.*jstl-impl[^/]*\.jar$` -+ -Patterns of jars on the 'system' (ie container) path that contain tlds. -Use | to separate each pattern. -jspc:: -Default value: the `org.apache.jasper.JspC` instance being configured. -+ -The JspC class actually performs the pre-compilation. -All setters on the JspC class are available. -You can download the javadoc https://repo1.maven.org/maven2/org/glassfish/web/javax.servlet.jsp/2.3.2/javax.servlet.jsp-2.3.2-javadoc.jar[here]. - -Taking all the default settings, here's how to configure the war plugin to use the generated `web.xml` that includes all of the jsp servlet declarations: - -[source,xml] ----- - - org.apache.maven.plugins - maven-war-plugin - - ${project.basedir}/target/web.xml - - ----- - -[[jspc-production-precompile]] -==== Precompiling only for Production Build - -As compiling jsps is usually done during preparation for a production release and not usually done during development, it is more convenient to put the plugin setup inside a which which can be deliberately invoked during prep for production. - -For example, the following profile will only be invoked if the flag `-Dprod` is present on the run line: - -[source,xml] ----- - - - prod - - prod - - - - - org.eclipse.jetty - jetty-jspc-maven-plugin - {VERSION} - - - - org.apache.maven.plugins - maven-war-plugin - - - - - - ----- - -The following invocation would cause your code to be compiled, the jsps to be compiled, the and s inserted in the `web.xml` and your webapp assembled into a war: - ----- -$ mvn -Dprod package ----- - -[[jspc-overlay-precompile]] -==== Precompiling Jsps with Overlaid Wars - -Precompiling jsps with an overlaid war requires a bit more configuration. -This is because you need to separate the steps of unpacking the overlaid war and then repacking the final target war so the jetty-jspc-maven-plugin has the opportunity to access the overlaid resources. - -In the example we'll show, we will use an overlaid war. -The overlaid war will provide the `web.xml` file but the jsps will be in `src/main/webapp` (i.e. part of the project that uses the overlay). -We will unpack the overlaid war file, compile the jsps and merge their servlet definitions into the extracted `web.xml`, then pack everything into a war. - -Here's an example configuration of the war plugin that separate those phases into an unpack phase, and then a packing phase: - -[source,xml] ----- - - maven-war-plugin - - - unpack - exploded - generate-resources - - target/foo - - - - org.eclipse.jetty.demos - demo-jetty-webapp - - - - - - pack - war - package - - target/foo - target/web.xml - - - - ----- - -Now you also need to configure the `jetty-jspc-maven-plugin` so that it can use the web.xml that was extracted by the war unpacking and merge in the generated definitions of the servlets. -This is in `target/foo/WEB-INF/web.xml`. -Using the default settings, the `web.xml` merged with the jsp servlet definitions will be put into `target/web.xml`. - -[source,xml] ----- - - org.eclipse.jetty - jetty-jspc-maven-plugin - {VERSION} - - - jspc - - jspc - - - target/foo/WEB-INF/web.xml - **/*.foo - **/*.fff - - - - ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-maven-helloworld.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-maven-helloworld.adoc deleted file mode 100644 index 9ff0e315c1ad..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-maven-helloworld.adoc +++ /dev/null @@ -1,309 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-maven-helloworld]] -=== Using Maven - -http://maven.apache.org/[Apache Maven] is a software project management and comprehension tool. -Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information. - -It is an ideal tool to build a web application project, and such projects can use the xref:jetty-maven-plugin[jetty-maven-plugin] to easily run the web application and save time in development. -You can also use Maven to build, test and run a project which embeds Jetty. - -[NOTE] -==== -Use of Maven and the jetty-maven-plugin is *not* required. -Using Maven for Jetty implementations is a popular choice, but users encouraged to manage their projects in whatever way suits their needs. -Other popular tools include Ant and Gradle. -==== - -First we'll have a look at a very simple HelloWorld java application that embeds Jetty, then a simple webapp which makes use of the xref:jetty-maven-plugin[jetty-maven-plugin] to speed up the development cycle. - -[[configuring-embedded-jetty-with-maven]] -==== Using Embedded Jetty with Maven - -Maven uses convention over configuration, so it is best to use the project structure Maven recommends. -You can use _xref:archetypes[http://maven.apache.org/guides/introduction/introduction-to-archetypes.html[archetypes]]_ to quickly setup Maven projects, but we will set up the structure manually for this simple tutorial example: - ----- -> mkdir JettyMavenHelloWorld -> cd JettyMavenHelloWorld -> mkdir -p src/main/java/org/example ----- - -[[creating-helloworld-class]] -===== Creating the HelloWorld Class - -Use an editor to create the file `src/main/java/org/example/HelloWorld.java` with the following contents: - -[source,java] ----- -package org.example; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.ServletException; -import java.io.IOException; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.handler.AbstractHandler; - -public class HelloWorld extends AbstractHandler -{ - public void handle(String target, - Request baseRequest, - HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException - { - response.setContentType("text/html;charset=utf-8"); - response.setStatus(HttpServletResponse.SC_OK); - baseRequest.setHandled(true); - response.getWriter().println("

Hello World

"); - } - - public static void main(String[] args) throws Exception - { - Server server = new Server(8080); - server.setHandler(new HelloWorld()); - - server.start(); - server.join(); - } -} ----- - -[[creating-embedded-pom-descriptor]] -===== Creating the POM Descriptor - -The `pom.xml` file declares the project name and its dependencies. -Use an editor to create the file `pom.xml` in the `JettyMavenHelloWorld` directory with the following contents: - -[source,xml] ----- - - - 4.0.0 - org.example - hello-world - 0.1-SNAPSHOT - jar - Jetty HelloWorld - - - - {VERSION} - - - - - org.eclipse.jetty - jetty-server - ${jettyVersion} - - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.1 - - java - - - org.example.HelloWorld - - - - - ----- - -[[buildng-and-running-embedded-helloworld]] -===== Building and Running Embedded HelloWorld - -You can now compile and execute the HelloWorld class by using these commands: - ----- -> mvn clean compile exec:java ----- - -You can point your browser to `http://localhost:8080` to see the _Hello World_ page. -You can observe what Maven is doing for you behind the scenes by using the `mvn dependency:tree` command, which reveals the transitive dependency resolved and downloaded as: - ----- -> mvn dependency:tree -[INFO] Scanning for projects... -... -[INFO] -[INFO] ------------------------------------------------------------------------ -[INFO] Building Jetty HelloWorld 0.1-SNAPSHOT -[INFO] ------------------------------------------------------------------------ -[INFO] -[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ hello-world --- -... -[INFO] org.example:hello-world:jar:0.1-SNAPSHOT -[INFO] \- org.eclipse.jetty:jetty-server:jar:9.3.9.v20160517:compile -[INFO] +- javax.servlet:javax.servlet-api:jar:3.1.0:compile -[INFO] +- org.eclipse.jetty:jetty-http:jar:9.3.9.v20160517:compile -[INFO] | \- org.eclipse.jetty:jetty-util:jar:9.3.9.v20160517:compile -[INFO] \- org.eclipse.jetty:jetty-io:jar:9.3.9.v20160517:compile -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 4.145 s -[INFO] Finished at: 2016-08-01T13:46:42-04:00 -[INFO] Final Memory: 15M/209M -[INFO] ------------------------------------------------------------------------ ----- - -[[developing-standard-webapp-with-jetty-and-maven]] -==== Developing a Standard WebApp with Jetty and Maven - -The previous section demonstrated how to use Maven with an application that embeds Jetty. -Now we will examine instead how to develop a standard webapp with Maven and Jetty. -First create the Maven structure (you can use the maven webapp archetype instead if you prefer): - ----- -> mkdir JettyMavenHelloWarApp -> cd JettyMavenHelloWebApp -> mkdir -p src/main/java/org/example -> mkdir -p src/main/webapp/WEB-INF ----- - -[[creating-servlet]] -===== Creating a Servlet - -Use an editor to create the file `src/main/java/org/example/HelloServlet.java` with the following contents: - -[source,java] ----- -package org.example; - -import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -public class HelloServlet extends HttpServlet -{ - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - response.setContentType("text/html"); - response.setStatus(HttpServletResponse.SC_OK); - response.getWriter().println("

Hello Servlet

"); - response.getWriter().println("session=" + request.getSession(true).getId()); - } -} ----- - -You need to declare this servlet in the deployment descriptor, so create the file `src/main/webapp/WEB-INF/web.xml` and add the following contents: - -[source,xml] ----- - - - - - Hello - org.example.HelloServlet - - - Hello - /hello/* - - - ----- - -[[creating-plugin-pom-descriptor]] -===== Creating the POM Descriptor - -The `pom.xml` file declares the project name and its dependencies. -Use an editor to create the file `pom.xml` with the following contents in the `JettyMavenHelloWarApp` directory, noting particularly the declaration of the xref:jetty-maven-plugin[jetty-maven-plugin]: - -[source,xml] ----- - - - 4.0.0 - org.example - hello-world - 0.1-SNAPSHOT - war - Jetty HelloWorld WebApp - - - {VERSION} - - - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - - - - - org.eclipse.jetty - jetty-maven-plugin - ${jettyVersion} - - - - - ----- - -[[building-and-running-web-application]] -===== Building and Running the Web Application - -Now you can both build and run the web application without needing to assemble it into a war by using the xref:jetty-maven-plugin[jetty-maven-plugin] via the command: - ----- -> mvn jetty:run ----- - -You can see the static and dynamic content at `http://localhost:8080/hello` - -There are a great deal of configuration options available for the jetty-maven-plugin to help you build and run your webapp. -The full reference is at xref:jetty-maven-plugin[Configuring the Jetty Maven Plugin]. - -[[building-war-file]] -===== Building a WAR file - -You can create a Web Application Archive (WAR) file from the project with the command: - ----- -> mvn package ----- - -The resulting war file is in the `target` directory and may be deployed on any standard servlet server, including xref:og-deploy[Jetty]. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-maven-plugin.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-maven-plugin.adoc deleted file mode 100644 index 6c9a12cea747..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/jetty-maven-plugin.adoc +++ /dev/null @@ -1,1174 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[jetty-maven-plugin]] -=== Using the Jetty Maven Plugin - -The Jetty Maven plugin is useful for rapid development and testing. -It can optionally periodically scan your project for changes and automatically redeploy the webapp if any are found. -This makes the development cycle more productive by eliminating the build and deploy steps: you use your IDE to make changes to the project, and the running web container automatically picks them up, allowing you to test them straight away. - -The plugin has been substantially re-architected in jetty-10 to: - -* have less goals -* make deployment modes (embedded, forked or to a jetty distribution) apply uniformly across all goals -* simplify configuration options -* make the purpose and operation of each goal clearer -* rearchitect with composition rather than inheritance to make future extensions easier - -There are now only 4 goals to run a webapp in jetty: - -* xref:jetty-run-goal[jetty:run] -* xref:jetty-run-war-goal[jetty:run-war] -* xref:jetty-start-goal[jetty:start] -* xref:jetty-start-war-goal[jetty:start-war] - -Plus two utility goals: - -* xref:jetty-stop-goal[jetty:stop] -* xref:jetty-effective-web-xml-goal[jetty:effective-web-xml] - -`jetty:run` and `jetty:start` are alike in that they both run an unassembled webapp in jetty,however `jetty:run` is designed to be used at the command line, whereas `jetty:start` is specifically designed to be bound to execution phases in the build lifecycle. -`jetty:run` will pause maven while jetty is running, echoing all output to the console, and then stop maven when jetty exits. -`jetty:start` will not pause maven, will write all its output to a file, and will not stop maven when jetty exits. - -`jetty:run-war` and `jetty:start-war` are similar in that they both run an _assembled_ war file in jetty. -However, `jetty:run-war` is designed to be run at the command line, whereas `jetty:start-war` is specifically designed to be bound to execution phases in the build lifecycle. -`jetty:run-war` will pause maven while jetty is running, echoing all output to the console, and then stop maven when jetty exits. -`jetty:start-war` will not not pause maven, will write all its output to a file, and will not stop maven when jetty exits. - -[IMPORTANT] -==== -While the Jetty Maven Plugin can be very useful for development we do not recommend its use in a _production capacity_. -In order for the plugin to work it needs to leverage many internal Maven apis and Maven itself it not a production deployment tool. -We recommend either the traditional xrefr:og-deploy[distribution] deployment approach or using xref:og-arch[embedded Jetty]. -==== - -[[get-up-and-running]] -==== Get Up and Running - -First, add `jetty-maven-plugin` to your `pom.xml` definition: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - {VERSION} - ----- - -Then, from the same directory as your root `pom.xml`, type: - ----- -mvn jetty:run ----- - -This starts Jetty and serves up your project on http://localhost:8080/. - -Jetty will continue to run until you stop it. -By default, it will not automatically restart your webapp. -Set a non-zero `` value to have jetty scan your webapp for changes and automatically redeploy, or set `` to `0` to cause manual redeployment by hitting the kbd:[Enter] key. - -You can terminate the plugin with a kbd:[Ctrl+c] in the terminal window where it is running. - -[NOTE] -==== -The classpath of the running Jetty instance and its deployed webapp are managed by Maven, and may not be exactly what you expect. -For example: a webapp's dependent jars might be referenced via the local repository, or other projects in the reactor, not the `WEB-INF/lib` directory. -==== - -[[supported-goals]] -==== Supported Goals - -The goals prefixed with `"run"` are designed to be used at the _command line_. -They first run a maven build on your project to ensure at least the classes are all built. -They then start jetty and pause the maven build process until jetty is manually terminated, at which time the build will also be terminated. -Jetty can scan various files in your project for changes and redeploy the webapp as necessary, or you can choose to manually trigger a redeploy if you prefer. -All output from jetty is echoed to the console. - -The goals prefixed with `"start"` are designed to be used with _build lifecycle bindings in the pom_, and _not_ at the command line. -No part of your project will be rebuilt by invoking these goals - you should ensure that your bind the execution to a build phase where all necessary parts of your project have been built. -Maven will start and terminate jetty at the appropriate points in the build lifecycle, continuing with the build. -Jetty will _not_ scan any files in your project for changes, and your webapp will _not_ be redeployed either automatically or manually. -Output from jetty is directed to a file in the `target` directory. - -To see a list of all goals supported by the Jetty Maven plugin, do: - ----- -mvn jetty:help ----- - -To see the detailed list of parameters that can be configured for a particular goal, in addition to its description, do: - ----- -mvn jetty:help -Ddetail=true -Dgoal= ----- - -[[deployment-modes]] -==== Deployment Modes -All of the `"run"` and `"start"` goals can deploy your webapp either into the running maven process, or forked into a new child process, or forked into a jetty distribution on disk. - -This is controlled by setting the `deployMode` configuration parameter in the pom, but can also be set by defining the maven property 'jetty.deployMode'. - -===== Embedded - -`deployMode` of `EMBED`. -This is the "classic" jetty maven plugin deployment mode, running in-process with maven. -This is the _default_ mode. - -These extra configuration parameters are available: - -httpConnector:: -Optional. -Note that to configure a https connector, you will need to use xml configuration files instead, setting the `jettyXmls` parameter. -This parameter can only be used to configure a standard http connector. -If not specified, Jetty will create a link:{javadoc-url}/org/eclipse/jetty/server/ServerConnector.html[ServerConnector] instance listening on port 8080. -You can change this default port number by using the system property `jetty.http.port` on the command line, for example, `mvn -Djetty.http.port=9999 jetty:run`. -Alternatively, you can use this configuration element to set up the information for the ServerConnector. -The following are the valid configuration sub-elements: -port::: -The port number for the connector to listen on. -By default it is 8080. -host::: -The particular interface for the connector to listen on. -By default, all interfaces. -name::: -The name of the connector, which is useful for configuring contexts to respond only on particular connectors. -idleTimeout::: -Maximum idle time for a connection. -You could instead configure the connectors in a standard xref:og-xml[jetty xml config file] and put its location into the `jettyXml` parameter. -Note that since Jetty 9.0 it is no longer possible to configure a https connector directly in the pom.xml: you need to use jetty xml config files to do it. -loginServices:: -Optional. -A list of `org.eclipse.jetty.security.LoginService` implementations. Note that there is no default realm. -If you use a realm in your `web.xml` you can specify a corresponding realm here. -You could instead configure the login services in a jetty xml file and add its location to the `jettyXml` parameter. -See xref:configuring-security-settings[Configuring Security]. -requestLog:: -Optional. -An implementation of the `org.eclipse.jetty.server.RequestLog` request log interface. -An implementation that respects the NCSA format is available as `org.eclipse.jetty.server.NCSARequestLog`. -There are three other ways to configure the RequestLog: -+ - * In a jetty xml config file, as specified in the `jettyXml` parameter. - * In a context xml config file, as specified in the `contextXml` parameter. - * In the `webApp` element. -+ -See xref:pg-server-http-request-logging[Configuring Request Logs] for more information. -server:: -Optional as of Jetty 9.3.1. -This would configure an instance of `org.eclipse.jetty.server.Server` for the plugin to use, however it is usually _not_ necessary to configure this, as the plugin will automatically configure one for you. -In particular, if you use the `jettyXmls` element, then you generally _don't_ want to define this element, as you are probably using the `jettyXmls` file/s to configure up a Server with a special constructor argument, such as a custom threadpool. -If you define both a `server` element and use a `jettyXmls` element which points to a config file that has a line like `` then the the xml configuration will override what you configure for the `server` in the `pom.xml`. -useProvidedScope:: -Default value is `false`. -If true, the dependencies with `provided` are placed onto the __container classpath__. -Be aware that this is _not_ the webapp classpath, as `provided` indicates that these dependencies would normally be expected to be provided by the container. -You should very rarely ever need to use this. -See xref:container-classpath[Container Classpath vs WebApp Classpath]. - -===== Forked - -`deployMode` of `FORK`. -This is similar to the old "jetty:run-forked" goal - a separate process is forked to run your webapp embedded into jetty. -These extra configuration parameters are available: - -env:: -Optional. -Map of key/value pairs to pass as environment to the forked JVM. -jvmArgs:: -Optional. -A space separated string representing arbitrary arguments to pass to the forked JVM. -forkWebXml:: -Optional. -Defaults to `target/fork-web.xml`. -This is the location of a quickstart web xml file that will be _generated_ during the forking of the jetty process. -You should not need to set this parameter, but it is available if you wish to control the name and location of that file. -useProvidedScope:: -Default value is `false`. -If true, the dependencies with `provided` are placed onto the __container classpath__. -Be aware that this is NOT the webapp classpath, as "provided" indicates that these dependencies would normally be expected to be provided by the container. -You should very rarely ever need to use this. -See xref:container-classpath[Container Classpath vs WebApp Classpath]. - -===== In a jetty distribution - -`deployMode` of `EXTERNAL`. -This is similar to the old "jetty:run-distro" goal - your webapp is deployed into a dynamically downloaded, unpacked and configured jetty distribution. -A separate process is forked to run it. -These extra configuration parameters are available: - -jettyBase:: -Optional. -The location of an existing jetty base directory to use to deploy the webapp. -The existing base will be copied to the `target/` directory before the webapp is deployed. -If there is no existing jetty base, a fresh one will be made in `target/jetty-base`. -jettyHome:: -Optional. -The location of an existing unpacked jetty distribution. -If one does not exist, a fresh jetty distribution will be downloaded from maven and installed to the `target` directory. -jettyOptions:: -Optional. -A space separated string representing extra arguments to the synthesized jetty command line. -Values for these arguments can be found in the section titled "Options" in the output of `java -jar $jetty.home/start.jar --help`. -jvmArgs:: -Optional. -A space separated string representing arguments that should be passed to the jvm of the child process running the distro. -modules:: -Optional. -An array of names of additional jetty modules that the jetty child process will activate. -Use this to change the xref:container-classpath[container classpath] instead of `useProvidedScope`. -These modules are enabled by default: `server,http,webapp,deploy`. - - -[[common-configuration]] -==== Common Configuration - -The following configuration parameters are common to all of the `"run-"` and `"start-"` goals: - -deployMode:: -One of `EMBED`, `FORK` or `EXTERNAL`. -Default `EMBED`. -Can also be configured by setting the Maven property `jetty.deployMode`. -This parameter determines whether the webapp will run in jetty in-process with Maven, forked into a new process, or deployed into a jetty distribution. -See xref:deployment-modes[Deployment Modes]. -jettyXmls:: -Optional. -A comma separated list of locations of jetty xml files to apply in addition to any plugin configuration parameters. -You might use it if you have other webapps, handlers, specific types of connectors etc., to deploy, or if you have other Jetty objects that you cannot configure from the plugin. -skip:: -Default is false. -If true, the execution of the plugin exits. -Same as setting the SystemProperty `-Djetty.skip` on the command line. -This is most useful when configuring Jetty for execution during integration testing and you want to skip the tests. -excludedGoals:: -Optional. -A list of Jetty plugin goal names that will cause the plugin to print an informative message and exit. -Useful if you want to prevent users from executing goals that you know cannot work with your project. -supportedPackagings:: -Optional. -Defaults to `war`. -This is a list of maven <packaging> types that can work with the jetty plugin. -Usually, only `war` projects are suitable, however, you may configure other types. -The plugin will refuse to start if the <packaging> type in the pom is not in list of `supportedPackagings`. -systemProperties:: -Optional. -Allows you to configure System properties for the execution of the plugin. -For more information, see xref:setting-system-properties[Setting System Properties]. -systemPropertiesFile:: -Optional. -A file containing System properties to set for the execution of the plugin. -By default, settings that you make here *do not* override any system properties already set on the command line, by the JVM, or in the POM via `systemProperties`. -Read xref:setting-system-properties[Setting System Properties] for how to force overrides. -jettyProperties:: -Optional. -A map of property name, value pairs. -Allows you to configure standard jetty properties. - -[[container-classpath]] -==== Container Classpath vs WebApp Classpath - -The Servlet Specification makes a strong distinction between the classpath for a webapp, and the classpath of the container. -When running in maven, the plugin's classpath is equivalent to the container classpath. -It will make a classpath for the webapp to be deployed comprised of <dependencies> specified in the pom. - -If your production environment places specific jars onto the container's classpath, the equivalent way to do this with maven is to define these as <dependencies> for the _plugin_ itself, not the _project_. See http://maven.apache.org/pom.html#Plugins[configuring maven plugins]. -This is suitable if you are using either `EMBED` or `FORK` mode. -If you are using `EXTERNAL` mode, then you should configure the `modules` parameter with the names of the jetty modules that place these jars onto the container classpath. - -Note that in `EMBED` or `FORK` mode, you could also influence the container classpath by setting the `useProvidedScope` parameter to `true`: this will place any dependencies with <scope>provided<scope> onto the plugin's classpath. -Use this very cautiously: as the plugin already automatically places most jetty jars onto the classpath, you could wind up with duplicate jars. - - -[[jetty-run-goal]] -==== jetty:run - -The `run` goal deploys a webapp that is _not_ first built into a WAR. -A virtual webapp is constructed from the project's sources and its dependencies. -It looks for the constituent parts of a webapp in the maven default project locations, although you can override these in the plugin configuration. -For example, by default it looks for: - -* resources in `${project.basedir}/src/main/webapp` -* classes in `${project.build.outputDirectory}` -* `web.xml` in `${project.basedir}/src/main/webapp/WEB-INF/` - -The plugin first runs a maven parallel build to ensure that the classes are built and up-to-date before deployment. -If you change the source of a class and your IDE automatically compiles it in the background, the plugin picks up the changed class (note you need to configure a non-zero `scan` interval for automatic redeployment). - -If the plugin is invoked in a multi-module build, any dependencies that are also in the maven reactor are used from their compiled classes. -Prior to jetty-9.4.7 any dependencies needed to be built first. - -Once invoked, you can configure the plugin to run continuously, scanning for changes in the project and automatically performing a hot redeploy when necessary. -Any changes you make are immediately reflected in the running instance of Jetty, letting you quickly jump from coding to testing, rather than going through the cycle of: code, compile, reassemble, redeploy, test. - -The maven build will be paused until jetty exits, at which time maven will also exit. - -Stopping jetty is accomplished by typing `cntrl-c` at the command line. - -Output from jetty will be logged to the console. - -Here is an example, which turns on scanning for changes every ten seconds, and sets the webapp context path to `/test`: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - {VERSION} - - 10 - - /test - - - ----- - -===== Configuration - -webApp:: -This is an instance of link:{javadoc-url}/org/eclipse/jetty/maven/plugin/MavenWebAppContext.html[org.eclipse.jetty.maven.plugin.MavenWebAppContext], which is an extension to the class link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.hml[`org.eclipse.jetty.webapp.WebAppContext`]. -You can use any of the setter methods on this object to configure your webapp. -Here are a few of the most useful ones: -+ -contextPath;; -The context path for your webapp. By default, this is set to `/`. -If using a custom value for this parameter, you should include the leading `/`, example `/mycontext`. -descriptor;; -The path to the `web.xml` file for your webapp. -By default, the plugin will look in `src/main/webapp/WEB-INF/web.xml`. -defaultsDescriptor;; -The path to a `webdefault.xml` file that will be applied to your webapp before the `web.xml`. -If you don't supply one, Jetty uses a default file baked into the `jetty-webapp.jar`. -overrideDescriptor;; -The path to a `web.xml` file that Jetty applies after reading your `web.xml`. -You can use this to replace or add configuration. -jettyEnvXml;; -Optional. -Location of a `jetty-env.xml` file, which allows you to make JNDI bindings that satisfy `env-entry`, `resource-env-ref`, and `resource-ref` linkages in the `web.xml` that are scoped only to the webapp and not shared with other webapps that you might be deploying at the same time (for example, by using a `jettyXml` file). -tempDirectory;; -The path to a dir that Jetty can use to expand or copy jars and jsp compiles when your webapp is running. -The default is `${project.build.outputDirectory}/tmp`. -baseResource;; -The path from which Jetty serves static resources. -Defaults to `src/main/webapp`. -If this location does not exist (because, for example, your project does not use static content), then the plugin will synthesize a virtual static resource location of `target/webapp-synth`. -resourceBases;; -Use instead of `baseResource` if you have multiple directories from which you want to serve static content. -This is an array of directory locations, either as urls or file paths. -baseAppFirst;; -Defaults to "true". -Controls whether any overlaid wars are added before or after the original base resource(s) of the webapp. -See the section on xref:using-overlaid-wars[overlaid wars] for more information. -containerIncludeJarPattern;; -Defaults to `.*/jetty-servlet-api-[^/]*\.jar$|.*javax.servlet.jsp.jstl-[^/]*\.jar|.*taglibs-standard-impl-.*\.jar`. -This is a pattern that is applied to the names of the jars on the container's classpath (ie the classpath of the plugin, not that of the webapp) that should be scanned for fragments, tlds, annotations etc. -This is analogous to the context attribute xref:og-container-include-jar-pattern[org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern] that is documented xref:og-container-include-jar-pattern[here]. -You can define extra patterns of jars that will be included in the scan. -webInfIncludeJarPattern;; -Defaults to matching _all_ of the dependency jars for the webapp (ie the equivalent of WEB-INF/lib). -You can make this pattern more restrictive to only match certain jars by using this setter. -This is analogous to the context attribute xref:og-web-inf-include-jar-pattern[org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern] that is documented xref:og-web-inf-include-jar-pattern[here]. -contextXml:: -The path to a context xml file that is applied to your webapp AFTER the `webApp` element. -classesDirectory:: -Location of your compiled classes for the webapp. -You should rarely need to set this parameter. -Instead, you should set `` in your `pom.xml`. -testClassesDirectory:: -Location of the compiled test classes for your webapp. By default this is `${project.build.testOutputDirectory}`. -useTestScope:: -If true, the classes from `testClassesDirectory` and dependencies of scope "test" are placed first on the classpath. -By default this is false. -scan:: -The pause in seconds between sweeps of the webapp to check for changes and automatically hot redeploy if any are detected. -*By default this is `-1`, which disables hot redeployment scanning.* -A value of `0` means no hot redeployment is done, and that you must use the kbd:[Enter] key to manually force a redeploy. -Any positive integer will enable hot redeployment, using the number as the sweep interval in seconds. -scanTargetPatterns:: -Optional. -List of extra directories with glob-style include/excludes patterns (see http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String-[javadoc] for http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String-[FileSystem.getPathMatcher]) to specify other files to periodically scan for changes. -scanClassesPattern:: -Optional. -Include and exclude patterns that can be applied to the classesDirectory for the purposes of scanning, it does *not* affect the classpath. -If a file or directory is excluded by the patterns then a change in that file (or subtree in the case of a directory) is ignored and will not cause the webapp to redeploy. -Patterns are specified as a relative path using a glob-like syntax as described in the http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String-[javadoc] for http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String-[FileSystem.getPathMatcher]. -scanTestClassesPattern:: -Optional. -Include and exclude patterns that can be applied to the testClassesDirectory for the purposes of scanning, it does *not* affect the classpath. -If a file or directory is excluded by the patterns then a change in that file (or subtree in the case of a directory) is ignored and will not cause the webapp to redeploy. -Patterns are specified as a relative path using a glob-like syntax as described in the http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String-[javadoc] for http://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String-[FileSystem.getPathMatcher]. - -See xref:deployment-modes[Deployment Modes] for other configuration parameters available when using the `run` goal in EMBED, FORK or EXTERNAL modes. - -Here's an example of a pom configuration for the plugin with the `run` goal: - -[source,xml] ----- - -... - -... - - org.eclipse.jetty - jetty-maven-plugin - {VERSION} - - - / - ${project.basedir}/src/over/here/web.xml - ${project.basedir}/src/over/here/jetty-env.xml - ${project.basedir}/src/staticfiles - - ${project.basedir}/somewhere/else - - - **/Foo.class - - - - - src/other-resources - - **/*.xml - **/*.properties - - - **/myspecial.xml - **/myspecial.properties - - - - - - -... - ----- - -If, for whatever reason, you cannot run on an unassembled webapp, the goal `run-war` works on assembled webapps. - -[[jetty-run-war-goal]] -==== jetty:run-war - -When invoked at the command line this goal first executes a maven build of your project to the package phase. - -By default it then deploys the resultant war to jetty, but you can use this goal instead to deploy _any_ war file by simply setting the `<webApp><war>` configuration parameter to its location. - -If you set a non-zero `scan`, Jetty watches your `pom.xml` and the WAR file; if either changes, it redeploys the war. - -The maven build is held up until jetty exits, which is achieved by typing `cntrl-c` at the command line. - -All jetty output is directed to the console. - -===== Configuration - -Configuration parameters are: - -webApp:: -war::: -The location of the built WAR file. This defaults to `${project.build.directory}/${project.build.finalName}.war`. -You can set it to the location of any pre-built war file. -contextPath::: -The context path for your webapp. By default, this is set to `/`. -If using a custom value for this parameter, you should include the leading `/`, example `/mycontext`. -defaultsDescriptor::: -The path to a `webdefault.xml` file that will be applied to your webapp before the `web.xml`. -If you don't supply one, Jetty uses a default file baked into the `jetty-webapp.jar`. -overrideDescriptor::: -The path to a `web.xml` file that Jetty applies after reading your `web.xml`. -You can use this to replace or add configuration. -containerIncludeJarPattern::: -Defaults to `.*/jetty-servlet-api-[^/]*\.jar$|.*javax.servlet.jsp.jstl-[^/]*\.jar|.*taglibs-standard-impl-.*\.jar`. -This is a pattern that is applied to the names of the jars on the container's classpath (ie the classpath of the plugin, not that of the webapp) that should be scanned for fragments, tlds, annotations etc. -This is analogous to the context attribute xref:og-container-include-jar-pattern[org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern] that is documented xref:og-container-include-jar-pattern[here]. -You can define extra patterns of jars that will be included in the scan. -webInfIncludeJarPattern::: -Defaults to matching _all_ of the dependency jars for the webapp (ie the equivalent of WEB-INF/lib). -You can make this pattern more restrictive to only match certain jars by using this setter. -This is analogous to the context attribute xref:og-web-inf-include-jar-pattern[org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern] that is documented xref:og-web-inf-include-jar-pattern[here]. -tempDirectory::: -The path to a dir that Jetty can use to expand or copy jars and jsp compiles when your webapp is running. -The default is `${project.build.outputDirectory}/tmp`. -contextXml::: -The path to a context xml file that is applied to your webapp AFTER the `webApp` element. -scan:: -The pause in seconds between sweeps of the webapp to check for changes and automatically hot redeploy if any are detected. -*By default this is `-1`, which disables hot redeployment scanning.* -A value of `0` means no hot redeployment is done, and that you must use the kbd:[Enter] key to manually force a redeploy. -Any positive integer will enable hot redeployment, using the number as the sweep interval in seconds. -scanTargetPatterns:: -Optional. -List of directories with ant-style include/excludes patterns to specify other files to periodically scan for changes. - -See xref:deployment-modes[Deployment Modes] for other configuration parameters available when using the `run-war` goal in EMBED, FORK or EXTERNAL modes. - -[[jetty-start-goal]] -==== jetty:start - -This is similar to the `jetty:run` goal, however it is _not_ designed to be run from the command line and does _not_ first execute the build up until the `test-compile` phase to ensure that all necessary classes and files of the webapp have been generated. -It will _not_ scan your project for changes and restart your webapp. -It does _not_ pause maven until jetty is stopped. - -Instead, it is designed to be used with build phase bindings in your pom. -For example to you can have maven start your webapp at the beginning of your tests and stop at the end. - -If the plugin is invoked as part of a multi-module build, any dependencies that are also in the maven reactor are used from their compiled classes. -Prior to jetty-9.4.7 any dependencies needed to be built first. - -Here's an example of using the `pre-integration-test` and `post-integration-test` Maven build phases to trigger the execution and termination of Jetty: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - {VERSION} - - foo - 9999 - - - - start-jetty - pre-integration-test - - start - - - - stop-jetty - post-integration-test - - stop - - - - ----- - -This goal will generate output from jetty into the `target/jetty-start.out` file. - -===== Configuration - -These configuration parameters are available: - -webApp:: -This is an instance of link:{javadoc-url}/org/eclipse/jetty/maven/plugin/MavenWebAppContext.html[org.eclipse.jetty.maven.plugin.MavenWebAppContext], which is an extension to the class link:{javadoc-url}/org/eclipse/jetty/webapp/WebAppContext.hml[`org.eclipse.jetty.webapp.WebAppContext`]. -You can use any of the setter methods on this object to configure your webapp. -Here are a few of the most useful ones: -+ -contextPath;; -The context path for your webapp. By default, this is set to `/`. -If using a custom value for this parameter, you should include the leading `/`, example `/mycontext`. -descriptor;; -The path to the `web.xml` file for your webapp. -The default is `src/main/webapp/WEB-INF/web.xml`. -defaultsDescriptor;; -The path to a `webdefault.xml` file that will be applied to your webapp before the `web.xml`. -If you don't supply one, Jetty uses a default file baked into the `jetty-webapp.jar`. -overrideDescriptor;; -The path to a `web.xml` file that Jetty applies after reading your `web.xml`. -You can use this to replace or add configuration. -jettyEnvXml;; -Optional. -Location of a `jetty-env.xml` file, which allows you to make JNDI bindings that satisfy `env-entry`, `resource-env-ref`, and `resource-ref` linkages in the `web.xml` that are scoped only to the webapp and not shared with other webapps that you might be deploying at the same time (for example, by using a `jettyXml` file). -tempDirectory;; -The path to a dir that Jetty can use to expand or copy jars and jsp compiles when your webapp is running. -The default is `${project.build.outputDirectory}/tmp`. -baseResource;; -The path from which Jetty serves static resources. -Defaults to `src/main/webapp`. -resourceBases;; -Use instead of `baseResource` if you have multiple directories from which you want to serve static content. -This is an array of directory names. -baseAppFirst;; -Defaults to "true". -Controls whether any overlaid wars are added before or after the original base resource(s) of the webapp. -See the section on xref:using-overlaid-wars[overlaid wars] for more information. -containerIncludeJarPattern;; -Defaults to `.*/jetty-servlet-api-[^/]*\.jar$|.*javax.servlet.jsp.jstl-[^/]*\.jar|.*taglibs-standard-impl-.*\.jar`. -This is a pattern that is applied to the names of the jars on the container's classpath (ie the classpath of the plugin, not that of the webapp) that should be scanned for fragments, tlds, annotations etc. -This is analogous to the context attribute xref:og-container-include-jar-pattern[org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern] that is documented xref:og-container-include-jar-pattern[here]. -You can define extra patterns of jars that will be included in the scan. -webInfIncludeJarPattern;; -Defaults to matching _all_ of the dependency jars for the webapp (ie the equivalent of WEB-INF/lib). -You can make this pattern more restrictive to only match certain jars by using this setter. -This is analogous to the context attribute xref:og-web-inf-include-jar-pattern[org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern] that is documented xref:og-web-inf-include-jar-pattern[here]. -contextXml:: -The path to a context xml file that is applied to your webapp AFTER the `webApp` element. -classesDirectory:: -Location of your compiled classes for the webapp. -You should rarely need to set this parameter. -Instead, you should set `build outputDirectory` in your `pom.xml`. -testClassesDirectory:: -Location of the compiled test classes for your webapp. By default this is `${project.build.testOutputDirectory}`. -useTestScope:: -If true, the classes from `testClassesDirectory` and dependencies of scope "test" are placed first on the classpath. -By default this is false. -stopPort:: -Optional. -Port to listen on for stop commands. -Useful to use in conjunction with the xref:jetty-stop-goal[stop] and xref:jetty-start-goal[start] goals. -stopKey:: -Optional. -Used in conjunction with stopPort for stopping jetty. -Useful to use in conjunction with the xref:jetty-stop-goal[stop] and xref:jetty-start-goal[start] goals. - -These additional configuration parameters are available when running in `FORK` or `EXTERNAL` mode: - -maxChildStartChecks:: -Default is `10`. -This is maximum number of times the parent process checks to see if the forked jetty process has started correctly -maxChildStartCheckMs:: -Default is `200`. -This is the time in milliseconds between checks on the startup of the forked jetty process. - - -[[jetty-start-war-goal]] -==== jetty:start-war - -Similarly to the `jetty:start` goal, `jetty:start-war` is designed to be bound to build lifecycle phases in your pom. - -It will _not_ scan your project for changes and restart your webapp. -It does _not_ pause maven until jetty is stopped. - -By default, if your pom is for a webapp project, it will deploy the war file for the project to jetty. -However, like the `jetty:run-war` project, you can nominate any war file to deploy by defining its location in the `<webApp><war>` parameter. - -If the plugin is invoked as part of a multi-module build, any dependencies that are also in the maven reactor are used from their compiled classes. -Prior to jetty-9.4.7 any dependencies needed to be built first. - -This goal will generate output from jetty into the `target/jetty-start-war.out` file. - -===== Configuration - -These configuration parameters are available: - -webApp:: -war::: -The location of the built WAR file. This defaults to `${project.build.directory}/${project.build.finalName}.war`. -You can set it to the location of any pre-built war file. -contextPath::: -The context path for your webapp. By default, this is set to `/`. -If using a custom value for this parameter, you should include the leading `/`, example `/mycontext`. -defaultsDescriptor::: -The path to a `webdefault.xml` file that will be applied to your webapp before the `web.xml`. -If you don't supply one, Jetty uses a default file baked into the `jetty-webapp.jar`. -overrideDescriptor::: -The path to a `web.xml` file that Jetty applies after reading your `web.xml`. -You can use this to replace or add configuration. -containerIncludeJarPattern::: -Defaults to `.*/jetty-servlet-api-[^/]*\.jar$|.*javax.servlet.jsp.jstl-[^/]*\.jar|.*taglibs-standard-impl-.*\.jar`. -This is a pattern that is applied to the names of the jars on the container's classpath (ie the classpath of the plugin, not that of the webapp) that should be scanned for fragments, tlds, annotations etc. -This is analogous to the context attribute xref:og-container-include-jar-pattern[org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern] that is documented xref:og-container-include-jar-pattern[here]. -You can define extra patterns of jars that will be included in the scan. -webInfIncludeJarPattern::: -Defaults to matching _all_ of the dependency jars for the webapp (ie the equivalent of WEB-INF/lib). -You can make this pattern more restrictive to only match certain jars by using this setter. -This is analogous to the context attribute xref:og-web-inf-include-jar-pattern[org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern] that is documented xref:og-web-inf-include-jar-pattern[here]. -tempDirectory::: -The path to a dir that Jetty can use to expand or copy jars and jsp compiles when your webapp is running. -The default is `${project.build.outputDirectory}/tmp`. -contextXml::: -The path to a context xml file that is applied to your webapp AFTER the `webApp` element. -stopPort:: -Optional. -Port to listen on for stop commands. -Useful to use in conjunction with the xref:jetty-stop-goal[stop]. -stopKey:: -Optional. -Used in conjunction with stopPort for stopping jetty. -Useful to use in conjunction with the xref:jetty-stop-goal[stop]. - -These additional configuration parameters are available when running in FORK or EXTERNAL mode: - -maxChildStartChecks:: -Default is `10`. -This is maximum number of times the parent process checks to see if the forked jetty process has started correctly -maxChildStartCheckMs:: -Default is `200`. -This is the time in milliseconds between checks on the startup of the forked jetty process. - - -[[jetty-stop-goal]] -==== jetty:stop - -The stop goal stops a FORK or EXTERNAL mode running instance of Jetty. -To use it, you need to configure the plugin with a special port number and key. -That same port number and key will also be used by the other goals that start jetty. - -===== Configuration - -stopPort:: -A port number for Jetty to listen on to receive a stop command to cause it to shutdown. -stopKey:: -A string value sent to the `stopPort` to validate the stop command. -stopWait:: -The maximum time in seconds that the plugin will wait for confirmation that Jetty has stopped. -If false or not specified, the plugin does not wait for confirmation but exits after issuing the stop command. - -Here's a configuration example: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - {VERSION} - - 9966 - foo - 10 - - ----- - -Then, while Jetty is running (in another window), type: - ----- -mvn jetty:stop ----- - -The `stopPort` must be free on the machine you are running on. -If this is not the case, you will get an "Address already in use" error message after the "Started ServerConnector ..." message. - -[[jetty-effective-web-xml-goal]] -==== jetty:effective-web-xml - -This goal calculates a synthetic `web.xml` (the "effective web.xml") according to the rules of the Servlet Specification taking into account all sources of discoverable configuration of web components in your application: descriptors (`webdefault.xml`, `web.xml`, `web-fragment.xml`s, `web-override.xml`) and discovered annotations (`@WebServlet`, `@WebFilter`, `@WebListener`). -No programmatic declarations of servlets, filters and listeners can be taken into account. - -You can calculate the effective web.xml for any pre-built war file by setting the `<webApp><war>` parameter, or you can calculate it for the unassembled webapp by setting all of the usual `<webApp>` parameters as for `jetty:run`. - -Other useful information about your webapp that is produced as part of the analysis is also stored as context parameters in the effective-web.xml. -The effective-web.xml can be used in conjunction with the xref:og-quickstart[Quickstart] feature to quickly start your webapp (note that Quickstart is not appropriate for the mvn jetty goals). - -The effective web.xml from these combined sources is generated into a file, which by default is `target/effective-web.xml`, but can be changed by setting the `effectiveWebXml` configuration parameter. - -===== Configuration - -effectiveWebXml:: -The full path name of a file into which you would like the effective web xml generated. -webApp:: -war::: -The location of the built WAR file. This defaults to `${project.build.directory}/${project.build.finalName}.war`. -You can set it to the location of any pre-built war file. -Or you can leave it blank and set up the other `webApp` parameters as per xref:jetty-run-goal[jetty:run], as well as the `webAppSourceDirectory`, `classes` and `testClasses` parameters. -contextPath::: -The context path for your webapp. By default, this is set to `/`. -If using a custom value for this parameter, you should include the leading `/`, example `/mycontext`. -defaultsDescriptor::: -The path to a `webdefault.xml` file that will be applied to your webapp before the `web.xml`. -If you don't supply one, Jetty uses a default file baked into the `jetty-webapp.jar`. -overrideDescriptor::: -The path to a `web.xml` file that Jetty applies after reading your `web.xml`. -You can use this to replace or add configuration. -containerIncludeJarPattern::: -Defaults to `.*/jetty-servlet-api-[^/]*\.jar$|.*javax.servlet.jsp.jstl-[^/]*\.jar|.*taglibs-standard-impl-.*\.jar`. -This is a pattern that is applied to the names of the jars on the container's classpath (ie the classpath of the plugin, not that of the webapp) that should be scanned for fragments, tlds, annotations etc. -This is analogous to the context attribute xref:og-container-include-jar-pattern[org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern] that is documented xref:og-container-include-jar-pattern[here]. -You can define extra patterns of jars that will be included in the scan. -webInfIncludeJarPattern::: -Defaults to matching _all_ of the dependency jars for the webapp (ie the equivalent of WEB-INF/lib). -You can make this pattern more restrictive to only match certain jars by using this setter. -This is analogous to the context attribute xref:og-web-inf-include-jar-pattern[org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern] that is documented xref:og-web-inf-include-jar-pattern[here]. -tempDirectory::: -The path to a dir that Jetty can use to expand or copy jars and jsp compiles when your webapp is running. -The default is `${project.build.outputDirectory}/tmp`. -contextXml::: -The path to a context xml file that is applied to your webapp AFTER the `webApp` element. - - -You can also generate the origin of each element into the effective web.xml file. -The origin is either a descriptor eg web.xml,web-fragment.xml,override-web.xml file, or an annotation eg @WebServlet. -Some examples of elements with origin attribute information are: - -[source,xml] ----- - - - - ----- - -To generate origin information, use the following configuration parameters on the `webApp` element: - -originAttribute:: -The name of the attribute that will contain the origin. -By default it is `origin`. -generateOrigin:: -False by default. If true, will force the generation of the originAttribute onto each element. - - -[[using-overlaid-wars]] -==== Using Overlaid wars - -If your webapp depends on other war files, the xref:jetty-run-goal[jetty:run] and xref:jetty-start-goal[jetty:start] goals are able to merge resources from all of them. -It can do so based on the settings of the http://maven.apache.org/plugins/maven-war-plugin/[maven-war-plugin], or if your project does not use the http://maven.apache.org/plugins/maven-war-plugin/[maven-war-plugin] to handle the overlays, it can fall back to a simple algorithm to determine the ordering of resources. - -===== With maven-war-plugin - -The maven-war-plugin has a rich set of capabilities for merging resources. -The `jetty:run` and `jetty:start` goals are able to interpret most of them and apply them during execution of your unassembled webapp. -This is probably best seen by looking at a concrete example. - -Suppose your webapp depends on the following wars: - -[source,xml] ----- - - com.acme - X - war - - - com.acme - Y - war - ----- - -Containing: - ----- -WebAppX: - - /foo.jsp - /bar.jsp - /WEB-INF/web.xml - -WebAppY: - - /bar.jsp - /baz.jsp - /WEB-INF/web.xml - /WEB-INF/special.xml ----- - -They are configured for the http://maven.apache.org/plugins/maven-war-plugin/overlays.html[maven-war-plugin]: - -[source,xml] ----- - - org.apache.maven.plugins - maven-war-plugin - {VERSION} - - - - com.acme - X - - bar.jsp - - - - com.acme - Y - - baz.jsp - - - - - - - ----- - -Then executing jetty:run would yield the following ordering of resources: `com.acme.X.war : com.acme.Y.war: ${project.basedir}/src/main/webapp`. -Note that the current project's resources are placed last in the ordering due to the empty element in the maven-war-plugin. -You can either use that, or specify the `false` parameter to the jetty-maven-plugin. - -Moreover, due to the `exclusions` specified above, a request for the resource ` bar.jsp` would only be satisfied from `com.acme.Y.war.` -Similarly as `baz.jsp` is excluded, a request for it would result in a 404 error. - -===== Without maven-war-plugin - -The algorithm is fairly simple, is based on the ordering of declaration of the dependent wars, and does not support exclusions. -The configuration parameter `` (see for example xref:jetty-run-goal[jetty:run] for more information) can be used to control whether your webapp's resources are placed first or last on the resource path at runtime. - -For example, suppose our webapp depends on these two wars: - -[source,xml] ----- - - com.acme - X - war - - - com.acme - Y - war - ----- - -Suppose the webapps contain: - ----- -WebAppX: - - /foo.jsp - /bar.jsp - /WEB-INF/web.xml - -WebAppY: - - /bar.jsp - /baz.jsp - /WEB-INF/web.xml - /WEB-INF/special.xml - ----- - -Then our webapp has available these additional resources: - ----- -/foo.jsp (X) -/bar.jsp (X) -/baz.jsp (Y) -/WEB-INF/web.xml (X) -/WEB-INF/special.xml (Y) ----- - -[[configuring-security-settings]] -==== Configuring Security Settings - -You can configure LoginServices in the plugin. -Here's an example of setting up the HashLoginService for a webapp: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - {VERSION} - - 10 - - /test - - - - Test Realm - ${project.basedir}/src/etc/realm.properties - - - - - ----- - -[[using-multiple-webapp-root-directories]] -==== Using Multiple Webapp Root Directories - -If you have external resources that you want to incorporate in the execution of a webapp, but which are not assembled into war files, you can't use the overlaid wars method described above, but you can tell Jetty the directories in which these external resources are located. -At runtime, when Jetty receives a request for a resource, it searches all the locations to retrieve the resource. -It's a lot like the overlaid war situation, but without the war. - -Here is a configuration example: - -[source,xml] ----- - - - /${build.finalName} - - src/main/webapp - /home/johndoe/path/to/my/other/source - /yet/another/folder - - - ----- - -[[running-more-than-one-webapp]] -==== Running More than One Webapp - -===== With jetty:run - -You can use either a `jetty.xml` file to configure extra (pre-compiled) webapps that you want to deploy, or you can use the `` configuration element to do so. -If you want to deploy webapp A, and webapps B and C in the same Jetty instance: - -Putting the configuration in webapp A's `pom.xml`: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - {VERSION} - - 10 - - /test - - - - ${project.basedir}../../B.war - /B - - - ${project.basedir}../../C.war - /C - - - - ----- - -[IMPORTANT] -==== -If the `ContextHandler` you are deploying is a webapp, it is *essential* that you use an `org.eclipse.jetty.maven.plugin.MavenWebAppContext` instance rather than a standard `org.eclipse.jetty.webapp.WebAppContext` instance. -Only the former will allow the webapp to function correctly in the maven environment. -==== - -Alternatively, add a `jetty.xml` file to webapp A. -Copy the `jetty.xml` file from the Jetty distribution, and then add WebAppContexts for the other 2 webapps: - -[source,xml] ----- - - - - - /B - ../../B.war - - - - - - - /C - ../../C.war - - - - ----- - -Then configure the location of this `jetty.xml` file into webapp A's jetty plugin: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - {VERSION} - - 10 - - /test - - src/main/etc/jetty.xml - - ----- - -For either of these solutions, the other webapps must already have been built, and they are not automatically monitored for changes. -You can refer either to the packed WAR file of the pre-built webapps or to their expanded equivalents. - -[[setting-system-properties]] -==== Setting System Properties - -You can specify property name/value pairs that Jetty sets as System properties for the execution of the plugin. -This feature is useful to tidy up the command line and save a lot of typing. - -However, *sometimes it is not possible to use this feature to set System properties* - sometimes the software component using the System property is already initialized by the time that maven runs (in which case you will need to provide the System property on the command line), or by the time that Jetty runs. -In the latter case, you can use the link:http://www.mojohaus.org/[maven properties plugin] to define the system properties instead. Here's an example that configures the logback logging system as the Jetty logger: - -[source,xml] ----- - - org.codehaus.mojo - properties-maven-plugin - 1.0-alpha-2 - - - - set-system-properties - - - - - logback.configurationFile - ${project.baseUri}/resources/logback.xml - - - - - - ----- - -[NOTE] -==== -If a System property is already set (for example, from the command line or by the JVM itself), then by default these configured properties *DO NOT* override them. -However, they can override system properties set from a file instead, see xref:specifying-properties-in-file[specifying system properties in a file]. -==== - -[[specifying-properties-in-pom]] -===== Specifying System Properties in the POM - -Here's an example of how to specify System properties in the POM: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - - - 222 - - - /test - - - - ----- - -[[specifying-properties-in-file]] -===== Specifying System Properties in a File - -You can also specify your System properties in a file. -System properties you specify in this way *do not* override System properties that set on the command line, by the JVM, or directly in the POM via `systemProperties`. - -Suppose we have a file called `mysys.props` which contains the following: - ----- -fooprop=222 ----- - -This can be configured on the plugin like so: - -[source,xml] ----- - - org.eclipse.jetty - jetty-maven-plugin - - ${project.basedir}/mysys.props - - /test - - - ----- - -You can instead specify the file by setting the System property `jetty.systemPropertiesFile` on the command line. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/maven.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/maven.adoc deleted file mode 100644 index 6d2427e547ee..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/maven/maven.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[maven-and-jetty]] -== Maven and Jetty - -include::jetty-maven-helloworld.adoc[] -include::jetty-maven-plugin.adoc[] -include::jetty-jspc-maven-plugin.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/migration/migration.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/migration/migration.adoc deleted file mode 100644 index 17f29b4b25de..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/migration/migration.adoc +++ /dev/null @@ -1,135 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[appendix] -[[pg-migration]] -== Migration Guides - -[[pg-migration-94-to-10]] -=== Migrating from Jetty 9.4.x to Jetty 10.0.x - -[[pg-migration-94-to-10-java-version]] -==== Required Java Version Changes - -[cols="1,1", options="header"] -|=== -| Jetty 9.4.x | Jetty 10.0.x -| Java 8 | Java 11 -|=== - -[[pg-migration-94-to-10-websocket]] -==== WebSocket Migration Guide - -Migrating from Jetty 9.4.x to Jetty 10.0.x requires changes in the coordinates of the Maven artifact dependencies for WebSocket. Some of these classes have also changed name and package. This is not a comprehensive list of changes but should cover the most common changes encountered during migration. - -[[pg-migration-94-to-10-websocket-maven-artifact-changes]] -===== Maven Artifacts Changes - -[cols="1a,1a", options="header"] -|=== -| Jetty 9.4.x | Jetty 10.0.x - -| `org.eclipse.jetty.websocket:**websocket-api**` -| `org.eclipse.jetty.websocket:**websocket-jetty-api**` - -| `org.eclipse.jetty.websocket:**websocket-server**` -| `org.eclipse.jetty.websocket:**websocket-jetty-server**` - -| `org.eclipse.jetty.websocket:**websocket-client**` -| `org.eclipse.jetty.websocket:**websocket-jetty-client**` - -| `org.eclipse.jetty.websocket:**javax-websocket-server-impl**` -| `org.eclipse.jetty.websocket:**websocket-javax-server**` - -| `org.eclipse.jetty.websocket:**javax-websocket-client-impl**` -| `org.eclipse.jetty.websocket:**websocket-javax-client**` - -|=== - -[[pg-migration-94-to-10-websocket-class-name-changes]] -===== Class Names Changes - -[cols="1a,1a", options="header"] -|=== -| Jetty 9.4.x | Jetty 10.0.x - -| `org.eclipse.jetty.websocket.**server.NativeWebSocketServletContainerInitializer**` -| `org.eclipse.jetty.websocket.**server.config.JettyWebSocketServletContainerInitializer**` - -| `org.eclipse.jetty.websocket.**jsr356.server.deploy.WebSocketServerContainerInitializer**` -| `org.eclipse.jetty.websocket.**javax.server.config.JavaxWebSocketServletContainerInitializer**` - -| `org.eclipse.jetty.websocket.**servlet.WebSocketCreator**` -| `org.eclipse.jetty.websocket.**server.JettyWebSocketCreator**` - -| `org.eclipse.jetty.websocket.**servlet.ServletUpgradeRequest**` -| `org.eclipse.jetty.websocket.**server.JettyServerUpgradeRequest**` - -| `org.eclipse.jetty.websocket.**servlet.ServletUpgradeResponse**` -| `org.eclipse.jetty.websocket.**server.JettyServerUpgradeResponse**` - -| `org.eclipse.jetty.websocket.**servlet.WebSocketServlet**` -| `org.eclipse.jetty.websocket.**server.JettyWebSocketServlet**` - -| `org.eclipse.jetty.websocket.**servlet.WebSocketServletFactory**` -| `org.eclipse.jetty.websocket.**server.JettyWebSocketServletFactory**` -|=== - -[[pg-migration-94-to-10-websocket-example-code]] -===== Example Code - -[cols="1a,1a", options="header"] -|=== -| Jetty 9.4.x -| Jetty 10.0.x - -| -[source,java] ----- -public class ExampleWebSocketServlet extends WebSocketServlet -{ - @Override - public void configure(WebSocketServletFactory factory) - { - factory.setCreator(new WebSocketCreator() - { - @Override - public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) - { - return new ExampleEndpoint(); - } - }); - } -} ----- - -| -[source,java] ----- -public class ExampleWebSocketServlet extends JettyWebSocketServlet -{ - @Override - public void configure(JettyWebSocketServletFactory factory) - { - factory.setCreator(new JettyWebSocketCreator() - { - @Override - public Object createWebSocket(JettyServerUpgradeRequest req, JettyServerUpgradeResponse resp) - { - return new ExampleEndpoint(); - } - }); - } -} ----- -|=== \ No newline at end of file diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-cookie.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-cookie.adoc deleted file mode 100644 index a9283d97bfd2..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-cookie.adoc +++ /dev/null @@ -1,35 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-compliance-cookie]] -==== Cookie Compliance Modes - -The standards for Cookies have varied greatly over time from a non-specified but de-facto standard (implemented by the first browsers), through link:https://tools.ietf.org/html/rfc2965[RFC 2965] and currently to link:https://tools.ietf.org/html/rfc6265[RFC 6265]. - -The link:{javadoc-url}/org/eclipse/jetty/http/CookieCompliance.Violation.html[CookieCompliance.Violation] enumeration defines the RFC requirements that may be optionally enforced by Jetty when parsing the `Cookie` HTTP header in requests and when generating the `Set-Cookie` HTTP header in responses. - -These violations are then grouped into modes by the link:{javadoc-url}/org/eclipse/jetty/http/CookieCompliance.html[`CookieCompliance`] class, which also defines several named modes that support common deployed sets of violations, with the default being link:{javadoc-url}/org/eclipse/jetty/http/CookieCompliance.html#RFC6265[`CookieCompliance.RFC6265`]. - -For example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=cookieCompliance] ----- - -If you want to customize the violations that you want to allow, you can create your own mode using the link:{javadoc-url}/org/eclipse/jetty/http/CookieCompliance.html#from(java.lang.String)[`CookieCompliance.from(String)`] method: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=cookieComplianceCustom] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-http.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-http.adoc deleted file mode 100644 index 22b80d68ba81..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-http.adoc +++ /dev/null @@ -1,42 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-compliance-http]] -==== HTTP Compliance Modes - -In 1995, when Jetty was first implemented, there were no RFC specification of HTTP, only a W3C specification for link:https://www.w3.org/Protocols/HTTP/AsImplemented.html[HTTP/0.9], which has since been obsoleted or augmented by: - - * link:https://datatracker.ietf.org/doc/html/rfc1945[RFC 1945] for HTTP/1.0 in 1996 - * link:https://datatracker.ietf.org/doc/html/rfc2068[RFC 2068] for HTTP/1.1 in 1997 - * link:https://datatracker.ietf.org/doc/html/rfc2616[RFC 2616] for HTTP/1.1 bis in 1999 - * link:https://datatracker.ietf.org/doc/html/rfc7230[RFC 7230], link:https://datatracker.ietf.org/doc/html/rfc7231[RFC 7231], link:https://datatracker.ietf.org/doc/html/rfc7232[RFC 7232], link:https://datatracker.ietf.org/doc/html/rfc7233[RFC 7233], link:https://datatracker.ietf.org/doc/html/rfc7234[RFC 7234], link:https://datatracker.ietf.org/doc/html/rfc7235[RFC 7235] again for HTTP/1.1 in 2014 - * link:https://datatracker.ietf.org/doc/html/rfc7540[RFC 7540] for HTTP/2.0 in 2015 - -In addition to these evolving requirements, some earlier version of Jetty did not completely or strictly implement the RFC at the time (for example, case-insensitive HTTP methods). -Therefore, upgrading to a newer Jetty version may cause runtime behavior differences that may break your applications. - -The link:{javadoc-url}/org/eclipse/jetty/http/HttpCompliance.Violation.html[`HttpCompliance.Violation`] enumeration defines the RFC requirements that may be optionally enforced by Jetty, to support legacy deployments. These possible violations are grouped into modes by the link:{javadoc-url}/org/eclipse/jetty/http/HttpCompliance.html[`HttpCompliance`] class, which also defines several named modes that support common deployed sets of violations (with the default being link:{javadoc-url}/org/eclipse/jetty/http/HttpCompliance.html#RFC7230[`HttpCompliance.RFC7230`]). - -For example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=httpCompliance] ----- - -If you want to customize the violations that you want to allow, you can create your own mode using the link:{javadoc-url}/org/eclipse/jetty/http/HttpCompliance.html#from(java.lang.String)[`HttpCompliance.from(String)`] method: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=httpComplianceCustom] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-uri.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-uri.adoc deleted file mode 100644 index bdf3699dcd96..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance-uri.adoc +++ /dev/null @@ -1,52 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-compliance-uri]] -==== URI Compliance Modes - -Universal Resource Locators (URLs) where initially formalized in 1994 in link:https://datatracker.ietf.org/doc/html/rfc1738[RFC 1738] and then refined in 1995 with relative URLs by link:https://datatracker.ietf.org/doc/html/rfc1808[RFC 1808]. - -In 1998, URLs were generalized to Universal Resource Identifiers (URIs) by link:https://datatracker.ietf.org/doc/html/rfc2396[RFC 2396], which also introduced features such a link:https://datatracker.ietf.org/doc/html/rfc2396#section-3.3[path parameter]s. - -This was then obsoleted in 2005 by link:https://datatracker.ietf.org/doc/html/rfc3986[RFC 3986] which removed the definition for path parameters. - -Unfortunately by this stage the existence and use of such parameters had already been codified in the Servlet specification. -For example, the relative URI `/foo/bar;JSESSIONID=a8b38cd02b1c` would define the path parameter `JSESSIONID` for the path segment `bar`, but the most recent RFC does not specify a formal definition of what this relative URI actually means. - -The current situation is that there may be URIs that are entirely valid for link:https://datatracker.ietf.org/doc/html/rfc3986[RFC 3986], but are ambiguous when handled by the Servlet APIs: - -* A URI with `..` _and_ path parameters such as `/some/..;/path` is not link:https://datatracker.ietf.org/doc/html/rfc3986#section-5.2[_resolved_] by RFC 3986, since the resolution process only applies to the exact segment `..`, not to `..;`. -However, once the path parameters are removed by the Servlet APIs, the resulting `/some/../path` can easily be resolved to `/path`, rather than be treated as a path that has `..;` as a segment. -* A URI such as `/some/%2e%2e/path` is not resolved by RFC 3986, yet when URL-decoded by the Servlet APIs will result in `/some/../path` which can easily be resolved to `/path`, rather than be treated as a path that has `..` as a segment. -* A URI with empty segments like `/some//../path` may be correctly resolved to `/some/path` (the `..` removes the previous empty segment) by the Servlet APIs. -However, if the URI raw path is passed to some other APIs (for example, file system APIs) it can be interpreted as `/path` because the empty segment `//` is discarded and treated as `/`, and the `..` thus removes the `/some` segment. - -In order to avoid ambiguous URIs, Jetty imposes additional URI requirements in excess of what is required by link:https://datatracker.ietf.org/doc/html/rfc3986[RFC 3986] compliance. - -These additional requirements may optionally be violated and are defined by the link:{javadoc-url}/org/eclipse/jetty/http/UriCompliance.Violation.html[`UriCompliance.Violation`] enumeration. - -These violations are then grouped into modes by the link:{javadoc-url}/org/eclipse/jetty/http/UriCompliance.html[`UriCompliance`] class, which also defines several named modes that support common deployed sets of violations, with the default being link:{javadoc-url}/org/eclipse/jetty/http/UriCompliance.html#DEFAULT[`UriCompliance.DEFAULT`]. - -For example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=uriCompliance] ----- - -If you want to customize the violations that you want to allow, you can create your own mode using the link:{javadoc-url}/org/eclipse/jetty/http/UriCompliance.html#from(java.lang.String)[`UriCompliance.from(String)`] method: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=uriComplianceCustom] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance.adoc deleted file mode 100644 index b3efacb87d50..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/compliance/server-compliance.adoc +++ /dev/null @@ -1,33 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-compliance]] -=== Server Compliance Modes - -The Jetty server strives to keep up with the latest link:https://en.wikipedia.org/wiki/Request_for_Comments[IETF RFC]s for compliance with internet specifications, which are periodically updated. - -When possible, Jetty will support backwards compatibility by providing compliance modes that can be configured to allow violations of the current specifications that may have been allowed in obsoleted specifications. - -There are compliance modes provided for: - -* xref:pg-server-compliance-http[HTTP Compliance] -* xref:pg-server-compliance-uri[URI Compliance] -* xref:pg-server-compliance-cookie[Cookie Compliance] - -Compliance modes can be configured to allow violations from the RFC requirements, or in some cases to allow additional behaviors that Jetty has implemented in excess of the RFC (for example, to allow xref:pg-server-compliance-uri[ambiguous URIs]). - -For example, the HTTP RFCs require that request HTTP methods are link:https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.1[case sensitive], however Jetty can allow case-insensitive HTTP methods by including the link:{javadoc-url}/org/eclipse/jetty/http/HttpCompliance.Violation.html#CASE_INSENSITIVE_METHOD[`HttpCompliance.Violation.CASE_INSENSITIVE_METHOD`] in the link:{javadoc-url}/org/eclipse/jetty/http/HttpCompliance.html[`HttpCompliance`] set of allowed violations. - -include::server-compliance-http.adoc[] -include::server-compliance-uri.adoc[] -include::server-compliance-cookie.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/fastcgi/server-fastcgi.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/fastcgi/server-fastcgi.adoc deleted file mode 100644 index 46363049fea9..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/fastcgi/server-fastcgi.adoc +++ /dev/null @@ -1,17 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-fastcgi]] -=== FastCGI Server Libraries - -TODO diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-application.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-application.adoc deleted file mode 100644 index a5f63f289807..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-application.adoc +++ /dev/null @@ -1,55 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http-application]] -===== Writing HTTP Server Applications - -Writing HTTP applications is typically simple, especially when using blocking APIs. -However, there are subtle cases where it is worth clarifying what a server application should do to obtain the desired results when run by Jetty. - -[[pg-server-http-application-1xx]] -====== Sending 1xx Responses - -The link:https://tools.ietf.org/html/rfc7231#section-5.1.1[HTTP/1.1 RFC] allows for `1xx` informational responses to be sent before a real content response. -Unfortunately the servlet specification does not provide a way for these to be sent, so Jetty has had to provide non-standard handling of these headers. - -[[pg-server-http-application-100]] -====== 100 Continue - -The `100 Continue` response should be sent by the server when a client sends a request with an `Expect: 100-continue` header, as the client will not send the body of the request until the `100 Continue` response has been sent. - -The intent of this feature is to allow a server to inspect the headers and to tell the client to not send a request body that might be too large or insufficiently private or otherwise unable to be handled. - -Jetty achieves this by waiting until the input stream or reader is obtained by the filter/servlet, before sending the `100 Continue` response. -Thus a filter/servlet may inspect the headers of a request before getting the input stream and send an error response (or redirect etc.) rather than the 100 continues. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=continue100] ----- - -[[jetty-102-processing]] -====== 102 Processing - -link:https://tools.ietf.org/html/rfc2518[RFC 2518] defined the `102 Processing` status code that can be sent: - -[quote,RFC 2518 section 10.1] -when the server has a reasonable expectation that the request will take significant time to complete. -As guidance, if a method is taking longer than 20 seconds (a reasonable, but arbitrary value) to process the server SHOULD return a `102 Processing` response. - -However, a later update of RFC 2518, link:https://tools.ietf.org/html/rfc4918[RFC 4918], removed the `102 Processing` status code for link:https://tools.ietf.org/html/rfc4918#appendix-F.3["lack of implementation"]. - -Jetty supports the `102 Processing` status code. -If a request is received with the `Expect: 102-processing` header, then a filter/servlet may send a `102 Processing` response (without terminating further processing) by calling `response.sendError(102)`. - -// TODO: add section to always read request content until -1 is reached. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-connector.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-connector.adoc deleted file mode 100644 index 182a4575352f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-connector.adoc +++ /dev/null @@ -1,243 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http-connector]] -==== Server Connectors - -A `Connector` is the component that handles incoming requests from clients, and works in conjunction with `ConnectionFactory` instances. - -The available implementations are: - -* `org.eclipse.jetty.server.ServerConnector`, for TCP/IP sockets. -* `org.eclipse.jetty.unixdomain.server.UnixDomainServerConnector` for Unix-Domain sockets (requires Java 16 or later). - -Both use a `java.nio.channels.ServerSocketChannel` to listen to a socket address and to accept socket connections. - -Since `ServerConnector` wraps a `ServerSocketChannel`, it can be configured in a similar way, for example the IP port to listen to, the IP address to bind to, etc.: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=configureConnector] ----- - -Likewise, `UnixDomainServerConnector` also wraps a `ServerSocketChannel` and can be configured with the Unix-Domain path to listen to: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=configureConnectorUnix] ----- - -[IMPORTANT] -==== -You can use Unix-Domain sockets support only when you run your server with Java 16 or later. -==== - -The _acceptors_ are threads (typically only one) that compete to accept socket connections. -When a connection is accepted, `ServerConnector` wraps the accepted `SocketChannel` and passes it to the xref:pg-arch-io-selector-manager[`SelectorManager`]. -Therefore, there is a little moment where the acceptor thread is not accepting new connections because it is busy wrapping the just accepted connection to pass it to the `SelectorManager`. -Connections that are ready to be accepted but are not accepted yet are queued in a bounded queue (at the OS level) whose capacity can be configured with the `acceptQueueSize` parameter. - -If your application must withstand a very high rate of connections opened, configuring more than one acceptor thread may be beneficial: when one acceptor thread accepts one connection, another acceptor thread can take over accepting connections. - -The _selectors_ are components that manage a set of connected sockets, implemented by xref:pg-arch-io-selector-manager[`ManagedSelector`]. -Each selector requires one thread and uses the Java NIO mechanism to efficiently handle a set of connected sockets. -As a rule of thumb, a single selector can easily manage up to 1000-5000 sockets, although the number may vary greatly depending on the application. - -For example, web site applications tend to use sockets for one or more HTTP requests to retrieve resources and then the socket is idle for most of the time. -In this case a single selector may be able to manage many sockets because chances are that they will be idle most of the time. -On the contrary, web messaging applications tend to send many small messages at a very high frequency so that sockets are rarely idle. -In this case a single selector may be able to manage less sockets because chances are that many of them will be active at the same time. - -It is possible to configure more than one `ServerConnector` (each listening on a different port), or more than one `UnixDomainServerConnector` (each listening on a different path), or ``ServerConnector``s and ``UnixDomainServerConnector``s, for example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=configureConnectors] ----- - -[[pg-server-http-connector-protocol]] -===== Configuring Protocols - -For each accepted socket connection, the server `Connector` asks a `ConnectionFactory` to create a `Connection` object that handles the traffic on that socket connection, parsing and generating bytes for a specific protocol (see xref:pg-arch-io[this section] for more details about `Connection` objects). - -A server `Connector` can be configured with one or more ``ConnectionFactory``s. -If no `ConnectionFactory` is specified then `HttpConnectionFactory` is implicitly configured. - -[[pg-server-http-connector-protocol-http11]] -====== Clear-Text HTTP/1.1 - -`HttpConnectionFactory` creates `HttpConnection` objects that parse bytes and generate bytes for the HTTP/1.1 protocol. - -This is how you configure Jetty to support clear-text HTTP/1.1: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=http11] ----- - -[[pg-server-http-connector-protocol-http11-tls]] -====== Encrypted HTTP/1.1 (https) - -Supporting encrypted HTTP/1.1 (that is, requests with the `https` scheme) is supported by configuring an `SslContextFactory` that has access to the KeyStore containing the private server key and public server certificate, in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=tlsHttp11] ----- - -You can customize the SSL/TLS provider as explained in xref:pg-server-http-connector-protocol-tls-conscrypt[this section]. - -[[pg-server-http-connector-protocol-http2]] -====== Clear-Text HTTP/2 - -It is well known that the HTTP ports are `80` (for clear-text HTTP) and `443` for encrypted HTTP. -By using those ports, a client had _prior knowledge_ that the server would speak, respectively, the HTTP/1.x protocol and the TLS protocol (and, after decryption, the HTTP/1.x protocol). - -HTTP/2 was designed to be a smooth transition from HTTP/1.1 for users and as such the HTTP ports were not changed. -However the HTTP/2 protocol is, on the wire, a binary protocol, completely different from HTTP/1.1. -Therefore, with HTTP/2, clients that connect to port `80` (or to a specific Unix-Domain path) may speak either HTTP/1.1 or HTTP/2, and the server must figure out which version of the HTTP protocol the client is speaking. - -Jetty can support both HTTP/1.1 and HTTP/2 on the same clear-text port by configuring both the HTTP/1.1 and the HTTP/2 ``ConnectionFactory``s: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=http11H2C] ----- - -Note how the ``ConnectionFactory``s passed to `ServerConnector` are in order: first HTTP/1.1, then HTTP/2. -This is necessary to support both protocols on the same port: Jetty will start parsing the incoming bytes as HTTP/1.1, but then realize that they are HTTP/2 bytes and will therefore _upgrade_ from HTTP/1.1 to HTTP/2. - -This configuration is also typical when Jetty is installed in backend servers behind a load balancer that also takes care of offloading TLS. -When Jetty is behind a load balancer, you can always prepend the PROXY protocol as described in xref:pg-server-http-connector-protocol-proxy-http11[this section]. - -[[pg-server-http-connector-protocol-http2-tls]] -====== Encrypted HTTP/2 - -When using encrypted HTTP/2, the unencrypted protocol is negotiated by client and server using an extension to the TLS protocol called ALPN. - -Jetty supports ALPN and encrypted HTTP/2 with this configuration: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=tlsALPNHTTP] ----- - -Note how the ``ConnectionFactory``s passed to `ServerConnector` are in order: TLS, ALPN, HTTP/2, HTTP/1.1. - -Jetty starts parsing TLS bytes so that it can obtain the ALPN extension. -With the ALPN extension information, Jetty can negotiate a protocol and pick, among the ``ConnectionFactory``s supported by the `ServerConnector`, the `ConnectionFactory` correspondent to the negotiated protocol. - -The fact that the HTTP/2 protocol comes before the HTTP/1.1 protocol indicates that HTTP/2 is the preferred protocol for the server. - -Note also that the default protocol set in the ALPN ``ConnectionFactory``, which is used in case ALPN is not supported by the client, is HTTP/1.1 -- if the client does not support ALPN is probably an old client so HTTP/1.1 is the safest choice. - -You can customize the SSL/TLS provider as explained in xref:pg-server-http-connector-protocol-tls-conscrypt[this section]. - -[[pg-server-http-connector-protocol-http3]] -====== HTTP/3 - -HTTP/3 is based on UDP, differently from HTTP/1 and HTTP/2 that are based on TCP. - -An HTTP/3 client may initiate a connection (using the QUIC protocol via UDP) on the canonical HTTP secure port `443`, but chances are that the connection may not succeed (for example, the server does not listen for UDP on port `443`, only listens for TCP). - -For this reason, HTTP servers typically listen on the canonical HTTP secure port `443` for HTTP/1 and HTTP/2, and advertise the availability HTTP/3 as an link:https://datatracker.ietf.org/doc/html/rfc7838[_HTTP alternate service_] on a different port (and possibly a different host). - -For example, an HTTP/2 response may include the following header: - -[source] ----- -Alt-Svc: h3=":843" ----- - -The presence of this header indicates that protocol `h3` is available on the same host (since no host is defined before the port), but on port `843`. -The HTTP/3 client may now initiate a QUIC connection on port `843` and make HTTP/3 requests. - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant client -participant "server:443" as h2server -participant "server:843" as h3server - -client -> h2server : HTTP/2 request -h2server -> client : HTTP/2 response\nAlt-Svc: h3=":843" -client -> h3server : HTTP/3 requests -h3server -> client : HTTP/3 responses -... ----- - -The code necessary to configure HTTP/2 is described in xref:pg-server-http-connector-protocol-http2-tls[this section]. - -To setup HTTP/3, for example on port `843`, you need the following code (some of which could be shared with other connectors such as HTTP/2's): - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=h3] ----- - -[[pg-server-http-connector-protocol-tls-conscrypt]] -====== Using Conscrypt as SSL/TLS Provider - -If not explicitly configured, the TLS implementation is provided by the JDK you are using at runtime. - -OpenJDK's vendors may replace the default TLS provider with their own, but you can also explicitly configure an alternative TLS provider. - -The standard TLS provider from OpenJDK is implemented in Java (no native code), and its performance is not optimal, both in CPU usage and memory usage. - -A faster alternative, implemented natively, is Google's link:https://github.com/google/conscrypt/[Conscrypt], which is built on link:https://boringssl.googlesource.com/boringssl/[BoringSSL], which is Google's fork of link:https://www.openssl.org/[OpenSSL]. - -CAUTION: As Conscrypt eventually binds to a native library, there is a higher risk that a bug in Conscrypt or in the native library causes a JVM crash, while the Java implementation will not cause a JVM crash. - -To use Conscrypt as TLS provider, you must have the Conscrypt jar and the Jetty dependency `jetty-alpn-conscrypt-server-{version}.jar` in the class-path or module-path. - -Then, you must configure the JDK with the Conscrypt provider, and configure Jetty to use the Conscrypt provider, in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=conscrypt] ----- - -[[pg-server-http-connector-protocol-proxy-http11]] -====== Jetty Behind a Load Balancer - -It is often the case that Jetty receives connections from a load balancer configured to distribute the load among many Jetty backend servers. - -From the Jetty point of view, all the connections arrive from the load balancer, rather than the real clients, but is possible to configure the load balancer to forward the real client IP address and IP port to the backend Jetty server using the link:https://www.haproxy.org/download/2.1/doc/proxy-protocol.txt[PROXY protocol]. - -NOTE: The PROXY protocol is widely supported by load balancers such as link:http://cbonte.github.io/haproxy-dconv/2.2/configuration.html#5.2-send-proxy[HAProxy] (via its `send-proxy` directive), link:https://docs.nginx.com/nginx/admin-guide/load-balancer/using-proxy-protocol[Nginx](via its `proxy_protocol on` directive) and others. - -To support this case, Jetty can be configured in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=proxyHTTP] ----- - -Note how the ``ConnectionFactory``s passed to `ServerConnector` are in order: first PROXY, then HTTP/1.1. -Note also how the PROXY `ConnectionFactory` needs to know its _next_ protocol (in this example, HTTP/1.1). - -Each `ConnectionFactory` is asked to create a `Connection` object for each accepted TCP connection; the `Connection` objects will be chained together to handle the bytes, each for its own protocol. -Therefore the `ProxyConnection` will handle the PROXY protocol bytes and `HttpConnection` will handle the HTTP/1.1 bytes producing a request object and response object that will be processed by ``Handler``s. - -The load balancer may be configured to communicate with Jetty backend servers via Unix-Domain sockets (requires Java 16 or later). -For example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=proxyHTTPUnix] ----- - -Note that the only difference when using Unix-Domain sockets is instantiating `UnixDomainServerConnector` instead of `ServerConnector` and configuring the Unix-Domain path instead of the IP port. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler-implement.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler-implement.adoc deleted file mode 100644 index 543eafe0f4e2..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler-implement.adoc +++ /dev/null @@ -1,54 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http-handler-implement]] -===== Implementing Handler - -The `Handler` API consist fundamentally of just one method: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=handlerAPI] ----- - -The `target` parameter is an identifier for the resource. -This is normally the URI that is parsed from an HTTP request. -However, a request could be forwarded to either a named resource, in which case `target` will be the name of the resource, or to a different URI, in which case `target` will be the new URI. - -Applications may wrap the request or response (or both) and forward the wrapped request or response to a different URI (which may be possibly handled by a different `Handler`). -This is the reason why there are two request parameters in the `Handler` APIs: the first is the unwrapped, original, request that also gives access to Jetty-specific APIs, while the second is the application-wrapped Servlet request. - -[[pg-server-http-handler-impl-hello]] -====== Hello World Handler - -A simple "Hello World" `Handler` is the following: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=handlerHello] ----- - -Such a simple `Handler` extends from `AbstractHandler` and can access the request and response main features, such as reading request headers and content, or writing response headers and content. - -[[pg-server-http-handler-impl-filter]] -====== Filtering Handler - -A filtering `Handler` is a handler that perform some modification to the request or response, and then either forwards the request to another `Handler` or produces an error response: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=handlerFilter] ----- - -Note how a filtering `Handler` extends from `HandlerWrapper` and as such needs another handler to forward the request processing to, and how the two ``Handler``s needs to be linked together to work properly. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler-use.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler-use.adoc deleted file mode 100644 index f89def615678..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler-use.adoc +++ /dev/null @@ -1,412 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http-handler-use]] -===== Jetty Handlers - -Web applications are the unit of deployment in an HTTP server or Servlet container such as Jetty. - -Two different web applications are typically deployed on different __context path__s, where a _context path_ is the initial segment of the URI path. -For example, web application `webappA` that implements a web user interface for an e-commerce site may be deployed to context path `/shop`, while web application `webappB` that implements a REST API for the e-commerce business may be deployed to `/api`. - -A client making a request to URI `/shop/cart` is directed by Jetty to `webappA`, while a request to URI `/api/products` is directed to `webappB`. - -An alternative way to deploy the two web applications of the example above is to use _virtual hosts_. -A _virtual host_ is a subdomain of the primary domain that shares the same IP address with the primary domain. -If the e-commerce business primary domain is `domain.com`, then a virtual host for `webappA` could be `shop.domain.com`, while a virtual host for `webappB` could be `api.domain.com`. - -Web application `webappA` can now be deployed to virtual host `shop.domain.com` and context path `/`, while web application `webappB` can be deployed to virtual host `api.domain.com` and context path `/`. -Both applications have the same context path `/`, but they can be distinguished by the subdomain. - -A client making a request to `+https://shop.domain.com/cart+` is directed by Jetty to `webappA`, while a request to `+https://api.domain.com/products+` is directed to `webappB`. - -Therefore, in general, a web application is deployed to a _context_ which can be seen as the pair `(virtual_host, context_path)`. -In the first case the contexts were `(domain.com, /shop)` and `(domain.com, /api)`, while in the second case the contexts were `(shop.domain.com, /)` and `(api.domain.com, /)`. -Server applications using the Jetty Server Libraries create and configure a _context_ for each web application. -Many __context__s can be deployed together to enrich the web application offering -- for example a catalog context, a shop context, an API context, an administration context, etc. - -Web applications can be written using exclusively the Servlet APIs, since developers know well the Servlet API and because they guarantee better portability across Servlet container implementations. - -Embedded web applications based on the Servlet APIs are described in xref:pg-server-http-handler-use-servlet[this section]. - -Embedded web applications may also require additional features such as access to Jetty specific APIs, or utility features such as redirection from HTTP to HTTPS, support for `gzip` content compression, etc. -The Jetty Server Libraries provides a number of out-of-the-box __Handler__s that implement the most common functionalities and are described in xref:pg-server-http-handler-use[this section]. - -[[pg-server-http-handler-use-util-context]] -====== ContextHandler - -`ContextHandler` is a `Handler` that represents a _context_ for a web application. -It is a `HandlerWrapper` that performs some action before and after delegating to the nested `Handler`. -// TODO: expand on what the ContextHandler does, e.g. ServletContext. - -The simplest use of `ContextHandler` is the following: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=contextHandler] ----- - -The `Handler` tree structure looks like the following: - -[source,screen] ----- -Server -└── ContextHandler /shop - └── ShopHandler ----- - -[[pg-server-http-handler-use-util-context-collection]] -====== ContextHandlerCollection - -Server applications may need to deploy to Jetty more than one web application. - -Recall from the xref:pg-server-http-handler[introduction] that Jetty offers `HandlerCollection` and `HandlerList` that may contain a sequence of children ``Handler``s. -However, both of these have no knowledge of the concept of _context_ and just iterate through the sequence of ``Handler``s. - -A better choice for multiple web application is `ContextHandlerCollection`, that matches a _context_ from either its _context path_ or _virtual host_, without iterating through the ``Handler``s. - -If `ContextHandlerCollection` does not find a match, it just returns. -What happens next depends on the `Handler` tree structure: other ``Handler``s may be invoked after `ContextHandlerCollection`, for example `DefaultHandler` (see xref:pg-server-http-handler-use-util-default-handler[this section]). -Eventually, if `Request.setHandled(true)` is not called, Jetty returns an HTTP `404` response to the client. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=contextHandlerCollection] ----- - -The `Handler` tree structure looks like the following: - -[source,screen] ----- -Server -└── ContextHandlerCollection - ├── ContextHandler /shop - │ └── ShopHandler - └── ContextHandler /api - └── RESTHandler ----- - -[[pg-server-http-handler-use-util-resource-handler]] -====== ResourceHandler -- Static Content - -Static content such as images or files (HTML, JavaScript, CSS) can be sent by Jetty very efficiently because Jetty can write the content asynchronously, using direct ``ByteBuffer``s to minimize data copy, and using a memory cache for faster access to the data to send. - -Being able to write content asynchronously means that if the network gets congested (for example, the client reads the content very slowly) and the server stalls the send of the requested data, then Jetty will wait to resume the send _without_ blocking a thread to finish the send. - -`ResourceHandler` supports the following features: - -* Welcome files, for example serving `/index.html` for request URI `/` -* Precompressed resources, serving a precompressed `/document.txt.gz` for request URI `/document.txt` -* link:https://tools.ietf.org/html/rfc7233[Range requests], for requests containing the `Range` header, which allows clients to pause and resume downloads of large files -* Directory listing, serving a HTML page with the file list of the requested directory -* Conditional headers, for requests containing the `If-Match`, `If-None-Match`, `If-Modified-Since`, `If-Unmodified-Since` headers. - -The number of features supported and the efficiency in sending static content are on the same level as those of common front-end servers used to serve static content such as Nginx or Apache. -Therefore, the traditional architecture where Nginx/Apache was the front-end server used only to send static content and Jetty was the back-end server used only to send dynamic content is somehow obsolete as Jetty can perform efficiently both tasks. -This leads to simpler systems (less components to configure and manage) and more performance (no need to proxy dynamic requests from front-end servers to back-end servers). - -NOTE: It is common to use Nginx/Apache as load balancers, or as rewrite/redirect servers. -We typically recommend link:https://haproxy.org[HAProxy] as load balancer, and Jetty has xref:pg-server-http-handler-use-util-rewrite-handler[rewrite/redirect features] as well. - -This is how you configure a `ResourceHandler` to create a simple file server: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=resourceHandler] ----- - -If you need to serve static resources from multiple directories: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=multipleResourcesHandler] ----- - -If the resource is not found, `ResourceHandler` will not call `Request.setHandled(true)` so what happens next depends on the `Handler` tree structure. -See also xref:pg-server-http-handler-use-util-default-handler[how to use] `DefaultHandler`. - -[[pg-server-http-handler-use-util-gzip-handler]] -====== GzipHandler - -`GzipHandler` provides supports for automatic decompression of compressed request content and automatic compression of response content. - -`GzipHandler` is a `HandlerWrapper` that inspects the request and, if the request matches the `GzipHandler` configuration, just installs the required components to eventually perform decompression of the request content or compression of the response content. -The decompression/compression is not performed until the web application reads request content or writes response content. - -`GzipHandler` can be configured at the server level in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=serverGzipHandler] ----- - -The `Handler` tree structure looks like the following: - -[source,screen] ----- -Server -└── GzipHandler - └── ContextHandlerCollection - ├── ContextHandler 1 - :── ... - └── ContextHandler N ----- - -However, in less common cases, you can configure `GzipHandler` on a per-context basis, for example because you want to configure `GzipHandler` with different parameters for each context, or because you want only some contexts to have compression support: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=contextGzipHandler] ----- - -The `Handler` tree structure looks like the following: - -[source,screen] ----- -Server -└── ContextHandlerCollection - └── ContextHandlerCollection - ├── GzipHandler - │ └── ContextHandler /shop - │ └── ShopHandler - └── ContextHandler /api - └── RESTHandler ----- - -// TODO: does ServletContextHandler really need a special configuration? - -[[pg-server-http-handler-use-util-rewrite-handler]] -====== RewriteHandler - -`RewriteHandler` provides support for URL rewriting, very similarly to link:https://httpd.apache.org/docs/current/mod/mod_rewrite.html[Apache's mod_rewrite] or link:https://nginx.org/en/docs/http/ngx_http_rewrite_module.html[Nginx rewrite module]. - -The Maven artifact coordinates are: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty - jetty-rewrite - {version} - ----- - -`RewriteHandler` can be configured with a set of __rule__s; a _rule_ inspects the request and when it matches it performs some change to the request (for example, changes the URI path, adds/removes headers, etc.). - -The Jetty Server Libraries provide rules for the most common usages, but you can write your own rules by extending the `org.eclipse.jetty.rewrite.handler.Rule` class. - -Please refer to the `jetty-rewrite` module link:{javadoc-url}/org/eclipse/jetty/rewrite/handler/package-summary.html[javadocs] for the complete list of available rules. - -You typically want to configure `RewriteHandler` at the server level, although it is possible to configure it on a per-context basis. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=rewriteHandler] ----- - -The `Handler` tree structure looks like the following: - -[source,screen] ----- -Server -└── RewriteHandler - └── ContextHandlerCollection - ├── ContextHandler 1 - :── ... - └── ContextHandler N ----- - -[[pg-server-http-handler-use-util-stats-handler]] -====== StatisticsHandler - -`StatisticsHandler` gathers and exposes a number of statistic values related to request processing such as: - -* Total number of requests -* Current number of concurrent requests -* Minimum, maximum, average and standard deviation of request processing times -* Number of responses grouped by HTTP code (i.e. how many `2xx` responses, how many `3xx` responses, etc.) -* Total response content bytes - -Server applications can read these values and use them internally, or expose them via some service, or xref:pg-arch-jmx[export them to JMX]. - -`StatisticsHandler` can be configured at the server level or at the context level. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=statsHandler] ----- - -The `Handler` tree structure looks like the following: - -[source,screen] ----- -Server -└── StatisticsHandler - └── ContextHandlerCollection - ├── ContextHandler 1 - :── ... - └── ContextHandler N ----- - -[[pg-server-http-handler-use-util-secure-handler]] -====== SecuredRedirectHandler -- Redirect from HTTP to HTTPS - -`SecuredRedirectHandler` allows to redirect requests made with the `http` scheme (and therefore to the clear-text port) to the `https` scheme (and therefore to the encrypted port). - -For example a request to `+http://domain.com:8080/path?param=value+` is redirected to `+https://domain.com:8443/path?param=value+`. - -Server applications must configure a `HttpConfiguration` object with the secure scheme and secure port so that `SecuredRedirectHandler` can build the redirect URI. - -`SecuredRedirectHandler` is typically configured at the server level, although it can be configured on a per-context basis. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=securedHandler] ----- - -[[pg-server-http-handler-use-util-default-handler]] -====== DefaultHandler - -`DefaultHandler` is a terminal `Handler` that always calls `Request.setHandled(true)` and performs the following: - -* Serves the `favicon.ico` Jetty icon when it is requested -* Sends a HTTP `404` response for any other request -* The HTTP `404` response content nicely shows a HTML table with all the contexts deployed on the `Server` instance - -`DefaultHandler` is best used as the last `Handler` of a `HandlerList`, for example: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=defaultHandler] ----- - -The `Handler` tree structure looks like the following: - -[source,screen] ----- -Server -└── HandlerList - ├── ContextHandlerCollection - │ ├── ContextHandler 1 - │ :── ... - │ └── ContextHandler N - └── DefaultHandler ----- - -In the example above, `ContextHandlerCollection` will try to match a request to one of the contexts; if the match fails, `HandlerList` will call the next `Handler` which is `DefaultHandler` that will return a HTTP `404` with an HTML page showing the existing contexts deployed on the `Server`. - -NOTE: `DefaultHandler` just sends a nicer HTTP `404` response in case of wrong requests from clients. -Jetty will send an HTTP `404` response anyway if `DefaultHandler` is not used. - -[[pg-server-http-handler-use-servlet]] -===== Servlet API Handlers - -[[pg-server-http-handler-use-servlet-context]] -====== ServletContextHandler - -``Handler``s are easy to write, but often web applications have already been written using the Servlet APIs, using ``Servlet``s and ``Filter``s. - -`ServletContextHandler` is a `ContextHandler` that provides support for the Servlet APIs and implements the behaviors required by the Servlet specification. - -The Maven artifact coordinates are: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty - jetty-servlet - {version} - ----- - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=servletContextHandler] ----- - -The `Handler` and Servlet components tree structure looks like the following: - -[source,screen,subs=normal] ----- -Server -└── ServletContextHandler /shop - ├── _ShopCartServlet /cart/*_ - └── _CrossOriginFilter /*_ ----- - -Note how the Servlet components (they are not ``Handler``s) are represented in _italic_. - -Note also how adding a `Servlet` or a `Filter` returns a _holder_ object that can be used to specify additional configuration for that particular `Servlet` or `Filter`. - -When a request arrives to `ServletContextHandler` the request URI will be matched against the ``Filter``s and ``Servlet`` mappings and only those that match will process the request, as dictated by the Servlet specification. - -IMPORTANT: `ServletContextHandler` is a terminal `Handler`, that is it always calls `Request.setHandled(true)` when invoked. -Server applications must be careful when creating the `Handler` tree to put ``ServletContextHandler``s as last ``Handler``s in a `HandlerList` or as children of `ContextHandlerCollection`. - -// TODO: revise what above, as ServletContextHandler is not a terminal handler. -// TODO: introduce the fact that ServletContextHandler can have a class loader that may be used to "isolate" web application classes. - -[[pg-server-http-handler-use-webapp-context]] -====== WebAppContext - -`WebAppContext` is a `ServletContextHandler` that auto configures itself by reading a `web.xml` Servlet configuration file. - -Server applications can specify a `+*.war+` file or a directory with the structure of a `+*.war+` file to `WebAppContext` to deploy a standard Servlet web application packaged as a `war` (as defined by the Servlet specification). - -Where server applications using `ServletContextHandler` must manually invoke methods to add ``Servlet``s and ``Filter``s, `WebAppContext` reads `WEB-INF/web.xml` to add ``Servlet``s and ``Filter``s, and also enforces a number of restrictions defined by the Servlet specification, in particular related to class loading. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=webAppContextHandler] ----- - -[[pg-server-http-handler-use-webapp-context-class-loading]] -.WebAppContext Class Loading - -The Servlet specification requires that a web application class loader must load the web application classes from `WEB-INF/classes` and `WEB_INF/lib`. -The web application class loader is special because it behaves differently from typical class loaders: where typical class loaders first delegate to their parent class loader and then try to find the class locally, the web application class loader first tries to find the class locally and then delegates to the parent class loader. -The typical class loading model, parent-first, is _inverted_ for web application class loaders, as they use a child-first model. - -Furthermore, the Servlet specification requires that web applications cannot load or otherwise access the Servlet container implementation classes, also called _server classes_. -In the Jetty case, the Servlet specification class `javax.servlet.http.HttpServletRequest` is implemented by `org.eclipse.jetty.server.Request`. -Web applications cannot downcast Servlet's `HttpServletRequest` to Jetty's `Request` to access Jetty specific features -- this ensures maximum web application portability across Servlet container implementations. - -Lastly, the Servlet specification requires that other classes, also called _system classes_, such as `javax.servlet.http.HttpServletRequest` or JDK classes such as `java.lang.String` or `java.sql.Connection` cannot be modified by web applications by putting, for example, modified versions of those classes in `WEB-INF/classes` so that they are loaded first by the web application class loader (instead of the class-path class loader where they are normally loaded from). - -`WebAppContext` implements this class loader logic using a single class loader, `org.eclipse.jetty.webapp.WebAppClassLoader`, with filtering capabilities: when it loads a class, it checks whether the class is a _system class_ or a _server class_ and acts according to the Servlet specification. - -When `WebAppClassLoader` is asked to load a class, it first tries to find the class locally (since it must use the inverted child-first model); if the class is found, and it is not a _system class_, the class is loaded; otherwise the class is not found locally. -If the class is not found locally, the parent class loader is asked to load the class; the parent class loader uses the standard parent-first model, so it delegates the class loading to its parent, and so on. -If the class is found, and it is not a _server class_, the class is loaded; otherwise the class is not found and a `ClassNotFoundException` is thrown. - -Unfortunately, the Servlet specification does not define exactly which classes are _system classes_ and which classes are _server classes_. -However, Jetty picks good defaults and allows server applications to customize _system classes_ and _server classes_ in `WebAppContext`. - -// TODO: add a section on parentLoaderPriority. -// TODO: add a code example about how to set system/server classes. -// TODO: add a code example about how to configure extra classpath -// TODO: add a section on ClassLoading (see old docs) - -// TODO: add a section on Configuration (system/server classes) -// TODO: add a section about how to setup JSP support - -[[pg-server-http-handler-use-default-servlet]] -====== DefaultServlet -- Static Content for Servlets - -If you have a xref:pg-server-http-handler-use-servlet-context[Servlet web application], you may want to use a `DefaultServlet` instead of `ResourceHandler`. -The features are similar, but `DefaultServlet` is more commonly used to serve static files for Servlet web applications. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=defaultServlet] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler.adoc deleted file mode 100644 index a73d8e557832..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-handler.adoc +++ /dev/null @@ -1,62 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http-handler]] -==== Server Handlers - -An `org.eclipse.jetty.server.Handler` is the component that processes incoming HTTP requests and eventually produces HTTP responses. - -``Handler``s can be organized in different ways: - -* in a sequence, where ``Handler``s are invoked one after the other -** `HandlerCollection` invokes _all_ ``Handler``s one after the other -** `HandlerList` invokes ``Handlers``s until one calls `Request.setHandled(true)` to indicate that the request has been handled and no further `Handler` should be invoked -* nested, where one `Handler` invokes the next, nested, `Handler` -** `HandlerWrapper` implements this behavior - -The `HandlerCollection` behavior (invoking _all_ handlers) is useful when for example the last `Handler` is a logging `Handler` that logs the request (that may have been modified by previous handlers). - -The `HandlerList` behavior (invoking handlers up to the first that calls `Request.setHandled(true)`) is useful when each handler processes a different URIs or a different virtual hosts: ``Handler``s are invoked one after the other until one matches the URI or virtual host. - -The nested behavior is useful to enrich the request with additional services such as HTTP session support (`SessionHandler`), or with specific behaviors dictated by the Servlet specification (`ServletHandler`). - -``Handler``s can be organized in a tree by composing them together: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=handlerTree] ----- - -The corresponding `Handler` tree structure looks like the following: - -[source,screen] ----- -HandlerCollection -├── HandlerList -│ ├── App1Handler -│ └── HandlerWrapper -│ └── App2Handler -└── LoggingHandler ----- - -Server applications should rarely write custom ``Handler``s, preferring instead to use existing ``Handler``s provided by the Jetty Server Libraries for managing web application contexts, security, HTTP sessions and Servlet support. -Refer to xref:pg-server-http-handler-use[this section] for more information about how to use the ``Handler``s provided by the Jetty Server Libraries. - -However, in some cases the additional features are not required, or additional constraints on memory footprint, or performance, or just simplicity must be met. -In these cases, implementing your own `Handler` may be a better solution. -Refer to xref:pg-server-http-handler-implement[this section] for more information about how to write your own ``Handler``s. - -// TODO: document ScopedHandler? Is this really necessary or just an implementation detail that application will never worry about? - -include::server-http-handler-use.adoc[] -include::server-http-handler-implement.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-security.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-security.adoc deleted file mode 100644 index 682e0f09a501..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http-security.adoc +++ /dev/null @@ -1,19 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http-security]] -===== Securing HTTP Server Applications - -// TODO: ConstraintSecurityHandler and Authenticators and LoginServices -TODO - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http.adoc deleted file mode 100644 index 6c387c1a1ab8..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http/server-http.adoc +++ /dev/null @@ -1,202 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http]] -=== HTTP Server Libraries - -Web application development typically involves writing your web applications, packaging them into a web application archive, the `+*.war+` file, and then deploy the `+*.war+` file into a standalone Servlet Container that you have previously installed. - -The Eclipse Jetty server libraries allow you to write web applications components using either the Jetty APIs (by writing xref:pg-server-http-handler[Jetty ``Handler``s]) or using the standard xref:pg-server-http-handler-use-servlet[Servlet APIs] (by writing ``Servlet``s and Servlet ``Filter``s). -These components can then be programmatically assembled together, without the need of creating a `+*.war+` file, added to a Jetty ``Server`` instance that is then started. -This result in your web applications to be available to HTTP clients as if you deployed your `+*.war+` files in a standalone Jetty server. - -The Maven artifact coordinates are: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty - jetty-server - {version} - ----- - -An `org.eclipse.jetty.server.Server` instance is the central component that links together a collection of ``Connector``s and a collection of ``Handler``s, with threads from a `ThreadPool` doing the work. - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam padding 5 - -scale 1.5 - -hide members -hide circle - -Server - ThreadPool -Connectors - Server -Server -- Handlers ----- - -The components that accept connections from clients are `org.eclipse.jetty.server.Connector` implementations. - -When a Jetty server interprets the HTTP protocol (HTTP/1.1, HTTP/2 or HTTP/3), it uses `org.eclipse.jetty.server.Handler` instances to process incoming requests and eventually produce responses. - -A `Server` must be created, configured and started: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=simple] ----- - -The example above shows the simplest HTTP/1.1 server; it has no support for HTTP sessions, for HTTP authentication, or for any of the features required by the Servlet specification. - -All these features are provided by the Jetty Server Libraries, and server applications only need to put the required components together to provide all the required features. - -The ``Handler``s provided by the Jetty Server Libraries allow writing server applications that have functionalities similar to Apache HTTPD or Nginx (for example: URL redirection, URL rewriting, serving static content, reverse proxying, etc.), as well as generating content dynamically by processing incoming requests. -Read xref:pg-server-http-handler[this section] for further details about ``Handler``s. - -If you are interested in writing your server application based on the Servlet APIs, jump to xref:pg-server-http-handler-use-servlet[this section]. - -[[pg-server-http-request-processing]] -==== Request Processing - -The Jetty HTTP request processing is outlined below in the diagram below. -You may want to refer to the xref:pg-arch-io[Jetty I/O architecture] for additional information about the classes mentioned below. - -Request handing is slightly different for each protocol; in HTTP/2 Jetty takes into account multiplexing, something that is not present in HTTP/1.1. - -However, the diagram below captures the essence of request handling that is common among all protocols that carry HTTP requests. - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false - -participant ManagedSelector -participant EndPoint -participant Connection -participant Parser -participant HttpChannel -participant Server -participant Handlers - -ManagedSelector -> EndPoint : read ready -EndPoint -> Connection : onFillable() -Connection -> EndPoint : fill() -EndPoint --> Connection -Connection -> Parser : parse() -Parser -> HttpChannel : events -Connection -> HttpChannel : handle() -HttpChannel -> Server : handle() -Server -> Handlers : handle() ----- - -First, the Jetty I/O layer emits an event that a socket has data to read. -This event is converted to a call to `AbstractConnection.onFillable()`, where the `Connection` first reads from the `EndPoint` into a `ByteBuffer`, and then calls a protocol specific parser to parse the bytes in the `ByteBuffer`. - -The parser emit events that are protocol specific; the HTTP/2 parser, for example, emits events for each HTTP/2 frame that has been parsed, and similarly does the HTTP/3 parser. -The parser events are then converted to protocol independent events such as _"request start"_, _"request headers"_, _"request content chunk"_, etc. -that in turn are converted into method calls to `HttpChannel`. - -When enough of the HTTP request is arrived, the `Connection` calls `HttpChannel.handle()` that calls the `Handler` chain, that eventually calls the server application code. - -[[pg-server-http-channel-events]] -===== HttpChannel Events - -The central component processing HTTP requests is `HttpChannel`. -There is a 1-to-1 relationship between an HTTP request/response and an `HttpChannel`, no matter what is the specific protocol that carries the HTTP request over the network (HTTP/1.1, HTTP/2, HTTP/3 or FastCGI). - -Advanced server applications may be interested in the progress of the processing of an HTTP request/response by `HttpChannel`. -A typical case is to know exactly _when_ the HTTP request/response processing is complete, for example to monitor processing times. - -NOTE: A `Handler` or a Servlet `Filter` may not report precisely when an HTTP request/response processing is finished. -A server application may write a small enough content that is aggregated by Jetty for efficiency reasons; the write returns immediately, but nothing has been written to the network yet. - -`HttpChannel` notifies ``HttpChannel.Listener``s of the progress of the HTTP request/response handling. -Currently, the following events are available: - -* `requestBegin` -* `beforeDispatch` -* `dispatchFailure` -* `afterDispatch` -* `requestContent` -* `requestContentEnd` -* `requestTrailers` -* `requestEnd` -* `responseBegin` -* `responseCommit` -* `responseContent` -* `responseFailure` -* `responseEnd` -* `complete` - -Please refer to the `HttpChannel.Listener` link:{javadoc-url}/org/eclipse/jetty/server/HttpChannel.Listener.html[javadocs] for the complete list of events. - -Server applications can register `HttpChannel.Listener` by adding them as xref:pg-arch-bean[beans] to the `Connector`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=httpChannelListener] ----- - -[[pg-server-http-request-logging]] -==== Request Logging - -HTTP requests and responses can be logged to provide data that can be later analyzed with other tools. -These tools can provide information such as the most frequently accessed request URIs, the response status codes, the request/response content lengths, geographical information about the clients, etc. - -The default request/response log line format is the link:https://en.wikipedia.org/wiki/Common_Log_Format[NCSA Format] extended with referrer data and user-agent data. - -[NOTE] -==== -Typically, the extended NCSA format is the is enough and it's the standard used and understood by most log parsing tools and monitoring tools. - -To customize the request/response log line format see the link:{javadoc-url}/org/eclipse/jetty/server/CustomRequestLog.html[`CustomRequestLog` javadocs]. -==== - -Request logging can be enabled at the server level, or at the web application context level. - -The request logging output can be directed to an SLF4J logger named `"org.eclipse.jetty.server.RequestLog"` at `INFO` level, and therefore to any logging library implementation of your choice (see also xref:pg-troubleshooting-logging[this section] about logging). - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=serverRequestLogSLF4J] ----- - -Alternatively, the request logging output can be directed to a daily rolling file of your choice, and the file name must contain `yyyy_MM_dd` so that rolled over files retain their date: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=serverRequestLogFile] ----- - -For maximum flexibility, you can log to multiple ``RequestLog``s using class `RequestLog.Collection`, for example by logging with different formats or to different outputs. - -You can use `CustomRequestLog` with a custom `RequestLog.Writer` to direct the request logging output to your custom targets (for example, an RDBMS). -You can implement your own `RequestLog` if you want to have functionalities that are not implemented by `CustomRequestLog`. - -Request logging can also be enabled at the web application context level, using `RequestLogHandler` (see xref:pg-server-http-handler[this section] about how to organize Jetty ``Handler``s) to wrap a web application `Handler`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java[tags=contextRequestLog] ----- - -include::server-http-connector.adoc[] -include::server-http-handler.adoc[] -include::server-http-security.adoc[] -include::server-http-application.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http2/server-http2.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http2/server-http2.adoc deleted file mode 100644 index 9cbcec7acf00..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http2/server-http2.adoc +++ /dev/null @@ -1,143 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http2]] -=== HTTP/2 Server Library - -In the vast majority of cases, server applications should use the generic, high-level, xref:pg-server-http[HTTP server library] that also provides HTTP/2 support via the HTTP/2 ``ConnectionFactory``s as described in details xref:pg-server-http-connector-protocol-http2[here]. - -The low-level HTTP/2 server library has been designed for those applications that need low-level access to HTTP/2 features such as _sessions_, _streams_ and _frames_, and this is quite a rare use case. - -See also the correspondent xref:pg-client-http2[HTTP/2 client library]. - -[[pg-server-http2-intro]] -==== Introduction - -The Maven artifact coordinates for the HTTP/2 client library are the following: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.http2 - http2-server - {version} - ----- - -include::../../http2.adoc[tag=multiplex] - -[[pg-server-http2-flow-control]] -==== HTTP/2 Flow Control - -include::../../http2.adoc[tag=flowControl] - -How a server application should handle HTTP/2 flow control is discussed in details in xref:pg-server-http2-request[this section]. - -[[pg-server-http2-setup]] -==== Server Setup - -The low-level HTTP/2 support is provided by `org.eclipse.jetty.http2.server.RawHTTP2ServerConnectionFactory` and `org.eclipse.jetty.http2.api.server.ServerSessionListener`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java[tags=setup] ----- - -Where server applications using the xref:pg-server-http[high-level server library] deal with HTTP requests and responses in ``Handler``s, server applications using the low-level HTTP/2 server library deal directly with HTTP/2 __session__s, __stream__s and __frame__s in a `ServerSessionListener` implementation. - -The `ServerSessionListener` interface defines a number of methods that are invoked by the implementation upon the occurrence of HTTP/2 events, and that server applications can override to react to those events. - -Please refer to the `ServerSessionListener` link:{javadoc-url}/org/eclipse/jetty/http2/api/server/ServerSessionListener.html[javadocs] for the complete list of events. - -The first event is the _accept_ event and happens when a client opens a new TCP connection to the server and the server accepts the connection. -This is the first occasion where server applications have access to the HTTP/2 `Session` object: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java[tags=accept] ----- - -After connecting to the server, a compliant HTTP/2 client must send the link:https://tools.ietf.org/html/rfc7540#section-3.5[HTTP/2 client preface], and when the server receives it, it generates the _preface_ event on the server. -This is where server applications can customize the connection settings by returning a map of settings that the implementation will send to the client: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java[tags=preface] ----- - -[[pg-server-http2-request]] -==== Receiving a Request - -Receiving an HTTP request from the client, and sending a response, creates a _stream_ that encapsulates the exchange of HTTP/2 frames that compose the request and the response. - -An HTTP request is made of a `HEADERS` frame, that carries the request method, the request URI and the request headers, and optional `DATA` frames that carry the request content. - -Receiving the `HEADERS` frame opens the `Stream`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java[tags=request] ----- - -Server applications should return a `Stream.Listener` implementation from `onNewStream(...)` to be notified of events generated by the client, such as `DATA` frames carrying request content, or a `RST_STREAM` frame indicating that the client wants to _reset_ the request, or an idle timeout event indicating that the client was supposed to send more frames but it did not. - -The example below shows how to receive request content: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java[tags=requestContent] ----- - -include::../../http2.adoc[tag=apiFlowControl] - -[[pg-server-http2-response]] -==== Sending a Response - -After receiving an HTTP request, a server application must send an HTTP response. - -An HTTP response is typically composed of a `HEADERS` frame containing the HTTP status code and the response headers, and optionally one or more `DATA` frames containing the response content bytes. - -The HTTP/2 protocol also supports response trailers (that is, headers that are sent after the response content) that also are sent using a `HEADERS` frame. - -A server application can send a response in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java[tags=response;!exclude] ----- - -[[pg-server-http2-reset]] -==== Resetting a Request - -A server application may decide that it does not want to accept the request. -For example, it may throttle the client because it sent too many requests in a time window, or the request is invalid (and does not deserve a proper HTTP response), etc. - -A request can be reset in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java[tags=reset;!exclude] ----- - -[[pg-server-http2-push]] -==== HTTP/2 Push of Resources - -A server application may _push_ secondary resources related to a primary resource. - -A client may inform the server that it does not accept pushed resources(see link:https://tools.ietf.org/html/rfc7540#section-8.2[this section] of the specification) via a `SETTINGS` frame. -Server applications must track `SETTINGS` frames and verify whether the client supports HTTP/2 push, and only push if the client supports it: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java[tags=push] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http3/server-http3.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http3/server-http3.adoc deleted file mode 100644 index b39e2d661e1b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/http3/server-http3.adoc +++ /dev/null @@ -1,146 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-http3]] -=== HTTP/3 Server Library - -In the vast majority of cases, server applications should use the generic, high-level, xref:pg-server-http[HTTP server library] that also provides HTTP/3 support via the HTTP/3 connector and ``ConnectionFactory``s as described in details xref:pg-server-http-connector-protocol-http3[here]. - -The low-level HTTP/3 server library has been designed for those applications that need low-level access to HTTP/3 features such as _sessions_, _streams_ and _frames_, and this is quite a rare use case. - -See also the correspondent xref:pg-client-http3[HTTP/3 client library]. - -[[pg-server-http3-intro]] -==== Introduction - -The Maven artifact coordinates for the HTTP/3 client library are the following: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.http3 - http3-server - {version} - ----- - -include::../../http3.adoc[tag=multiplex] - -// TODO: flow control? -//[[pg-server-http3-flow-control]] -//==== HTTP/3 Flow Control -// -//include::../../http3.adoc[tag=flowControl] -// -//How a server application should handle HTTP/3 flow control is discussed in details in xref:pg-server-http3-request[this section]. - -[[pg-server-http3-setup]] -==== Server Setup - -The low-level HTTP/3 support is provided by `org.eclipse.jetty.http3.server.RawHTTP3ServerConnectionFactory` and `org.eclipse.jetty.http3.api.Session.Server.Listener`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java[tags=setup] ----- - -Where server applications using the xref:pg-server-http[high-level server library] deal with HTTP requests and responses in ``Handler``s, server applications using the low-level HTTP/3 server library deal directly with HTTP/3 __session__s, __stream__s and __frame__s in a `Session.Server.Listener` implementation. - -The `Session.Server.Listener` interface defines a number of methods that are invoked by the implementation upon the occurrence of HTTP/3 events, and that server applications can override to react to those events. - -Please refer to the `Session.Server.Listener` link:{javadoc-url}/org/eclipse/jetty/http3/api/Session.Server.Listener.html[javadocs] for the complete list of events. - -The first event is the _accept_ event and happens when a client opens a new QUIC connection to the server and the server accepts the connection. -This is the first occasion where server applications have access to the HTTP/3 `Session` object: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java[tags=accept] ----- - -After the QUIC connection has been established, both client and server send an HTTP/3 `SETTINGS` frame to exchange their HTTP/3 configuration. -This generates the _preface_ event, where applications can customize the HTTP/3 settings by returning a map of settings that the implementation will send to the other peer: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java[tags=preface] ----- - -[[pg-server-http3-request]] -==== Receiving a Request - -Receiving an HTTP request from the client, and sending a response, creates a _stream_ that encapsulates the exchange of HTTP/3 frames that compose the request and the response. - -An HTTP request is made of a `HEADERS` frame, that carries the request method, the request URI and the request headers, and optional `DATA` frames that carry the request content. - -Receiving the `HEADERS` frame opens the `Stream`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java[tags=request] ----- - -Server applications should return a `Stream.Server.Listener` implementation from `onRequest(...)` to be notified of events generated by the client, such as `DATA` frames carrying request content, or a reset event indicating that the client wants to _reset_ the request, or an idle timeout event indicating that the client was supposed to send more frames but it did not. - -The example below shows how to receive request content: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java[tags=requestContent] ----- - -// TODO: flow control? -//include::../../http3.adoc[tag=apiFlowControl] - -[[pg-server-http3-response]] -==== Sending a Response - -After receiving an HTTP request, a server application must send an HTTP response. - -An HTTP response is typically composed of a `HEADERS` frame containing the HTTP status code and the response headers, and optionally one or more `DATA` frames containing the response content bytes. - -The HTTP/3 protocol also supports response trailers (that is, headers that are sent after the response content) that also are sent using a `HEADERS` frame. - -A server application can send a response in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java[tags=response;!exclude] ----- - -[[pg-server-http3-reset]] -==== Resetting a Request - -A server application may decide that it does not want to accept the request. -For example, it may throttle the client because it sent too many requests in a time window, or the request is invalid (and does not deserve a proper HTTP response), etc. - -A request can be reset in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java[tags=reset;!exclude] ----- - -// TODO: push not yet implemented in HTTP/3. -//[[pg-server-http3-push]] -//==== HTTP/3 Push of Resources -// -//A server application may _push_ secondary resources related to a primary resource. -// -//A client may inform the server that it does not accept pushed resources(see link:https://tools.ietf.org/html/rfc7540#section-8.2[this section] of the specification) via a `SETTINGS` frame. -//Server applications must track `SETTINGS` frames and verify whether the client supports HTTP/3 push, and only push if the client supports it: -// -//[source,java,indent=0] -//---- -//include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java[tags=push] -//---- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/server-io-arch.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/server-io-arch.adoc deleted file mode 100644 index b8d207b36a11..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/server-io-arch.adoc +++ /dev/null @@ -1,224 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-io-arch]] -=== Server I/O Architecture - -The Jetty server libraries provide the basic components and APIs to implement a network server. - -They build on the common xref:pg-arch-io[Jetty I/O Architecture] and provide server specific concepts. - -The Jetty server libraries provide I/O support for TCP/IP sockets (for both IPv4 and IPv6) and, when using Java 16 or later, for Unix-Domain sockets. - -Support for Unix-Domain sockets is interesting when Jetty is deployed behind a proxy or a load-balancer: it is possible to configure the proxy or load balancer to communicate with Jetty via Unix-Domain sockets, rather than via the loopback network interface. - -The central I/O server-side component are `org.eclipse.jetty.server.ServerConnector`, that handles the TCP/IP socket traffic, and `org.eclipse.jetty.unixdomain.server.UnixDomainServerConnector`, that handles the Unix-Domain socket traffic. - -`ServerConnector` and `UnixDomainServerConnector` are very similar, and while in the following sections `ServerConnector` is used, the same concepts apply to `UnixDomainServerConnector`, unless otherwise noted. - -A `ServerConnector` manages a list of ``ConnectionFactory``s, that indicate what protocols the connector is able to speak. - -[[pg-server-io-arch-connection-factory]] -==== Creating Connections with `ConnectionFactory` - -Recall from the xref:pg-arch-io-connection[`Connection` section] of the Jetty I/O architecture that `Connection` instances are responsible for parsing bytes read from a socket and generating bytes to write to that socket. - -On the server-side, a `ConnectionFactory` creates `Connection` instances that know how to parse and generate bytes for the specific protocol they support -- it can be either HTTP/1.1, or TLS, or FastCGI, or the link:https://www.haproxy.org/download/2.1/doc/proxy-protocol.txt[PROXY protocol]. - -For example, this is how clear-text HTTP/1.1 is configured for TCP/IP sockets: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=http] ----- - -With this configuration, the `ServerConnector` will listen on port `8080`. - -Similarly, this is how clear-text HTTP/1.1 is configured for Unix-Domain sockets: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=httpUnix] ----- - -With this configuration, the `UnixDomainServerConnector` will listen on file `/tmp/jetty.sock`. - -[NOTE] -==== -`ServerConnector` and `UnixDomainServerConnector` only differ by how they are configured -- for `ServerConnector` you specify the IP port it listens to, for `UnixDomainServerConnector` you specify the Unix-Domain path it listens to. - -Both configure ``ConnectionFactory``s in exactly the same way. -==== - -When a new socket connection is established, `ServerConnector` delegates to the `ConnectionFactory` the creation of the `Connection` instance for that socket connection, that is linked to the corresponding `EndPoint`: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam padding 5 - -hide members -hide circle - -scale 1.5 - -circle network -circle application - -network - SocketChannelEndPoint -SocketChannelEndPoint - HttpConnection -HttpConnection - application ----- - -For every socket connection there will be an `EndPoint` + `Connection` pair. - -[[pg-server-io-arch-connection-factory-wrapping]] -==== Wrapping a `ConnectionFactory` - -A `ConnectionFactory` may wrap another `ConnectionFactory`; for example, the TLS protocol provides encryption for any other protocol. -Therefore, to support encrypted HTTP/1.1 (also known as `https`), you need to configure the `ServerConnector` with two ``ConnectionFactory``s -- one for the TLS protocol and one for the HTTP/1.1 protocol, like in the example below: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=tlsHttp] ----- - -With this configuration, the `ServerConnector` will listen on port `8443`. -When a new socket connection is established, the first `ConnectionFactory` configured in `ServerConnector` is invoked to create a `Connection`. -In the example above, `SslConnectionFactory` creates a `SslConnection` and then asks to its wrapped `ConnectionFactory` (in the example, `HttpConnectionFactory`) to create the wrapped `Connection` (an `HttpConnection`) and will then link the two ``Connection``s together, in this way: - -[plantuml] ----- -skinparam backgroundColor transparent -skinparam monochrome true -skinparam shadowing false -skinparam padding 5 - -hide members -hide circle - -scale 1.5 - -circle network -circle application - -network - SocketChannelEndPoint -SocketChannelEndPoint - SslConnection -SslConnection -- DecryptedEndPoint -DecryptedEndPoint - HttpConnection -HttpConnection - application ----- - -Bytes read by the `SocketChannelEndPoint` will be interpreted as TLS bytes by the `SslConnection`, then decrypted and made available to the `DecryptedEndPoint` (a component part of `SslConnection`), which will then provide them to `HttpConnection`. - -The application writes bytes through the `HttpConnection` to the `DecryptedEndPoint`, which will encrypt them through the `SslConnection` and write the encrypted bytes to the `SocketChannelEndPoint`. - -[[pg-server-io-arch-connection-factory-detecting]] -==== Choosing `ConnectionFactory` via Bytes Detection - -Typically, a network port is associated with a specific protocol. -For example, port `80` is associated with clear-text HTTP, while port `443` is associated with encrypted HTTP (that is, the TLS protocol wrapping the HTTP protocol, also known as `https`). - -In certain cases, applications need to listen to the same port for two or more protocols, or for different but incompatible versions of the same protocol, which can only be distinguished by reading the initial bytes and figuring out to what protocol they belong to. - -The Jetty server libraries support this case by placing a `DetectorConnectionFactory` in front of other ``ConnectionFactory``s. -`DetectorConnectionFactory` accepts a list of ``ConnectionFactory``s that implement `ConnectionFactory.Detecting`, which will be called to see if one of them recognizes the initial bytes. - -In the example below you can see how to support both clear-text and encrypted HTTP/1.1 (i.e. both `http` and `https`) _on the same network port_: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=detector] ----- - -<1> Creates the `DetectorConnectionFactory` with the `SslConnectionFactory` as the only detecting `ConnectionFactory`. -With this configuration, the detector will delegate to `SslConnectionFactory` to recognize the initial bytes, which will detect whether the bytes are TLS protocol bytes. -<2> Creates the `ServerConnector` with `DetectorConnectionFactory` as the first `ConnectionFactory`, and `HttpConnectionFactory` as the next `ConnectionFactory` to invoke if the detection fails. - -In the example above `ServerConnector` will listen on port 8181. -When a new socket connection is established, `DetectorConnectionFactory` is invoked to create a `Connection`, because it is the first `ConnectionFactory` specified in the `ServerConnector` list. -`DetectorConnectionFactory` reads the initial bytes and asks to its detecting ``ConnectionFactory``s if they recognize the bytes. -In the example above, the detecting ``ConnectionFactory`` is `SslConnectionFactory` which will therefore detect whether the initial bytes are TLS bytes. -If one of the detecting ``ConnectionFactory``s recognizes the bytes, it creates a `Connection`; otherwise `DetectorConnectionFactory` will try the next `ConnectionFactory` after itself in the `ServerConnector` list. -In the example above, the next `ConnectionFactory` after `DetectorConnectionFactory` is `HttpConnectionFactory`. - -The final result is that when new socket connection is established, the initial bytes are examined: if they are TLS bytes, a `SslConnectionFactory` will create a `SslConnection` that wraps an `HttpConnection` as explained xref:pg-server-io-arch-connection-factory-wrapping[here], therefore supporting `https`; otherwise they are not TLS bytes and an `HttpConnection` is created, therefore supporting `http`. - -[[pg-server-io-arch-connection-factory-custom]] -==== Writing a Custom `ConnectionFactory` - -This section explains how to use the Jetty server-side libraries to write a generic network server able to parse and generate any protocol.. - -Let's suppose that we want to write a custom protocol that is based on JSON but has the same semantic as HTTP; let's call this custom protocol `JSONHTTP`, so that a request would look like this: - -[source,json] ----- -{ - "type": "request", - "method": "GET", - "version": "HTTP/1.1", - "uri": "http://localhost/path", - "fields": { - "content-type": "text/plain;charset=ASCII" - }, - "content": "HELLO" -} ----- - -In order to implement this custom protocol, we need to: - -* implement a `JSONHTTPConnectionFactory` -* implement a `JSONHTTPConnection` -* parse bytes and generate bytes in the `JSONHTTP` format -* design an easy to use API that applications use to process requests and respond - -First, the `JSONHTTPConnectionFactory`: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=jsonHttpConnectionFactory] ----- - -Note how `JSONHTTPConnectionFactory` extends `AbstractConnectionFactory` to inherit facilities common to all `ConnectionFactory` implementations. - -Second, the `JSONHTTPConnection`. -Recall from the xref:pg-arch-io-echo[echo `Connection` example] that you need to override `onOpen()` to call `fillInterested()` so that the Jetty I/O system will notify your `Connection` implementation when there are bytes to read by calling `onFillable()`. -Furthermore, because the Jetty libraries are non-blocking and asynchronous, you need to use `IteratingCallback` to implement `onFillable()`: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=jsonHttpConnection] ----- - -Again, note how `JSONHTTPConnection` extends `AbstractConnection` to inherit facilities that you would otherwise need to re-implement from scratch. - -When `JSONHTTPConnection` receives a full JSON object it calls `invokeApplication(...)` to allow the application to process the incoming request and produce a response. - -At this point you need to design a non-blocking asynchronous API that takes a `Callback` parameter so that applications can signal to the implementation when the request processing is complete (either successfully or with a failure). - -A simple example of this API design could be the following: - -* Wrap the JSON `Map` into a `JSONHTTPRequest` parameter so that applications may use more specific HTTP APIs such as `JSONHTTPRequest.getMethod()` rather than a generic `Map.get("method")` -* Provide an equivalent `JSONHTTPResponse` parameter so that applications may use more specific APIs such as `JSONHTTPResponse.setStatus(int)` rather than a generic `Map.put("status", 200)` -* Provide a `Callback` (or a `CompletableFuture`) parameter so that applications may indicate when the request processing is complete - -This results in the following API: - -[source,java,indent=0] ----- -include::../{doc_code}/org/eclipse/jetty/docs/programming/server/ServerDocs.java[tags=jsonHttpAPI] ----- - -The important part of this simple API example is the `Callback` parameter that makes the API non-blocking and asynchronous. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/server.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/server.adoc deleted file mode 100644 index 38ba7efe456b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/server.adoc +++ /dev/null @@ -1,39 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server]] -== Server Libraries - -The Eclipse Jetty Project provides server-side libraries that allow you to configure and start programmatically an HTTP or WebSocket server from a main class, or embed it in your existing application. -A typical example is a HTTP server that needs to expose a REST endpoint. -Another example is a proxy application that receives HTTP requests, processes them, and then forwards them to third party services, for example using the Jetty xref:pg-client[client libraries]. - -While historically Jetty is an HTTP server, it is possible to use the Jetty server-side libraries to write a generic network server that interprets any network protocol (not only HTTP). -If you are interested in the low-level details of how the Eclipse Jetty server libraries work, or are interested in writing a custom protocol, look at the xref:pg-server-io-arch[Server I/O Architecture]. - -The Jetty server-side libraries provide: - -* HTTP support for HTTP/1.0, HTTP/1.1, HTTP/2, clear-text or encrypted, HTTP/3, for applications that want to embed Jetty as a generic HTTP server or proxy, via the xref:pg-server-http[HTTP libraries] -* HTTP/2 low-level support, for applications that want to explicitly handle low-level HTTP/2 _sessions_, _streams_ and _frames_, via the xref:pg-server-http2[HTTP/2 libraries] -* HTTP/3 low-level support, for applications that want to explicitly handle low-level HTTP/3 _sessions_, _streams_ and _frames_, via the xref:pg-server-http3[HTTP/3 libraries] -* WebSocket support, for applications that want to embed a WebSocket server, via the xref:pg-server-websocket[WebSocket libraries] -* FCGI support, to delegate requests to python or similar scripting languages. - -include::compliance/server-compliance.adoc[] -include::http/server-http.adoc[] -include::http2/server-http2.adoc[] -include::http3/server-http3.adoc[] -include::sessions/sessions.adoc[] -include::websocket/server-websocket.adoc[] -include::fastcgi/server-fastcgi.adoc[] -include::server-io-arch.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-architecture.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-architecture.adoc deleted file mode 100644 index 3a1568459b25..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-architecture.adoc +++ /dev/null @@ -1,61 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-architecture]] -==== Session Architecture - -Terminology:: -SessionIdManager::: is responsible for allocation of session ids -HouseKeeper::: is responsible for orchestrating the detection and removal of expired sessions -SessionHandler::: is responsible for managing the lifecycle of sessions within its associated context -SessionCache::: is an L1 cache of in-use `Session` objects -Session::: is a stateful object representing a `HttpSession` -SessionData::: encapsulates the attributes and metadata associated with a `Session` -SessionDataStore::: is responsible for creating, storing and reading `SessionData` -CachingSessionDataStore::: is an L2 cache of `SessionData` - -The session architecture can be represented like so: - -[plantuml] ----- -title Session Composition Diagram -class Server - -interface SessionIdManager - -class HouseKeeper - -class SessionHandler - -interface SessionCache - -interface SessionDataStore - -class CachingSessionDataStore - -class Session - -class SessionData - -Server "1" *-down- "1" SessionIdManager -SessionIdManager "1" *-left- "1" HouseKeeper -Server "1" *-down- "n" SessionHandler -SessionHandler "1" *-down- "1" SessionCache -SessionCache "1" *-down- "1" SessionDataStore -SessionCache o-down- Session -Session "1" *-- "1" SessionData -SessionDataStore --> SessionData: CRUD -SessionDataStore <|-- CachingSessionDataStore -CachingSessionDataStore o- SessionData ----- - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-cachingsessiondatastore.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-cachingsessiondatastore.adoc deleted file mode 100644 index 001e889481d1..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-cachingsessiondatastore.adoc +++ /dev/null @@ -1,42 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-cachingsessiondatastore]] -===== The CachingSessionDataStore - -[plantuml] ----- -interface SessionDataMap -class CachingSessionDataStore -interface SessionDataStore - -CachingSessionDataStore "1" *-down- "1" SessionDataMap -CachingSessionDataStore "1" *-down- "1" SessionDataStore -SessionDataMap <|-- MemcachedSessionDataMap ----- - -The link:{javadoc-url}/org/eclipse/jetty/server/session/CachingSessionDataStore.html[CachingSessionDataStore] is a special type of `SessionDataStore` that checks an L2 cache for `SessionData` before checking a delegate `SessionDataStore`. -This can improve the performance of slow stores. - -The L2 cache is an instance of a link:{javadoc-url}/org/eclipse/jetty/server/session/SessionDataMap.html[SessionDataMap]. -Jetty provides one implementation of this L2 cache based on `memcached`, link:{javadoc-url}/org/eclipse/jetty/memcached/session/MemcachedSessionDataMap.html[MemcachedSessionDataMap]. - -====== Configuration - -Here's an example of how to programmatically configure ``CachingSessionDataStore``s, using a xref:pg-server-session-datastore-file[FileSessionDataStore] as a delegate, and `memcached` as the L2 cache: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=cachingsds] ----- - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessioncache.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessioncache.adoc deleted file mode 100644 index 7de873e0cd4f..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessioncache.adoc +++ /dev/null @@ -1,153 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-cache]] -==== The SessionCache - -There is one `SessionCache` per `SessionHandler`, and thus one per context. -Its purpose is to provide an L1 cache of `Session` objects. -Having a working set of `Session` objects in memory allows multiple simultaneous requests for the same session to share the same `Session` object. -A `SessionCache` uses a `SessionDataStore` to create, read, store and delete the `SessionData` associated with the `Session`. - -There are two ways to create a `SessionCache` for a `SessionHandler`: - -. allow the `SessionHandler` to create one lazily at startup. -The `SessionHandler` looks for a `SessionCacheFactory` bean on the server to produce the `SessionCache` instance. -It then looks for a `SessionDataStoreFactory` bean on the server to produce a `SessionDataStore` instance to use with the `SessionCache`. - -. pass a fully configured `SessionCache` instance to the `SessionHandler`. -You are responsible for configuring both the `SessionCache` instance and its `SessionDataStore` - -More on ``SessionDataStore``s xref:pg-server-session-datastore[later], in this section we will concentrate on the `SessionCache` and `SessionCacheFactory`. - - -The link:{javadoc-url}/org/eclipse/jetty/server/session/AbstractSessionCache.html[AbstractSessionCache] provides most of the behaviour of ``SessionCache``s. -If you are implementing a custom `SessionCache` we strongly recommend you extend this base class, as the Servlet Specification has many subtleties and extending the base class ensures that your implementation will take account of them. - -Some of the important behaviours of ``SessionCache``s are: - -eviction:: -By default, sessions remain in a cache until they are expired or invalidated. -If you have many or large sessions that are infrequently referenced you can use eviction to reduce the memory consumed by the cache. -When a session is evicted, it is removed from the cache but it is _not_ invalidated. -If you have configured a `SessionDataStore` that persists or distributes the session in some way, it will continue to exist, and can be read back in when it needs to be referenced again. -The eviction strategies are: - NEVER_EVICT::: - This is the default, sessions remain in the cache until expired or invalidated. - EVICT_ON_SESSION_EXIT::: - When the last simultaneous request for a session finishes, the session will be evicted from the cache. - EVICT_ON_INACTIVITY::: - If a session has not been referenced for a configurable number of seconds, then it will be evicted from the cache. - -saveOnInactiveEviction:: -This controls whether a session will be persisted to the `SessionDataStore` if it is being evicted due to the EVICT_ON_INACTIVITY policy. -Usually sessions are written to the `SessionDataStore` whenever the last simultaneous request exits the session. -However, as `SessionDataStores` can be configured to xref:pg-server-session-datastore-skip[skip some writes], this option ensures that the session will be written out. - -saveOnCreate:: -Usually a session will be written through to the configured `SessionDataStore` when the last request for it finishes. -In the case of a freshly created session, this means that it will not be persisted until the request is fully finished. -If your application uses context forwarding or including, the newly created session id will not be available in the subsequent contexts. -You can enable this feature to ensure that a freshly created session is immediately persisted after creation: in this way the session id will be available for use in other contexts accessed during the same request. - -removeUnloadableSessions:: -If a session becomes corrupted in the persistent store, it cannot be re-loaded into the `SessionCache`. -This can cause noisy log output during scavenge cycles, when the same corrupted session fails to load over and over again. -To prevent his, enable this feature and the `SessionCache` will ensure that if a session fails to be loaded, it will be deleted. - -invalidateOnShutdown:: -Some applications want to ensure that all cached sessions are removed when the server shuts down. -This option will ensure that all cached sessions are invalidated. -The `AbstractSessionCache` does not implement this behaviour, a subclass must implement the link:{javadoc-url}/org/eclipse/jetty/server/session/SessionCache.html#shutdown()[SessionCache.shutdown()] method. - -flushOnResponseCommit:: -This forces a "dirty" session to be written to the `SessionDataStore` just before a response is returned to the client, rather than waiting until the request is finished. -A "dirty" session is one whose attributes have changed, or it has been freshly created. -Using this option ensures that all subsequent requests - either to the same or a different node - will see the latest changes to the session. - -Jetty provides two `SessionCache` implementations: the link:{javadoc-url}/org/eclipse/jetty/server/session/DefaultSessionCache.html[DefaultSessionCache] and the link:{javadoc-url}/org/eclipse/jetty/server/session/NullSessionCache.html[NullSessionCache]. - -[[pg-server-session-hash]] -===== The DefaultSessionCache - -The link:{javadoc-url}/org/eclipse/jetty/server/session/DefaultSessionCache.html[DefaultSessionCache] retains `Session` objects in memory in a `ConcurrentHashMap`. -It is suitable for non-clustered and clustered deployments. -For clustered deployments, a sticky load balancer is *strongly* recommended, otherwise you risk indeterminate session state as the session bounces around multiple nodes. - -It implements the link:{javadoc-url}/org/eclipse/jetty/server/session/SessionCache.html#shutdown()[SessionCache.shutdown()] method. - -It also provides some statistics on sessions, which are convenient to access either directly in code or remotely via jmx: - -current sessions:: -The link:{javadoc-url}/org/eclipse/jetty/server/session/DefaultSessionCache.html#getSessionsCurrent()[DefaultSessionCache.getSessionsCurrent()] reports the number of sessions in the cache at the time of the method call. - -max sessions:: -The link:{javadoc-url}/org/eclipse/jetty/server/session/DefaultSessionCache.html#getSessionsCurrent()[DefaultSessionCache.getSessionsMax()] reports the highest number of sessions in the cache at the time of the method call. - - -total sessions:: -The link:{javadoc-url}/org/eclipse/jetty/server/session/DefaultSessionCache.html#getSessionsTotal()[DefaultSessionCache.getSessionsTotal()] reports the cumulative total of the number of sessions in the cache at the time of the method call. - -reset:: -The link:{javadoc-url}/org/eclipse/jetty/server/session/DefaultSessionCache.html#resetStats()[DefaultSessionCache.resetStats()] zeros out the statistics counters. - -If you create a link:{javadoc-url}/org/eclipse/jetty/server/session/DefaultSessionCacheFactory.html[DefaultSessionFactory] and register it as `Server` bean, a `SessionHandler` will be able to lazily create a `DefaultSessionCache`. -The `DefaultSessionCacheFactory` has all of the same configuration setters as a `DefaultSessionCache`. -Alternatively, if you only have a single `SessionHandler`, or you need to configure a `DefaultSessionCache` differently for every `SessionHandler`, then you could dispense with the `DefaultSessionCacheFactory` and simply instantiate, configure and pass in the `DefaultSessionCache` yourself. - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=defaultsessioncache] ----- - -NOTE: If you don't configure any `SessionCache` or `SessionCacheFactory`, the `SessionHandler` will automatically create a `DefaultSessionCache`. - -[[pg-server-session-null]] -===== The NullSessionCache - -The link:{javadoc-url}/org/eclipse/jetty/server/session/NullSessionCache.html[NullSessionCache] does not actually cache any objects: each request uses a fresh `Session` object. -It is suitable for clustered deployments without a sticky load balancer and non-clustered deployments when purely minimal support for sessions is needed. - -As no sessions are actually cached, of course functions like `invalidateOnShutdown` and all of the eviction strategies have no meaning for the `NullSessionCache`. - -There is a link:{javadoc-url}/org/eclipse/jetty/server/session/NullSessionCacheFactory.html[NullSessionCacheFactory] which you can instantiate, configure and set as a `Server` bean to enable the `SessionHandler` to automatically create new ``NullCache``s as needed. -All of the same configuration options are available on the `NullSessionCacheFactory` as the `NullSessionCache` itself. -Alternatively, if you only have a single `SessionHandler`, or you need to configure a `NullSessionCache` differently for every `SessionHandler`, then you could dispense with the `NullSessionCacheFactory` and simply instantiate, configure and pass in the `NullSessionCache` yourself. - - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=nullsessioncache] ----- - -[[pg-server-session-customcache]] -===== Implementing a Custom SessionCache - -As previously mentioned, we highly recommend that you extend the link:{javadoc-url}/org/eclipse/jetty/server/session/AbstractSessionCache.html[AbstractSessionCache]. - -===== Heterogeneous Caching - -Using one of the ``SessionCacheFactory``s will ensure that every time a `SessionHandler` starts it will create a new instance of the corresponding type of `SessionCache`. - -But, what if you deploy multiple webapps, and for one of them, you don't want to use sessions? -Or alternatively, you don't want to use sessions, but you have one webapp that now needs them? -In that case, you can configure the `SessionCacheFactory` appropriate to the majority, and then specifically create the right type of `SessionCache` for the others. -Here's an example where we configure the `DefaultSessionCacheFactory` to handle most webapps, but then specifically use a `NullSessionCache` for another: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=mixedsessioncache] ----- - - - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-file.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-file.adoc deleted file mode 100644 index 4a922a7ea00b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-file.adoc +++ /dev/null @@ -1,79 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-datastore-file]] -===== The FileSessionDataStore - -The `FileSessionDataStore` supports persistent storage of session data in a filesystem. - -IMPORTANT: Persisting sessions to the local file system should *never* be used in a clustered environment. - -One file represents one session in one context. - -File names follow this pattern: - -+[expiry]_[contextpath]_[virtualhost]_[id]+ - -expiry:: -This is the expiry time in milliseconds since the epoch. - -contextpath:: -This is the context path with any special characters, including `/`, replaced by the `_` underscore character. -For example, a context path of `/catalog` would become `_catalog`. -A context path of simply `/` becomes just `__`. -virtualhost:: -This is the first virtual host associated with the context and has the form of 4 digits separated by `.` characters. -If there are no virtual hosts associated with a context, then `0.0.0.0` is used: - - [digit].[digit].[digit].[digit] - -id:: -This is the unique id of the session. - -Putting all of the above together as an example, a session with an id of `node0ek3vx7x2y1e7pmi3z00uqj1k0` for the context with path `/test` with no virtual hosts and an expiry of `1599558193150` would have a file name of: - -`1599558193150__test_0.0.0.0_node0ek3vx7x2y1e7pmi3z00uqj1k0` - - -====== Configuration - -You can configure either a link:{javadoc-url}/org/eclipse/jetty/server/session/FileSessionDataStore.html[FileSessionDataStore] individually, or a `FileSessionDataStoreFactory` if you want multiple ``SessionHandler``s to use ``FileSessionDataStore``s that are identically configured. -The configuration methods are: - -storeDir:: -This is a File that defines the location for storage of session files. -If the directory does not exist at startup, it will be created. -If you use the same `storeDir` for multiple `SessionHandlers`, then the sessions for all of those contexts are stored in the same directory. -This is not a problem, as the name of the file is unique because it contains the context information. -You _must_ supply a value for this, otherwise startup of the `FileSessionDataStore` will fail. - -deleteUnrestorableFiles:: -Boolean, default `false`. -If set to `true`, unreadable files will be deleted. -This is useful to prevent repeated logging of the same error when the xref:pg-server-session-housekeeper[scavenger] periodically (re-)attempts to load the corrupted information for a session in order to expire it. - -include::session-sessiondatastore.adoc[tag=common-datastore-config] - -Let's look at an example of configuring a `FileSessionDataStoreFactory`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=filesessiondatastorefactory] ----- - -Here's an alternate example, configuring a `FileSessionDataStore` directly: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=filesessiondatastore] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-jdbc.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-jdbc.adoc deleted file mode 100644 index 12161f46cc0c..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-jdbc.adoc +++ /dev/null @@ -1,153 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-datastore-jdbc]] -===== The JDBCSessionDataStore - -The `JDBCSessionDataStore` supports persistent storage of session data in a relational database. -To do that, it requires a `DatabaseAdaptor` that handles the differences between databases (eg Oracle, Postgres etc), and a `SessionTableSchema` that allows for the customization of table and column names. - -[plantuml] ----- -class JDBCSessionDataStore -class DatabaseAdaptor -class SessionTableSchema - -JDBCSessionDataStore "1" *-- "1" DatabaseAdaptor -JDBCSessionDataStore "1" *-- "1" SessionTableSchema ----- - -`SessionData` is stored in a table with one row per session. -This is the table, with the table name, column names and type keywords at their default settings: - - -[caption="Table:"] -.JettySessions -[frame=all] -[cols=12*,options="header"] -|=== -|sessionId -|contextPath -|virtualHost -|lastNode -|accessTime -|lastAccessTime -|createTime -|cookieTime -|lastSavedTime -|expiryTime -|maxInterval -|map -|120 varchar|60 varchar|60 varchar|60 varchar|long|long|long|long|long|long|long|blob -|=== - -The name of the table and all columns can be configured using the `SessionTableSchema` class described below. -Many databases use different keywords for the `long`, `blob` and `varchar` types, so you can explicitly configure these if jetty cannot determine what they should be at runtime based on the metadata available from a db connection using the `DatabaseAdaptor` class described below. - -====== Configuration - -The link:{javadoc-url}/org/eclipse/jetty/server/session/JDBCSessionDataStore.html[JDBCSessionDataStore] and corresponding link:{javadoc-url}/org/eclipse/jetty/server/session/JDBCSessionDataStoreFactory.html[JDBCSessionDataStoreFactory] supports the following configuration: - -include::session-sessiondatastore.adoc[tag=common-datastore-config] - -DatabaseAdaptor:: -The `DatabaseAdaptor` can connect to a database either via a `javax.sql.Datasource` or a `java.sql.Driver`. -Additionally, a database-specific keyword can be configured for the `blob`, `varchar` and `long` types. -Note that the `DatabaseAdaptor` tries to automatically detect the type of the database from the first connection and select the appropriate type keywords, however you may need to explicitly configure them if you're not using `Postgres` or `Oracle`. - - datasource::: - This can either be a `Datasource` instance or the jndi name of a `Datasource` to look up. -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=dbaDatasource] ----- - - driverInfo::: - This is the name or instance of a jdbc `Driver` class and a connection url. -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=dbaDriver] ----- - - blobType::: - Default `blob` or `bytea` for Postgres. - - longType::: - Default `bigint` or `number(20)` for Oracle. - - stringType::: - Default `varchar`. - - -SessionTableSchema:: - schemaName::: - catalogName::: -The exact meaning of these two are dependent on your database vendor, but can broadly be described as further scoping for the session table name. -See https://en.wikipedia.org/wiki/Database_schema and https://en.wikipedia.org/wiki/Database_catalog. -These extra scoping names can come into play at startup time when Jetty determines if the session table already exists, or otherwise creates it on-the-fly. -If you have employed either of these concepts when you pre-created the session table, or you want to ensure that Jetty uses them when it auto-creates the session table, then you have two options: either set them explicitly, or let Jetty infer them from a database connection. -If you leave them unset, then no scoping will be done. -If you use the special value `INFERRED`, Jetty will determine them from a database connection. - - tableName::: -Default `JettySessions`. -This is the name of the table in which session data is stored. - - accessTimeColumn::: -Default `accessTime`. -This is the name of the column that stores the time - in ms since the epoch - at which a session was last accessed - - contextPathColumn::: -Default `contextPath`. -This is the name of the column that stores the `contextPath` of a session. - - cookieTimeColumn::: -Default `cookieTime`. -This is the name of the column that stores the time - in ms since the epoch - that the cookie was last set for a session. - - createTimeColumn::: -Default `createTime`. -This is the name of the column that stores the time - in ms since the epoch - at which a session was created. - - expiryTimeColumn::: -Default `expiryTime`. -This is name of the column that stores - in ms since the epoch - the time at which a session will expire. - - lastAccessTimeColumn::: -Default `lastAccessTime`. -This is the name of the column that stores the time - in ms since the epoch - that a session was previously accessed. - - lastSavedTimeColumn::: -Default `lastSavedTime`. -This is the name of the column that stores the time - in ms since the epoch - at which a session was last written. - - idColumn::: -Default `sessionId`. -This is the name of the column that stores the id of a session. - - lastNodeColumn::: -Default `lastNode`. -This is the name of the column that stores the `workerName` of the last node to write a session. - - virtualHostColumn::: -Default `virtualHost`. -This is the name of the column that stores the first virtual host of the context of a session. - - maxIntervalColumn::: -Default `maxInterval`. -This is the name of the column that stores the interval - in ms - during which a session can be idle before being considered expired. - - mapColumn::: -Default `map`. -This is the name of the column that stores the serialized attributes of a session. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-mongo.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-mongo.adoc deleted file mode 100644 index 968b284188de..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore-mongo.adoc +++ /dev/null @@ -1,102 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-datastore-mongo]] -===== The MongoSessionDataStore - -The `MongoSessionDataStore` supports persistence of `SessionData` in a nosql database. - -The best description for the document model for session information is found in the javadoc for the link:{javadoc-url}/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStore.html[MongoSessionDataStore]. -In overview, it can be represented thus: - -[plantuml] ----- -database HttpSessions { - folder jettySessions { - file session { - file "context" { - rectangle attributes - } - } - } -} ----- - -The database contains a document collection for the sessions. -Each document represents a session id, and contains one nested document per context in which that session id is used. -For example, the session id `abcd12345` might be used by two contexts, one with path `/contextA` and one with path `/contextB`. -In that case, the outermost document would refer to `abcd12345` and it would have a nested document for `/contextA` containing the session attributes for that context, and another nested document for `/contextB` containing the session attributes for that context. -Remember, according to the Servlet Specification, a session id can be shared by many contexts, but the attributes must be unique per context. - -The outermost document contains these fields: - -id:: -The session id. -created:: -The time (in ms since the epoch) at which the session was first created in any context. -maxIdle:: -The time (in ms) for which an idle session is regarded as valid. -As maxIdle times can be different for ``Session``s from different contexts, this is the _shortest_ maxIdle time. -expiry:: -The time (in ms since the epoch) at which the session will expire. -As the expiry time can be different for ``Session``s from different contexts, this is the _shortest_ expiry time. - -Each nested context-specific document contains: - -attributes:: -The session attributes as a serialized map. -lastSaved:: -The time (in ms since the epoch) at which the session in this context was saved. -lastAccessed:: -The time (in ms since the epoch) at which the session in this context was previously accessed. -accessed:: -The time (in ms since the epoch) at which this session was most recently accessed. -lastNode:: -The xref:pg-server-session-workername[workerName] of the last server that saved the session data. -version:: -An object that is updated every time a session is written out for a context. - -====== Configuration - -You can configure either a link:{javadoc-url}/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStore.html[MongoSessionDataStore] individually, or a link:{javadoc-url}/org/eclipse/jetty/nosql/mongodb/MongoSessionDataStore.html[MongoSessionDataStoreFactory] if you want multiple ``SessionHandler``s to use ``MongoSessionDataStore``s that are identically configured. -The configuration methods for the `MongoSessionDataStoreFactory` are: - -include::session-sessiondatastore.adoc[tag=common-datastore-config] - -dbName:: -This is the name of the database. -collectionName:: -The name of the document collection. - -There are two alternative ways to specify the connection to mongodb: - -connectionString:: -This is a mongodb url, eg `mongodb://localhost` -host:: -port:: -This is the hostname and port number of the mongodb instance to contact. - -Let's look at an example of configuring a `MongoSessionDataStoreFactory`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=mongosdfactory] ----- - -// TODO: the code example is missing. -// Here's an alternate example, configuring a `MongoSessionDataStore` directly: - -//[source,java,indent=0] -//---- -//include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=mongosessiondatastore] -//---- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore.adoc deleted file mode 100644 index e27d3a07b5cf..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessiondatastore.adoc +++ /dev/null @@ -1,78 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-datastore]] -==== The SessionDataStore - -A link:{javadoc-url}/org/eclipse/jetty/server/session/SessionDataStore.html[SessionDataStore] mediates the storage, retrieval and deletion of `SessionData`. -There is one `SessionDataStore` per `SessionCache`. -The server libraries provide a number of alternative `SessionDataStore` implementations. - -[plantuml] ----- -title SessionDataStores - -interface SessionDataStore -class AbstractSessionDataStore -class FileSessionDataStore -class GCloudSessionDataStore -class HazelcastSessionDataStore -class InfinispanSessionDataStore -class JDBCSessionDataStore -class MongoSessionDataStore -class CachingSessionDataStore - - -SessionDataStore <|-- AbstractSessionDataStore -AbstractSessionDataStore <|-- FileSessionDataStore -AbstractSessionDataStore <|-- GCloudSessionDataStore -AbstractSessionDataStore <|-- HazelcastSessionDataStore -AbstractSessionDataStore <|-- InfinispanSessionDataStore -AbstractSessionDataStore <|-- JDBCSessionDataStore -AbstractSessionDataStore <|-- MongoSessionDataStore -SessionDataStore <|-- CachingSessionDataStore ----- - -The link:{javadoc-url}/org/eclipse/jetty/server/session/AbstractSessionDataStore.html[AbstractSessionDataStore] provides most of the behaviour common to ``SessionDataStore``s: - -passivation:: -Supporting passivation means that session data is serialized. -Some persistence mechanisms serialize, such as JDBC, GCloud Datastore etc. -Others store an object in shared memory, e.g. Infinispan and thus don't serialize session data. -Whether or not a persistence technology entails passivation controls whether or not ``HttpSessionActivationListener``s will be called. -When implementing a custom `SessionDataStore` you need to decide whether or not passivation will be supported. - -[[pg-server-session-datastore-skip]] -//tag::common-datastore-config[] -savePeriod:: -This is an interval defined in seconds. -It is used to reduce the frequency with which `SessionData` is written. -Normally, whenever the last concurrent request leaves a `Session`, the `SessionData` for that `Session` is always persisted, even if the only thing that changed is the `lastAccessTime`. -If the `savePeriod` is non-zero, the `SessionData` will not be persisted if no session attributes changed, _unless_ the time since the last save exceeds the `savePeriod`. -Setting a non-zero value can reduce the load on the persistence mechanism, but in a clustered environment runs the risk that other nodes will see the session as expired because it has not been persisted sufficiently recently. - -gracePeriod:: -The `gracePeriod` is an interval defined in seconds. -It is an attempt to deal with the non-transactional nature of sessions with regard to finding sessions that have expired. -In a clustered configuration - even with a sticky load balancer - it is always possible that a session is "live" on a node but not yet updated in the persistent store. -This means that it can be hard to determine at any given moment whether a clustered session has truly expired. -Thus, we use the `gracePeriod` to provide a bit of leeway around the moment of expiry during xref:pg-server-session-housekeeper[scavenge]: - -* on every xref:pg-server-session-housekeeper[scavenge] cycle an `AbstractSessionDataStore` searches for sessions that belong to the context that expired at least one `gracePeriod` ago -* infrequently the `AbstractSessionDataStore` searches for and summarily deletes sessions - from any context - that expired at least 10 ``gracePeriod``s ago -//end::common-datastore-config[] - -[NOTE] -==== -The trivial link:{javadoc-url}/org/eclipse/jetty/server/session/NullSessionDataStore.html[NullSessionDataStore] - which does not persist sessions - is the default used by the `SessionHandler`. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessionhandler.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessionhandler.adoc deleted file mode 100644 index 0d4820d2bb7d..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessionhandler.adoc +++ /dev/null @@ -1,150 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-handler]] -==== The SessionHandler - -Each context can have a single `SessionHandler`. -The purpose of the `SessionHandler` is to interact with the `Request` and `Response` to create, maintain and propagate sessions. -It also calls the context-level session listeners at appropriate points in the session lifecycle. - -===== Configuration - -The majority of configuration for the link:{javadoc-url}/org/eclipse/jetty/server/session/SessionHandler.html[SessionHandler] can be done via `web.xml` `` declarations, or the `javax.servlet.SessionCookieConfig` api. -There are also a few jetty-specific configuration options that we will cover here: - -checkingRemoteSessionIdEncoding:: -Boolean, default `false`. -This controls whether or not the `javax.servlet.http.Response.encodeURL(String)` method will include the session id as a path parameter when the URL is destined for a remote node. -This can also be configured by: -* setting the `org.eclipse.jetty.servlet.CheckingRemoteSessionIdEncoding` context init paramter - -setMaxInactiveInterval:: -Integer, seconds. -This is the amount of time after which an unused session may be scavenged. -This can also be configured by: - -* defining the `` element in `web.xml`, although take note that this element is specified in _minutes_ but this method uses _seconds_. -* calling the `javax.servlet.ServletContext.setSessionTimeout(int)` method, where the timeout is configured in _minutes_. - -setHttpOnly:: -Boolean, default `false`. -If `true`, the session cookie will not be exposed to client-side scripting code. -This can also be configured by: - -* using `javax.servlet.SessionCookieConfig.setHttpOnly(boolean)` method -* defining the `` element in `web.xml` - -[[pg-server-session-handler-refreshcookie]] -refreshCookieAge:: -Integer, seconds, default is `-1`. -This controls resetting the session cookie when `SessionCookieConfig.setMaxAge(int)` is non-zero. -See also xref:pg-server-session-handler-maxAge[setting the max session cookie age with an init parameter]. -If the amount of time since the session cookie was last set exceeds this time, the session cookie is regenerated to keep the session cookie valid. - -sameSite:: -`HttpCookie.SameSite`, default `null`. -The values are `HttpCookie.SameSite.NONE`, `HttpCookie.SameSite.STRICT`, `HttpCookie.SameSite.LAX`. - -secureRequestOnly:: -Boolean, default `true`. -If `true` and the request is HTTPS, the set session cookie will be marked as `secure`, meaning the client will only send the session cookie to the server on subsequent requests over HTTPS. -This can also be configured by: - -* using the `javax.servlet.SessionCookieConfig.setSecure(true)` method, in which case the set session cookie will _always_ be marked as `secure`, even if the request triggering the creation of the cookie was not over HTTPS. - -sessionCookie:: -String, default is `JSESSIONID`. -This is the name of the session cookie. -It can alternatively be configured by: - -* using `javax.servlet.SessionCookieConfig.setName(String)` method -* setting the `org.eclipse.jetty.servlet.SessionCookie` context init parameter. - -sessionIdPathParameterName:: -String, default is `jsessionid`. -This is the name of the path parameter used to transmit the session id on request URLs, and on encoded URLS in responses. -It can alternatively be configured by: - -* setting the `org.eclipse.jetty.servlet.SessionIdPathParameterName` context init parameter - -sessionTrackingModes:: -`Set`. -Default is `SessionTrackingMode.COOKIE`, `SessionTrackingMode.URL`. -This can also be configured by: - -* using the `setSessionTrackingModes(Set)` method -* using the `javax.servlet.ServletContext.setSessionTrackingModes)` method -* defining up to three ````s for the `` element in `web.xml` - -usingCookies:: -Boolean, default `true`. -Determines whether or not the `SessionHandler` will look for session cookies on requests, and will set session cookies on responses. -If `false` session ids must be transmitted as path params on URLs. -This can also be configured by: - -* using the `setSessionTrackingModes(Set)` method -* using the `javax.servlet.ServletContext.setSessionTrackingModes)` method - -There are also a few session settings that do not have SessionHandler setters, but can be configured with context init parameters: - -[[pg-server-session-handler-maxAge]] -org.eclipse.jetty.servlet.MaxAge:: -This is the maximum number of seconds that the session cookie will be considered to be valid. -By default, the cookie has no maximum validity time. -See also xref:pg-server-session-handler-refreshcookie[refreshing the session cookie]. -The value can also be configured by: - -* calling the `SessionCookieConfig.setMaxAge(int)` method. - -org.eclipse.jetty.servlet.SessionDomain:: -String, default `null`. -This is the domain of the session cookie. -This can also be configured by: - -* using the `javax.servlet.SessionCookieConfig.setDomain(String)` method -* defining the `` element in `web.xml` - -org.eclipse.jetty.servlet.SessionPath:: -String, default `null`. -This is used when creating a new session cookie. -If nothing is configured, the context path is used instead, defaulting to `/`. -This can also be configured by: - -* using the `javax.servlet.SessionCookieConfig.setPath(String)` method -* defining the `` element in `web.xml` - -===== Statistics - -Some statistics about the sessions for a context can be obtained from the `SessionHandler`, either by calling the methods directly or via `jmx`: - -sessionsCreated:: -This is the total number of sessions that have been created for this context since Jetty started. - -sessionTimeMax:: -The longest period of time a session was valid in this context before being invalidated. - -sessionTimeMean:: -The average period of time a session in this context was valid. - -sessionTimeStdDev:: -The standard deviation of the session validity times for this context. - -sessionTimeTotal:: -The total time that all sessions in this context have remained valid. - -You can reset the statistics counters by either calling the following method directly on the the `SessionHandler`, or using `jmx`: - -statsReset:: -Resets the `SessionHandler` statistics counters. - diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessionidmgr.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessionidmgr.adoc deleted file mode 100644 index 0e47b8cd3aac..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/session-sessionidmgr.adoc +++ /dev/null @@ -1,84 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session-idmgr]] -==== The SessionIdManager - -There is a maximum of one `SessionIdManager` per `Server` instance. -Its purpose is to generate fresh, unique session ids and to coordinate the re-use of session ids amongst co-operating contexts. - -The `SessionIdManager` is agnostic with respect to the type of clustering technology chosen. - -Jetty provides a default implementation - the link:{javadoc-url}/org/eclipse/jetty/server/session/DefaultSessionIdManager.html[DefaultSessionIdManager] - which should meet the needs of most users. - -NOTE: If you do not explicitly configure a `SessionIdManager`, then when the `SessionHandler` starts, it will use an instance of the `DefaultSessionIdManager`. - -[[pg-server-session-defaultidmgr]] -===== The DefaultSessionIdManager - -At startup, if no instance of the `HouseKeeper` has been explicitly set, the `DefaultSessionIdManager` will create one. - -[[pg-server-session-workername]] -Also at startup, the `workerName` is determined. -The `workerName` must be unique per `Server`, and identifies the server in a cluster. -If a `workerName` has not been explicitly set, then the value is derived as follows: - -+node[JETTY_WORKER_NAME]+ - -where `JETTY_WORKER_NAME` is an environment variable whose value can be an integer or string. -If the environment variable is not set, then it defaults to `0`, yielding the default `workerName` of `"node0"`. - -The `DefaultSessionIdManager` uses `SecureRandom` to generate unique session ids. - -The `SessionHandler` class, which is used by both the `ServletContextHandler` and the `WebAppContext` classes, will instantiate a `DefaultSessionIdManager` on startup if it does not detect one already present for the `Server`. - -Here is an example of explicitly setting up a `DefaultSessionIdManager` with a `workerName` of `server3` in code: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=default] ----- - -==== Implementing a Custom SessionIdManager - -If the `DefaultSessionIdManager` does not meet your needs, you can extend it, or implement the `SessionIdManager` interface directly. - -When implementing a `SessionIdManager` pay particular attention to the following: - -* the `getWorkerName()` method _must_ return a name that is unique to the `Server` instance. -The `workerName` becomes important in clustering scenarios because sessions can migrate from node to node: the `workerName` identifies which node was last managing a `Session`. -* the contract of the `isIdInUse(String id)` method is very specific: a session id may _only_ be reused _iff_ it is already in use by another context. -This restriction is important to support cross-context dispatch. -* you should be _very_ careful to ensure that the `newSessionId(HttpServletRequest request, long created)` method does not return duplicate or predictable session ids. - -[[pg-server-session-housekeeper]] -===== The HouseKeeper - -There is a maximum of one link:{javadoc-url}/org/eclipse/jetty/server/session/HouseKeeper.html[HouseKeeper] per `SessionIdManager`. -Its purpose is to periodically poll the link:{javadoc-url}/org/eclipse/jetty/server/session/SessionHandler.html[SessionHandlers] to clean out expired sessions. -This operation is usually referred to as "scavenging" expired sessions. -The scavenging interval is configured by the `setIntervalSec(long)` method. -The default value is ``600``sec, ie ``10``mins. - -[IMPORTANT] -==== -The HouseKeeper semi-randomly adds an additional `10%` of the configured `intervalSec`. -This is to help prevent sync-ing up of servers in a cluster that are all restarted at once, and slightly stagger their scavenge cycles to ensure any load on the persistent storage mechanism is spread out. -==== - -This code example shows how to configure a `HouseKeeper`, along with a `DefaultSessionIdManager`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java[tags=housekeeper] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/sessions.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/sessions.adoc deleted file mode 100644 index 51ccafed5696..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/sessions/sessions.adoc +++ /dev/null @@ -1,29 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-session]] -=== HTTP Session Management - -Sessions are a concept within the Servlet API which allow requests to store and retrieve information across the time a user spends in an application. -Jetty provides a number of pluggable options for managing sessions. -In this section we'll look at the architecture of session support in Jetty, review the various pluggable options available and indicate what and how to customize should none of the existing options suit your usecase. - -include::session-architecture.adoc[] -include::session-sessionidmgr.adoc[] -include::session-sessionhandler.adoc[] -include::session-sessioncache.adoc[] -include::session-sessiondatastore.adoc[] -include::session-sessiondatastore-file.adoc[] -include::session-sessiondatastore-jdbc.adoc[] -include::session-sessiondatastore-mongo.adoc[] -include::session-cachingsessiondatastore.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-filter.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-filter.adoc deleted file mode 100644 index d2078cc76c78..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-filter.adoc +++ /dev/null @@ -1,82 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-websocket-configure-filter]] -==== Advanced `WebSocketUpgradeFilter` Configuration - -The `WebSocketUpgradeFilter` that handles the HTTP requests that upgrade to WebSocket is installed in these cases: - -* Either by the `JavaxWebSocketServletContainerInitializer`, as described in xref:pg-server-websocket-standard[this section]. -* Or by a call to `JettyWebSocketServerContainer.addMapping(\...)`, as described in xref:pg-server-websocket-jetty[this section]. - -Typically, the `WebSocketUpgradeFilter` is not present in the `web.xml` configuration, and therefore the mechanisms above create a new `WebSocketUpgradeFilter` and install it _before_ any other Filter declared in `web.xml`, under the default name of `"org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter"` and with path mapping `/*`. - -However, if the `WebSocketUpgradeFilter` is already present in `web.xml` under the default name, then the ``ServletContainerInitializer``s will use that declared in `web.xml` instead of creating a new one. - -This allows you to customize: - -* The filter order; for example, by configuring the `CrossOriginFilter` (or other filters) for increased security or authentication _before_ the `WebSocketUpgradeFilter`. -* The `WebSocketUpgradeFilter` configuration via ``init-param``s, that affects all `Session` instances created by this filter. -* The `WebSocketUpgradeFilter` path mapping. Rather than the default mapping of `+/*+`, you can map the `WebSocketUpgradeFilter` to a more specific path such as `+/ws/*+`. -* The possibility to have multiple ``WebSocketUpgradeFilter``s, mapped to different paths, each with its own configuration. - -For example: - -[source,xml,subs=verbatim] ----- - - - - My WebSocket WebApp - - - - cross-origin - org.eclipse.jetty.servlets.CrossOriginFilter - true - - - cross-origin - /* - - - - - - org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter - org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter - - - maxTextMessageSize - 1048576 - - true - - - org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter - - /ws/* - - - ----- -<1> The `CrossOriginFilter` is the first to protect against link:https://owasp.org/www-community/attacks/csrf[cross-site request forgery attacks]. -<2> The configuration for the _default_ `WebSocketUpgradeFilter`. -<3> Note the use of the _default_ `WebSocketUpgradeFilter` name. -<4> Specific configuration for `WebSocketUpgradeFilter` parameters. -<5> Use a more specific path mapping for `WebSocketUpgradeFilter`. - -Note that using a more specific path mapping for WebSocket requests is also beneficial to the performance of normal HTTP requests: they do not go through the `WebSocketUpgradeFilter` (as they will not match its path mapping), saving the cost of analyzing them to see whether they are WebSocket upgrade requests or not. diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-jetty.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-jetty.adoc deleted file mode 100644 index 144ddc3ea9ee..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-jetty.adoc +++ /dev/null @@ -1,200 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-websocket-jetty]] -==== Jetty APIs Implementation - -When you write a WebSocket application using the Jetty WebSocket APIs, your code typically need to depend on just the Jetty WebSocket APIs to compile your application. -However, at runtime you need to have the _implementation_ of the Jetty WebSocket APIs in your class-path (or module-path). - -Jetty's WebSocket APIs are provided by the following Maven artifact: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.websocket - websocket-jetty-api - {version} - ----- - -Jetty's implementation of the Jetty WebSocket APIs is provided by the following Maven artifact (and its transitive dependencies): - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.websocket - websocket-jetty-server - {version} - ----- - -[NOTE] -==== -The `websocket-jetty-api` artifact and the `websocket-jetty-server` artifact (and its transitive dependencies) should be present in the server class-path (or module-path), and never in the web application's `/WEB-INF/lib` directory. -==== - -To configure correctly your WebSocket application based on the Jetty WebSocket APIs, you need two steps: - -. Make sure that Jetty xref:pg-server-websocket-jetty-container[sets up] an instance of `JettyWebSocketServerContainer`. -. Use the `JettyWebSocketServerContainer` APIs in your applications to xref:pg-server-websocket-jetty-endpoints[register your WebSocket endpoints] that implement your application logic. - -You can read more about the xref:pg-websocket-architecture[Jetty WebSocket architecture], which is common to both client-side and server-side, to get familiar with the terminology used in the following sections. - -[[pg-server-websocket-jetty-container]] -===== Setting up `JettyWebSocketServerContainer` - -Jetty sets up a `JettyWebSocketServerContainer` instance using `JettyWebSocketServletContainerInitializer`. - -When you deploy web applications using xref:pg-server-http-handler-use-webapp-context[`WebAppContext`], then `JettyWebSocketServletContainerInitializer` is automatically discovered and initialized by Jetty when the web application starts, so that it sets up the `JettyWebSocketServerContainer`. -In this way, you do not need to write any additional code: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=standardContainerWebAppContext] ----- - -On the other hand, when you deploy web applications using xref:pg-server-http-handler-use-servlet-context[`ServletContextHandler`], you have to write the code to ensure that the `JettyWebSocketServletContainerInitializer` is initialized, so that it sets up the `JettyWebSocketServerContainer`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=jettyContainerServletContextHandler] ----- - -Calling `JettyWebSocketServletContainerInitializer.configure(\...)` must be done _before_ the `ServletContextHandler` is started, and configures the Jetty WebSocket implementation for that web application context. - -[[pg-server-websocket-jetty-endpoints]] -===== Configuring Endpoints - -Once you have xref:pg-server-websocket-jetty-container[setup] the `JettyWebSocketServerContainer`, you can configure your xref:pg-websocket-endpoints[WebSocket endpoints]. - -Differently from the xref:pg-server-websocket-standard-endpoints[configuration of standard WebSocket endpoints], WebSocket endpoint classes may be annotated with Jetty WebSocket API annotations, or extend the `org.eclipse.jetty.websocket.api.WebSocketListener` interface, but they are not automatically discovered, not even when deploying web applications using xref:pg-server-http-handler-use-webapp-context[`WebAppContext`]. - -[IMPORTANT] -==== -When using the Jetty WebSocket APIs, WebSocket endpoints must always be explicitly configured. -==== - -There are two ways of configuring WebSocket endpoints when using the Jetty WebSocket APIs: - -* xref:pg-server-websocket-jetty-endpoints-container[Using `JettyWebSocketServerContainer`], which is very similar to how WebSocket endpoints are configured when using the xref:pg-server-websocket-standard-endpoints[standard `javax.websocket` APIs], but also provides APIs to perform a direct, programmatic, WebSocket upgrade. -* xref:pg-server-websocket-jetty-endpoints-servlet[Using `JettyWebSocketServlet`], which may configured in `web.xml`, rather than in Java code. - -[[pg-server-websocket-jetty-endpoints-container]] -====== Using `JettyWebSocketServerContainer` - -To register WebSocket endpoints using the Jetty WebSocket APIs you need to access the `JettyWebSocketServerContainer` APIs. - -The `JettyWebSocketServerContainer` instance is stored in the `ServletContext`, so it can be retrieved when the `ServletContext` is initialized, either from a `ServletContextListener` or from a `HttpServlet`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=jettyEndpointsInitialization] ----- - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=jettyWebSocketInitializerServlet] ----- - -You can also use this variant to set up the `JettyWebSocketServerContainer` and configure the WebSocket endpoints in one step: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=jettyContainerAndEndpoints] ----- - -In the call to `JettyWebSocketServerContainer.addMapping(\...)`, you can specify a _path spec_ (the first parameter) that can be configured as specified in xref:pg-server-websocket-jetty-pathspec[this section]. - -When the `ServletContextHandler` is started, the `Configurator` lambda (the second parameter passed to `JettyWebSocketServletContainerInitializer.configure(\...)`) is invoked and allows you to explicitly configure the WebSocket endpoints using the Jetty WebSocket APIs provided by `JettyWebSocketServerContainer`. - -Under the hood, the call to `JettyWebSocketServerContainer.addMapping(\...)` installs the `org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter`, which is the component that intercepts HTTP requests to upgrade to WebSocket, described in xref:pg-server-websocket-standard-upgrade[this section]. -For more information about the configuration of `WebSocketUpgradeFilter` see also xref:pg-server-websocket-configure-filter[this section]. - -One last alternative to register your WebSocket endpoints is to use a programmatic WebSocket upgrade via `JettyWebSocketServerContainer.upgrade(\...)`, which allows you to use a standard `HttpServlet` subclass (rather than a `JettyWebSocketServlet` as explained in xref:pg-server-websocket-jetty-endpoints-servlet[this section]) to perform a direct WebSocket upgrade when your application logic demands so: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=jettyContainerServletContextHandler] ----- - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=jettyContainerUpgrade] ----- - -When using `JettyWebSocketServerContainer.upgrade(\...)`, the `WebSocketUpgradeFilter` is not installed, since the WebSocket upgrade is performed programmatically. - -[[pg-server-websocket-jetty-endpoints-servlet]] -====== Using `JettyWebSocketServlet` - -An alternative way to register WebSocket endpoints using the Jetty WebSocket APIs is to use a `JettyWebSocketServlet` subclass (or even many different `JettyWebSocketServlet` subclasses). - -This method has the advantage that it does not install the `WebSocketUpgradeFilter` under the hood, because the WebSocket upgrade is handled directly by your `JettyWebSocketServlet` subclass. -This may also have a performance benefit for non-WebSocket HTTP requests (as they will not pass through the `WebSocketUpgradeFilter`). - -Your `JettyWebSocketServlet` subclass may be declared and configured either in code or in `web.xml`. -Declaring your `JettyWebSocketServlet` subclass explicitly in code or in `web.xml` also simplifies the declaration and configuration of other web components such as other Servlets and/or Filters (for example, it is easier to configure the `CrossOriginFilter`, see also xref:pg-server-websocket-configure-filter[this section] for more information). - -For example, your `JettyWebSocketServlet` subclass may be declared in code in this way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=jettyWebSocketServletMain] ----- - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=jettyWebSocketServlet] ----- - -Note how in the call to `JettyWebSocketServletContainerInitializer.configure(\...)` the second parameter is `null`, because WebSocket endpoints are not created here, but instead by one (or more) `JettyWebSocketServlet` subclasses. -Yet the call is necessary to create other WebSocket implementation components that are necessary also when using `JettyWebSocketServlet` subclasses. - -An HTTP upgrade request to WebSocket that matches your `JettyWebSocketServlet` subclass path mapping (specified above via `ServletContextHandler.addServlet(\...)`) arrives at the Servlet and is inspected to verify whether it is a valid upgrade to WebSocket. - -If the HTTP request is a valid upgrade to WebSocket, `JettyWebSocketServlet` calls `configure(JettyWebSocketServletFactory factory)` that you have overridden in your subclass, so that your application can instantiate and return the WebSocket endpoint. -After having obtained the WebSocket endpoint, `JettyWebSocketServlet` performs the WebSocket upgrade. -From this point on, the communication happens with the WebSocket protocol, and HTTP components such as Filters and Servlets are not relevant anymore. - -If the HTTP request is not an upgrade to WebSocket, `JettyWebSocketServlet` delegates the processing to the superclass, `javax.servlet.HttpServlet`, which in turn invokes methods such as `doGet(\...)` or `doPost(\...)` depending on the HTTP method. -If your `JettyWebSocketServlet` subclass did not override the `doXYZ(\...)` method corresponding to the HTTP request, a `405 Method Not Allowed` response is returned to the client, as per the standard `HttpServlet` class implementation. - -[NOTE] -==== -It is possible to use both `JettyWebSocketServerContainer` and `JettyWebSocketServlet`. - -However, it is typically best to avoid mixing the use of `JettyWebSocketServerContainer` with the use of `JettyWebSocketServlet`, so that all your WebSocket endpoints are initialized by the same code in one place only. -==== - -Using `JettyWebSocketServerContainer.addMapping(\...)` will install the `WebSocketUpgradeFilter` under the hood, which by default will intercepts all HTTP requests to upgrade to WebSocket. -However, as explained in xref:pg-server-websocket-standard-upgrade[this section], if `WebSocketUpgradeFilter` does not find a matching WebSocket endpoint for the request URI path, then the HTTP request is passed to the Filter chain of your web application and may arrive to your `JettyWebSocketServlet` subclass, where it would be processed and possibly result in a WebSocket upgrade. - -[[pg-server-websocket-jetty-pathspec]] -====== Custom PathSpec Mappings - -The `JettyWebSocketServerContainer.addMapping(\...)` API maps a _path spec_ to a `JettyWebSocketCreator` instance (typically a lambda expression). -The path spec is matched against the WebSocket upgrade request URI to select the correspondent `JettyWebSocketCreator` to invoke. - -The path spec can have these forms: - -* Servlet syntax, specified with `servlet|`, where the `servlet|` prefix can be omitted if the path spec begins with `/` or `+*.+` (for example, `/ws`, `/ws/chat` or `+*.ws+`). -* Regex syntax, specified with `regex|`, where the `regex|` prefix can be omitted if the path spec begins with `^` (for example, `+^/ws/[0-9]++`). -* URI template syntax, specified with `uri-template|` (for example `+uri-template|/ws/chat/{room}+`). - -Within the `JettyWebSocketCreator`, it is possible to access the path spec and, for example in case of URI templates, extract additional information in the following way: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=uriTemplatePathSpec] ----- diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-standard.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-standard.adoc deleted file mode 100644 index 2560f2990919..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket-standard.adoc +++ /dev/null @@ -1,141 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-websocket-standard]] -==== Standard APIs Implementation - -When you write a WebSocket application using the standard `javax.websocket` APIs, your code typically need to depend on just the APIs to compile your application. -However, at runtime you need to have an implementation of the standard APIs in your class-path (or module-path). - -The standard `javax.websocket` APIs are provided by the following Maven artifact: - -[source,xml,subs=normal] ----- - - javax.websocket - javax.websocket-api - 1.1 - ----- - -However, the artifact above lacks a proper JPMS `module-info.class` file, and therefore it is a little more difficult to use if you want to use of JPMS for your application. - -If you want to use JPMS for your application, you can use this Maven artifact instead: - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.toolchain - jetty-javax-websocket-api - 1.1.2 - ----- - -This artifact is nothing more than the `javax.websocket:javax.websocket-api:1.1` artifact repackaged with a proper `module-info.class` file. - -At runtime, you also need an implementation of the standard `javax.websocket` APIs. - -Jetty's implementation of the standard `javax.websocket` APIs is provided by the following Maven artifact (and its transitive dependencies): - -[source,xml,subs=normal] ----- - - org.eclipse.jetty.websocket - websocket-javax-server - {version} - ----- - -[NOTE] -==== -The `javax.websocket-api` artifact and the `websocket-javax-server` artifact (and its transitive dependencies) should be present in the server class-path (or module-path), and never in the web application's `/WEB-INF/lib` directory. -==== - -To configure correctly your WebSocket application based on the standard `javax.websocket` APIs, you need two steps: - -. Make sure that Jetty xref:pg-server-websocket-standard-container[sets up] an instance of `javax.websocket.server.ServerContainer`. -. xref:pg-server-websocket-standard-endpoints[Configure] the WebSocket endpoints that implement your application logic, either by annotating their classes with the standard `javax.websocket` annotations, or by using the `ServerContainer` APIs to register them in your code. - -[[pg-server-websocket-standard-container]] -===== Setting Up `ServerContainer` - -Jetty sets up a `ServerContainer` instance using `JavaxWebSocketServletContainerInitializer`. - -When you deploy web applications using xref:pg-server-http-handler-use-webapp-context[`WebAppContext`], then `JavaxWebSocketServletContainerInitializer` is automatically discovered and initialized by Jetty when the web application starts, so that it sets up the `ServerContainer`. -In this way, you do not need to write any additional code: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=standardContainerWebAppContext] ----- - -On the other hand, when you deploy web applications using xref:pg-server-http-handler-use-servlet-context[`ServletContextHandler`], you have to write the code to ensure that the `JavaxWebSocketServletContainerInitializer` is initialized, so that it sets up the `ServerContainer`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=standardContainerServletContextHandler] ----- - -Calling `JavaxWebSocketServletContainerInitializer.configure(\...)` must be done _before_ the `ServletContextHandler` is started, and configures the `javax.websocket` implementation for that web application context. - -[[pg-server-websocket-standard-endpoints]] -===== Configuring Endpoints - -Once you have xref:pg-server-websocket-standard-container[setup] the `ServerContainer`, you can configure your WebSocket endpoints. - -The WebSocket endpoints classes may be either annotated with the standard `javax.websocket` annotations, extend the `javax.websocket.Endpoint` abstract class, or implement the `javax.websocket.server.ServerApplicationConfig` interface. - -When you deploy web applications using xref:pg-server-http-handler-use-webapp-context[`WebAppContext`], then annotated WebSocket endpoint classes are automatically discovered and registered. -In this way, you do not need to write any additional code; you just need to ensure that your WebSocket endpoint classes are present in the web application's `/WEB-INF/classes` directory, or in a `*.jar` file in `/WEB-INF/lib`. - -On the other hand, when you deploy web applications using xref:pg-server-http-handler-use-webapp-context[`WebAppContext`] but you need to perform more advanced configuration of the `ServerContainer` or of the WebSocket endpoints, or when you deploy web applications using xref:pg-server-http-handler-use-servlet-context[`ServletContextHandler`], you need to access the `ServerContainer` APIs. - -The `ServerContainer` instance is stored as a `ServletContext` attribute, so it can be retrieved when the `ServletContext` is initialized, either from a `ServletContextListener` or from a `HttpServlet`: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=standardEndpointsInitialization] ----- - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=standardWebSocketInitializerServlet] ----- - -When you deploy web applications using xref:pg-server-http-handler-use-servlet-context[`ServletContextHandler`], you can also use this variant to set up the `ServerContainer` and configure the WebSocket endpoints in one step: - -[source,java,indent=0] ----- -include::../../{doc_code}/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java[tags=standardContainerAndEndpoints] ----- - -When the `ServletContextHandler` is started, the `Configurator` lambda (the second parameter passed to `JavaxWebSocketServletContainerInitializer.configure(\...)`) is invoked and allows you to explicitly configure the WebSocket endpoints using the standard APIs provided by `ServerContainer`. - -[[pg-server-websocket-standard-upgrade]] -====== Upgrade to WebSocket - -Under the hood, `JavaxWebSocketServletContainerInitializer` installs the `org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter`, which is the component that intercepts HTTP requests to upgrade to WebSocket, and performs the upgrade from the HTTP protocol to the WebSocket protocol. - -[NOTE] -==== -The `WebSocketUpgradeFilter` is installed under the filter name corresponding to its class name (that is, the string `"org.eclipse.jetty.websocket.servlet.WebSocketUpgradeFilter"`) and with a filter mapping of `/*`. - -Refer to the xref:pg-server-websocket-configure-filter[advanced `WebSocketUpgradeFilter` configuration section] for more information. -==== - -With the default configuration, every HTTP request flows first through the `WebSocketUpgradeFilter`. - -If the HTTP request is a valid upgrade to WebSocket, then `WebSocketUpgradeFilter` tries to find a matching WebSocket endpoint for the request URI path; if the match is found, `WebSocketUpgradeFilter` performs the upgrade and does not invoke any other Filter or Servlet. -From this point on, the communication happens with the WebSocket protocol, and HTTP components such as Filters and Servlets are not relevant anymore. - -If the HTTP request is not an upgrade to WebSocket, or `WebSocketUpgradeFilter` did not find a matching WebSocket endpoint for the request URI path, then the request is passed to the Filter chain of your web application, and eventually the request arrives to a Servlet to be processed (otherwise a `404 Not Found` response is returned to client). diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket.adoc deleted file mode 100644 index 8543d899d491..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/server/websocket/server-websocket.adoc +++ /dev/null @@ -1,40 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[[pg-server-websocket]] -=== WebSocket Server - -Jetty provides two API implementations of the WebSocket protocol: - -* An implementation for the standard `javax.websocket` APIs provided by link:https://www.jcp.org/en/jsr/detail?id=356[JSR 356], described in xref:pg-server-websocket-standard[this section]. -* An implementation for Jetty-specific WebSocket APIs, described in xref:pg-server-websocket-jetty[this section]. - -Using the standard `javax.websocket` APIs allows your applications to depend only on standard APIs, and your applications may be deployed in any compliant WebSocket Container that supports JSR 356. - -The standard APIs provide these features that are not present in the Jetty WebSocket APIs: - -* Encoders and Decoders for automatic conversion of text or binary messages to objects. - -On the other hand, the Jetty WebSocket APIs are more efficient and offer greater and more fine-grained control, and provide these features that are not present in the standard APIs: - -* Suspend/resume to control backpressure. -* Remote socket address (IP address and port) information. -* WebSocket upgrade handling via Filter or Servlet. -* Advanced URI matching with Servlet WebSocket upgrade. -* Configuration of the network buffer capacity. - -If your application needs specific features that are not provided by the standard APIs, the Jetty WebSocket APIs may provide such features -- and if they do not, you may ask for these features by submitting an issue to the Jetty Project without waiting for the standard process to approve them. - -include::server-websocket-standard.adoc[] -include::server-websocket-jetty.adoc[] -include::server-websocket-filter.adoc[] diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/troubleshooting.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/troubleshooting.adoc deleted file mode 100644 index 9e8cc9870a7b..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/troubleshooting.adoc +++ /dev/null @@ -1,105 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -[appendix] -[[pg-troubleshooting]] -== Troubleshooting Jetty - -TODO: introduction -// TODO: explain the process to troubleshoot Jetty: -// TODO: #1 enable JMX -// TODO: #2 enable GC logs -// TODO: #3 take jvm/component dumps -// TODO: #4 enable debug logging if you can - -[[pg-troubleshooting-logging]] -=== Logging - -The Jetty libraries (both client and server) use link:http://slf4j.org/[SLF4J] as logging APIs. -You can therefore plug in any SLF4J logging implementation, and configure the logging category `org.eclipse.jetty` at the desired level. - -When you have problems with Jetty, the first thing that you want to do is to enable DEBUG logging. -This is helpful because by reading the DEBUG logs you get a better understanding of what is going on in the system (and that alone may give you the answers you need to fix the problem), and because Jetty developers will probably need the DEBUG logs to help you. - -==== Jetty SLF4J Binding - -The Jetty artifact `jetty-slf4j-impl` is a SLF4J binding, that is the Jetty implementation of the SLF4J APIs, and provides a number of easy-to-use features to configure logging. - -The Jetty SLF4J binding only provides an appender that writes to `System.err`. -For more advanced configurations (for example, logging to a file), use link:http://logback.qos.ch[LogBack], or link:https://logging.apache.org/log4j/2.x/[Log4j2], or your preferred SLF4J binding. - -CAUTION: Only one binding can be present in the class-path or module-path. If you use the LogBack SLF4J binding or the Log4j2 SLF4J binding, remember to remove the Jetty SLF4J binding. - -The Jetty SLF4J binding reads a file in the class-path (or module-path) called `jetty-logging.properties` that can be configured with the logging levels for various logger categories: - -.jetty-logging.properties -[source,screen] ----- -# By default, log at INFO level all Jetty classes. -org.eclipse.jetty.LEVEL=INFO - -# However, the Jetty client classes are logged at DEBUG level. -org.eclipse.jetty.client.LEVEL=DEBUG ----- - -Similarly to how you configure the `jetty-logging.properties` file, you can set the system property `org.eclipse.jetty[.].LEVEL=DEBUG` to quickly change the logging level to DEBUG without editing any file. -The system property can be set on the command line, or in your IDE when you run your tests or your Jetty-based application and will override the `jetty-logging.properties` file configuration. -For example to enable DEBUG logging for all the Jetty classes (_very_ verbose): - -[source,screen] ----- -java -Dorg.eclipse.jetty.LEVEL=DEBUG --class-path ... ----- - -If you want to enable DEBUG logging but only for the HTTP/2 classes: - -[source,screen] ----- -java -Dorg.eclipse.jetty.http2.LEVEL=DEBUG --class-path ... ----- - -[[pg-troubleshooting-thread-dump]] -=== JVM Thread Dump -TODO - -[[pg-troubleshooting-component-dump]] -=== Jetty Component Tree Dump - -Jetty components are organized in a xref:pg-arch-bean[component tree]. - -At the root of the component tree there is typically a `ContainerLifeCycle` instance -- typically a `Server` instance on the server and an `HttpClient` instance on the client. - -`ContainerLifeCycle` has built-in _dump_ APIs that can be invoked either directly or xref:pg-arch-jmx[via JMX]. - -// TODO: images from JMC? -// TODO: Command line JMX will be in JMX section. - -TIP: You can get more details from a Jetty's `QueuedThreadPool` dump by enabling detailed dumps via `queuedThreadPool.setDetailedDump(true)`. - -[[pg-troubleshooting-debugging]] -=== Debugging - -Sometimes, in order to figure out a problem, enabling xref:pg-troubleshooting-logging[DEBUG logging] is not enough and you really need to debug the code with a debugger. - -Debugging an embedded Jetty application is most easily done from your preferred IDE, so refer to your IDE instruction for how to debug Java applications. - -Remote debugging can be enabled in a Jetty application via command line options: - -[source,screen] ----- -java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000 --class-path ... ----- - -The example above enables remote debugging so that debuggers (for example, your preferred IDE) can connect to port `8000` on the host running the Jetty application to receive debugging events. - -NOTE: More technically, remote debugging exchanges JVM Tools Interface (JVMTI) events and commands via the Java Debug Wire Protocol (JDWP). diff --git a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/websocket.adoc b/documentation/jetty-documentation/src/main/asciidoc/programming-guide/websocket.adoc deleted file mode 100644 index f0ade7fcd861..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/programming-guide/websocket.adoc +++ /dev/null @@ -1,311 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -// Snippets of WebSocket documentation that are common between client and server. - -[[pg-websocket-architecture]] -==== Jetty WebSocket Architecture - -The Jetty WebSocket architecture is organized around the concept of a logical _connection_ between the client and the server. - -The connection may be physical, when connecting to the server using HTTP/1.1, as the WebSocket bytes are carried directly by the TCP connection. - -The connection may be virtual, when connecting to the server using HTTP/2, as the WebSocket bytes are wrapped into HTTP/2 `DATA` frames of an HTTP/2 stream. -In this case, a single TCP connection may carry several WebSocket virtual connections, each wrapped in its own HTTP/2 stream. - -Each side of a WebSocket connection, either client or server, is made of two entities: - -* A xref:pg-websocket-endpoints[WebSocket _endpoint_], the entity that _receives_ WebSocket events. -* A xref:pg-websocket-session[WebSocket _session_], the entity that offers an API to _send_ WebSocket data (and to close the WebSocket connection), as well as to configure WebSocket connection parameters. - -[[pg-websocket-endpoints]] -==== WebSocket Endpoints - -A WebSocket endpoint is the entity that receives WebSocket events. - -The WebSocket events are the following: - -* The _connect_ event. -This event is emitted when the WebSocket communication has been successfully established. -Applications interested in the connect event receive the WebSocket _session_ so that they can use it to send data to the remote peer. -* The _close_ event. -This event is emitted when the WebSocket communication has been closed. -Applications interested in the close event receive a WebSocket status code and an optional close reason message. -* The _error_ event. -This event is emitted when the WebSocket communication encounters a fatal error, such as an I/O error (for example, the network connection has been broken), or a protocol error (for example, the remote peer sends an invalid WebSocket frame). -Applications interested in the error event receive a `Throwable` that represent the error. -* The _message_ event. -The message event is emitted when a WebSocket message is received. -Only one thread at a time will be delivering a message event to the `onMessage` method; the next message event will not be delivered until the previous call to the `onMessage` method has exited. -Endpoints will always be notified of message events in the same order they were received over the network. -The message event can be of two types: -** Textual message event. -Applications interested in this type of messages receive a `String` representing the UTF-8 bytes received. -** Binary message event. -Applications interested in this type of messages receive a `byte[]` representing the raw bytes received. - -[[pg-websocket-endpoints-listener]] -===== Listener Endpoints - -A WebSocket endpoint may implement the `org.eclipse.jetty.websocket.api.WebSocketListener` interface to receive WebSocket events: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=listenerEndpoint] ----- -<1> Your listener class implements `WebSocketListener`. - -====== Message Streaming Reads - -If you need to deal with large WebSocket messages, you may reduce the memory usage by streaming the message content. -For large WebSocket messages, the memory usage may be large due to the fact that the text or the bytes must be accumulated until the message is complete before delivering the message event. - -To stream textual or binary messages, you must implement interface `org.eclipse.jetty.websocket.api.WebSocketPartialListener` instead of `WebSocketListener`. - -Interface `WebSocketPartialListener` exposes one method for textual messages, and one method to binary messages that receive _chunks_ of, respectively, text and bytes that form the whole WebSocket message. - -You may accumulate the chunks yourself, or process each chunk as it arrives, or stream the chunks elsewhere, for example: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=streamingListenerEndpoint] ----- - -[[pg-websocket-endpoints-annotated]] -===== Annotated Endpoints - -A WebSocket endpoint may annotate methods with `org.eclipse.jetty.websocket.api.annotations.*` annotations to receive WebSocket events. -Each annotated method may take an optional `Session` argument as its first parameter: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=annotatedEndpoint] ----- -<1> Use the `@WebSocket` annotation at the class level to make it a WebSocket endpoint. -<2> Use the `@OnWebSocketConnect` annotation for the _connect_ event. -As this is the first event notified to the endpoint, you can configure the `Session` object. -<3> Use the `@OnWebSocketClose` annotation for the _close_ event. -The method may take an optional `Session` as first parameter. -<4> Use the `@OnWebSocketError` annotation for the _error_ event. -The method may take an optional `Session` as first parameter. -<5> Use the `@OnWebSocketMessage` annotation for the _message_ event, both for textual and binary messages. -The method may take an optional `Session` as first parameter. - -[NOTE] -==== -For binary messages, you may declare the annotated method with either or these two signatures: - -[source,java] ----- -@OnWebSocketMessage -public void methodName(byte[] bytes, int offset, int length) { ... } ----- - -or - -[source,java] ----- -@OnWebSocketMessage -public void methodName(ByteBuffer buffer) { ... } ----- -==== - -====== Message Streaming Reads - -If you need to deal with large WebSocket messages, you may reduce the memory usage by streaming the message content. - -To stream textual or binary messages, you still use the `@OnWebSocketMessage` annotation, but you change the signature of the method to take, respectively a `Reader` and an `InputStream`: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=streamingAnnotatedEndpoint] ----- - -[CAUTION] -==== -`Reader` or `InputStream` only offer blocking APIs, so if the remote peers are slow in sending the large WebSocket messages, reading threads may be blocked in `Reader.read(char[])` or `InputStream.read(byte[])`, possibly exhausting the thread pool. -==== - -[[pg-websocket-session]] -==== WebSocket Session - -A WebSocket session is the entity that offers an API to send data to the remote peer, to close the WebSocket connection, and to configure WebSocket connection parameters. - -[[pg-websocket-session-configure]] -===== Configuring the Session - -You may configure the WebSocket session behavior using the `org.eclipse.jetty.websocket.api.Session` APIs. -You want to do this as soon as you have access to the `Session` object, typically from the xref:pg-websocket-endpoints[_connect_ event] handler: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=sessionConfigure] ----- - -The settings that can be configured include: - -maxBinaryMessageSize:: -the maximum size in bytes of a binary message (which may be composed of multiple frames) that can be received. - -maxTextMessageSize:: -the maximum size in bytes of a text message (which may be composed of multiple frames) that can be received. - -maxFrameSize:: -the maximum payload size in bytes of any WebSocket frame that can be received. - -inputBufferSize:: -the input (read from network/transport layer) buffer size in bytes; it has no relationship with the WebSocket frame size or message size. - -outputBufferSize:: -the output (write to network/transport layer) buffer size in bytes; it has no relationship to the WebSocket frame size or message size. - -autoFragment:: -whether WebSocket frames are automatically fragmented to respect the maximum frame size. - -idleTimeout:: -the duration that a WebSocket connection may remain idle (that is, there is no network traffic, neither in read nor in write) before being closed by the implementation. - -Please refer to the `Session` link:{javadoc-url}/org/eclipse/jetty/websocket/api/Session.html[javadocs] for the complete list of configuration APIs. - -[[pg-websocket-session-send]] -===== Sending Data - -To send data to the remote peer, you need to obtain the `RemoteEndpoint` object from the `Session`, and then use its API to send data. - -`RemoteEndpoint` offers two styles of APIs to send data: - -* Blocking APIs, where the call returns when the data has been sent, or throws an `IOException` if the data cannot be sent. -* Non-blocking APIs, where a callback object is notified when the data has been sent, or when there was a failure sending the data. - -[[pg-websocket-session-send-blocking]] -====== Blocking APIs - -`RemoteEndpoint` blocking APIs throw `IOException`: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=sendBlocking] ----- - -Blocking APIs are simpler to use since they can be invoked one after the other sequentially. - -[CAUTION] -==== -Sending large messages to the remote peer may cause the sending thread to block, possibly exhausting the thread pool. -Consider using non-blocking APIs for large messages. -==== - -[[pg-websocket-session-send-non-blocking]] -====== Non-Blocking APIs - -`RemoteEndpoint` non-blocking APIs have an additional callback parameter: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=sendNonBlocking] ----- -<1> Non-blocking APIs require a `WriteCallback` parameter. -<2> Note how the second send must be performed from inside the callback. -<3> Sequential sends may throw `WritePendingException`. - -Non-blocking APIs are more difficult to use since you are required to meet the following condition: - -[IMPORTANT] -==== -You cannot initiate another send of any kind until the previous send is completed. - -For example, if you have initiated a text send, you cannot initiate a binary send, until the previous send has completed. - -Furthermore, if you have initiated a non-blocking send, you cannot initiate a blocking send, until the previous send has completed. -==== - -This requirement is necessary to avoid unbounded buffering that could lead to ``OutOfMemoryError``s. - -[CAUTION] -==== -We strongly recommend that you follow the condition above. - -However, there may be cases where you want to explicitly control the number of outgoing buffered messages using `RemoteEndpoint.setMaxOutgoingFrames(int)`. - -Remember that trying to control the number of outgoing buffered messages is very difficult and tricky; you may set `maxOutgoingFrames=4` and have a situation where 6 threads try to concurrently send messages: threads 1 to 4 will be able to successfully buffer their messages, thread 5 may fail, but thread 6 may succeed because one of the previous threads completed its send. -At this point you have an out-of-order message delivery that could be unexpected and very difficult to troubleshoot because it will happen non-deterministically. -==== - -While non-blocking APIs are more difficult to use, they don't block the sender thread and therefore use less resources, which in turn typically allows for greater scalability under load: with respect to blocking APIs, non-blocking APIs need less resources to cope with the same load. - -[[pg-websocket-session-send-stream]] -====== Streaming Send APIs - -If you need to send large WebSocket messages, you may reduce the memory usage by streaming the message content. - -Both blocking and non-blocking APIs offer `sendPartial*(...)` methods that allow you to send a chunk of the whole message at a time, therefore reducing the memory usage since it is not necessary to have the whole message `String` or `byte[]` in memory to send it. - -Streaming sends using blocking APIs is quite simple: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=streamSendBlocking] ----- - -Streaming sends using non-blocking APIs is more complicated, as you should wait (without blocking!) for the callbacks to complete. - -Fortunately, Jetty provides you with the `IteratingCallback` utility class (described in more details xref:pg-arch-io-echo[in this section]) which greatly simplify the use of non-blocking APIs: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=streamSendNonBlocking] ----- -<1> Implementing `WriteCallback` allows to pass `this` to `sendPartialBytes(...)`. -<2> The `process()` method is called iteratively when each `sendPartialBytes(...)` is completed. -<3> Send the message chunks. - -[[pg-websocket-session-ping]] -===== Sending Ping/Pong - -The WebSocket protocol defines two special frame, named `Ping` and `Pong` that may be interesting to applications for these use cases: - -* Calculate the round-trip time with the remote peer. -* Keep the connection from being closed due to idle timeout -- a heartbeat-like mechanism. - -To handle `Ping`/`Pong` events, you may implement interface `org.eclipse.jetty.websocket.api.WebSocketPingPongListener`. - -[NOTE] -==== -`Ping`/`Pong` events are not supported when using annotations. -==== - -`Ping` frames may contain opaque application bytes, and the WebSocket implementation replies to them with a `Pong` frame containing the same bytes: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=pingPongListener] ----- -<1> The WebSocket endpoint class must implement `WebSocketPingPongListener` - -[[pg-websocket-session-close]] -===== Closing the Session - -When you want to terminate the communication with the remote peer, you close the `Session`: - -[source,java,indent=0] ----- -include::{doc_code}/org/eclipse/jetty/docs/programming/WebSocketDocs.java[tags=sessionClose] ----- - -Closing a WebSocket `Session` carries a status code and a reason message that the remote peer can inspect in the _close_ event handler (see xref:pg-websocket-endpoints[this section]). - -[NOTE] -==== -The reason message is optional, and may be truncated to fit into the WebSocket frame sent to the client. -It is best to use short tokens such as `"shutdown"`, or `"idle_timeout"`, etc. or even application specific codes such as `"0001"` or `"00AF"` that can be converted by the application into more meaningful messages. -==== diff --git a/documentation/jetty-documentation/src/main/asciidoc/styles.css b/documentation/jetty-documentation/src/main/asciidoc/styles.css deleted file mode 100644 index e094ee81d1e1..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/styles.css +++ /dev/null @@ -1,20 +0,0 @@ -/* - * ======================================================================== - * Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0 which is available at - * https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 - * which is available at https://www.apache.org/licenses/LICENSE-2.0. - * - * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 - * ======================================================================== - */ - -#header, #content, #footnotes, #footer { - max-width: 80em; -} - -.listingblock > .title { - font-style: normal; -} diff --git a/documentation/jetty-documentation/src/main/asciidoc/toc.css b/documentation/jetty-documentation/src/main/asciidoc/toc.css deleted file mode 100644 index 6079be7f9ebb..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/toc.css +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ======================================================================== - * Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0 which is available at - * https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 - * which is available at https://www.apache.org/licenses/LICENSE-2.0. - * - * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 - * ======================================================================== - */ - -.hidden { - display: none; -} -.toc-current, .toc-current * { - font-weight: bold; -} -.toc-item { - padding-right: 0.4em; -} -.toc-toggle { - padding-right: 0.4em; - cursor: pointer; -} diff --git a/documentation/jetty-documentation/src/main/asciidoc/toc.js b/documentation/jetty-documentation/src/main/asciidoc/toc.js deleted file mode 100644 index ddbbe505e4bb..000000000000 --- a/documentation/jetty-documentation/src/main/asciidoc/toc.js +++ /dev/null @@ -1,134 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -document.addEventListener('DOMContentLoaded', () => dynamicTOC()); - -function dynamicTOC() { - const content = document.getElementById('content'); - // Bind a click listener to all section titles. - const sectionTitles = content.querySelectorAll('a.link'); - for (const sectionTitle of sectionTitles) { - sectionTitle.addEventListener('click', event => collapseThenExpand(hash(event.target))); - } - // Bind a click listener to all inline links to documentation sections. - const inlineLinks = content.querySelectorAll('p > a'); - for (const inlineLink of inlineLinks) { - const linkHash = inlineLink.hash || ''; - if (linkHash.startsWith('#')) { - inlineLink.addEventListener('click', event => collapseThenExpand(hash(event.target))); - } - } - - // Bind a click listener to all TOC titles. - const toc = document.getElementById('toc'); - const tocTitles = toc.querySelectorAll('a'); - for (const tocTitle of tocTitles) { - tocTitle.addEventListener('click', event => collapseThenExpand(hash(event.target))); - } - - // Add the icons to TOC nodes. - const nodes = toc.querySelectorAll('li'); - for (const node of nodes) { - const span = document.createElement('span'); - const css = span.classList; - if (node.querySelector(':scope > ul')) { - css.add('toc-toggle'); - // Font-Awesome classes. - css.add('fa'); - css.add('fa-caret-right'); - span.addEventListener('click', event => toggle(event.target)); - } else { - css.add('toc-item'); - // The "icon" is the • HTML entity. - span.appendChild(document.createTextNode('•')); - } - node.prepend(span); - } - - collapseThenExpand(document.location.hash); -} - -function hash(element) { - const a = element.closest('a'); - return a ? a.hash : null; -} - -function collapseThenExpand(hash) { - const toc = document.getElementById('toc'); - if (hash) { - const current = toc.querySelector('a.toc-current'); - if (current) { - current.classList.remove('toc-current'); - } - const anchor = toc.querySelector('a[href="' + hash + '"'); - if (anchor) { - anchor.classList.add('toc-current'); - collapse(toc); - expand(anchor.parentNode); - } - } else { - collapse(toc); - } -} - -function collapse(node) { - const sections = node.querySelectorAll('ul'); - for (const section of sections) { - const css = section.classList; - // Always show first levels TOC titles. - const alwaysShow = css.contains('sectlevel1') || css.contains('sectlevel2'); - if (!alwaysShow) { - css.add('hidden'); - } - } - // Show the collapsed icon. - const spans = node.querySelectorAll('span.toc-toggle'); - for (const span of spans) { - const css = span.classList; - css.remove('fa-caret-down'); - css.add('fa-caret-right'); - } -} - -function expand(node) { - const root = document.getElementById('toc').querySelector('ul'); - // Show the current node and its ancestors. - let parent = node; - while (parent !== root) { - // Show the node. - parent.classList.remove('hidden'); - // Show the expanded icon. - const span = parent.querySelector(':scope > span.toc-toggle'); - if (span) { - const css = span.classList; - css.remove('fa-caret-right'); - css.add('fa-caret-down'); - } - parent = parent.parentNode; - } - // Show the children. - const children = node.querySelector(':scope > ul'); - if (children) { - children.classList.remove('hidden'); - } -} - -function toggle(span) { - const css = span.classList; - const expanded = css.contains('fa-caret-down'); - if (expanded) { - collapse(span.parentNode); - } else { - expand(span.parentNode); - } -} diff --git a/documentation/jetty-documentation/src/main/assembly/html.xml b/documentation/jetty-documentation/src/main/assembly/html.xml deleted file mode 100644 index a24dc02057d5..000000000000 --- a/documentation/jetty-documentation/src/main/assembly/html.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - html - - zip - - ${project.version} - - - ${project.basedir}/target/html - - - ** - - - - diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/ComponentDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/ComponentDocs.java deleted file mode 100644 index f309dad3af35..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/ComponentDocs.java +++ /dev/null @@ -1,284 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; - -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.util.component.AbstractLifeCycle; -import org.eclipse.jetty.util.component.Container; -import org.eclipse.jetty.util.component.ContainerLifeCycle; -import org.eclipse.jetty.util.component.LifeCycle; - -import static java.lang.System.Logger.Level.INFO; - -@SuppressWarnings("unused") -public class ComponentDocs -{ - public void start() throws Exception - { - // tag::start[] - class Monitor extends AbstractLifeCycle - { - } - - class Root extends ContainerLifeCycle - { - // Monitor is an internal component. - private final Monitor monitor = new Monitor(); - - public Root() - { - // The Monitor life cycle is managed by Root. - addManaged(monitor); - } - } - - class Service extends ContainerLifeCycle - { - // An instance of the Java scheduler service. - private ScheduledExecutorService scheduler; - - @Override - protected void doStart() throws Exception - { - // Java's schedulers cannot be restarted, so they must - // be created anew every time their container is started. - scheduler = Executors.newSingleThreadScheduledExecutor(); - // Even if Java scheduler does not implement - // LifeCycle, make it part of the component tree. - addBean(scheduler); - // Start all the children beans. - super.doStart(); - } - - @Override - protected void doStop() throws Exception - { - // Perform the opposite operations that were - // performed in doStart(), in reverse order. - super.doStop(); - removeBean(scheduler); - scheduler.shutdown(); - } - } - - // Create a Root instance. - Root root = new Root(); - - // Create a Service instance. - Service service = new Service(); - - // Link the components. - root.addBean(service); - - // Start the root component to - // start the whole component tree. - root.start(); - // end::start[] - } - - public void restart() throws Exception - { - // tag::restart[] - class Root extends ContainerLifeCycle - { - } - - class Service extends ContainerLifeCycle - { - // An instance of the Java scheduler service. - private ScheduledExecutorService scheduler; - - @Override - protected void doStart() throws Exception - { - // Java's schedulers cannot be restarted, so they must - // be created anew every time their container is started. - scheduler = Executors.newSingleThreadScheduledExecutor(); - // Even if Java scheduler does not implement - // LifeCycle, make it part of the component tree. - addBean(scheduler); - // Start all the children beans. - super.doStart(); - } - - @Override - protected void doStop() throws Exception - { - // Perform the opposite operations that were - // performed in doStart(), in reverse order. - super.doStop(); - removeBean(scheduler); - scheduler.shutdown(); - } - } - - Root root = new Root(); - Service service = new Service(); - root.addBean(service); - - // Start the Root component. - root.start(); - - // Stop temporarily Service without stopping the Root. - service.stop(); - - // Restart Service. - service.start(); - // end::restart[] - } - - public void getBeans() throws Exception - { - // tag::getBeans[] - class Root extends ContainerLifeCycle - { - } - - class Service extends ContainerLifeCycle - { - private ScheduledExecutorService scheduler; - - @Override - protected void doStart() throws Exception - { - scheduler = Executors.newSingleThreadScheduledExecutor(); - addBean(scheduler); - super.doStart(); - } - - @Override - protected void doStop() throws Exception - { - super.doStop(); - removeBean(scheduler); - scheduler.shutdown(); - } - } - - Root root = new Root(); - Service service = new Service(); - root.addBean(service); - - // Start the Root component. - root.start(); - - // Find all the direct children of root. - Collection children = root.getBeans(); - // children contains only service - - // Find all descendants of root that are instance of a particular class. - Collection schedulers = root.getContainedBeans(ScheduledExecutorService.class); - // schedulers contains the service scheduler. - // end::getBeans[] - } - - public void lifecycleListener() - { - // tag::lifecycleListener[] - Server server = new Server(); - - // Add an event listener of type LifeCycle.Listener. - server.addEventListener(new LifeCycle.Listener() - { - @Override - public void lifeCycleStarted(LifeCycle lifeCycle) - { - System.getLogger("server").log(INFO, "Server {0} has been started", lifeCycle); - } - - @Override - public void lifeCycleFailure(LifeCycle lifeCycle, Throwable failure) - { - System.getLogger("server").log(INFO, "Server {0} failed to start", lifeCycle, failure); - } - - @Override - public void lifeCycleStopped(LifeCycle lifeCycle) - { - System.getLogger("server").log(INFO, "Server {0} has been stopped", lifeCycle); - } - }); - // end::lifecycleListener[] - } - - public void containerListener() - { - // tag::containerListener[] - Server server = new Server(); - - // Add an event listener of type LifeCycle.Listener. - server.addEventListener(new Container.Listener() - { - @Override - public void beanAdded(Container parent, Object child) - { - System.getLogger("server").log(INFO, "Added bean {1} to {0}", parent, child); - } - - @Override - public void beanRemoved(Container parent, Object child) - { - System.getLogger("server").log(INFO, "Removed bean {1} from {0}", parent, child); - } - }); - // end::containerListener[] - } - - public void containerSiblings() - { - // tag::containerSiblings[] - class Parent extends ContainerLifeCycle - { - } - - class Child - { - } - - // The older child takes care of its siblings. - class OlderChild extends Child implements Container.Listener - { - private Set siblings = new HashSet<>(); - - @Override - public void beanAdded(Container parent, Object child) - { - siblings.add(child); - } - - @Override - public void beanRemoved(Container parent, Object child) - { - siblings.remove(child); - } - } - - Parent parent = new Parent(); - - Child older = new OlderChild(); - // The older child is a child bean _and_ a listener. - parent.addBean(older); - - Child younger = new Child(); - // Adding a younger child will notify the older child. - parent.addBean(younger); - // end::containerSiblings[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/HTTP2Docs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/HTTP2Docs.java deleted file mode 100644 index 5bc4f08d1766..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/HTTP2Docs.java +++ /dev/null @@ -1,92 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.util.Queue; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentLinkedQueue; - -import org.eclipse.jetty.http.HttpFields; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.http.HttpURI; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.http.MetaData; -import org.eclipse.jetty.http2.api.Session; -import org.eclipse.jetty.http2.api.Stream; -import org.eclipse.jetty.http2.client.HTTP2Client; -import org.eclipse.jetty.http2.frames.DataFrame; -import org.eclipse.jetty.http2.frames.HeadersFrame; -import org.eclipse.jetty.util.Callback; - -@SuppressWarnings("unused") -public class HTTP2Docs -{ - public void dataDemanded() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - CompletableFuture sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, null, true); - - // tag::dataDemanded[] - class Chunk - { - private final ByteBuffer buffer; - private final Callback callback; - - Chunk(ByteBuffer buffer, Callback callback) - { - this.buffer = buffer; - this.callback = callback; - } - } - - // A queue that consumers poll to consume content asynchronously. - Queue dataQueue = new ConcurrentLinkedQueue<>(); - - // Implementation of Stream.Listener.onDataDemanded(...) - // in case of asynchronous content consumption and demand. - Stream.Listener listener = new Stream.Listener.Adapter() - { - @Override - public void onDataDemanded(Stream stream, DataFrame frame, Callback callback) - { - // Get the content buffer. - ByteBuffer buffer = frame.getData(); - - // Store buffer to consume it asynchronously, and wrap the callback. - dataQueue.offer(new Chunk(buffer, Callback.from(() -> - { - // When the buffer has been consumed, then: - // A) succeed the nested callback. - callback.succeeded(); - // B) demand more DATA frames. - stream.demand(1); - }, callback::failed))); - - // Do not demand more content here, to avoid to overflow the queue. - } - }; - // end::dataDemanded[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/JMXDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/JMXDocs.java deleted file mode 100644 index 4ffdee236423..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/JMXDocs.java +++ /dev/null @@ -1,271 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming; - -import java.lang.management.ManagementFactory; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; -import javax.rmi.ssl.SslRMIClientSocketFactory; - -import org.eclipse.jetty.client.HttpClient; -import org.eclipse.jetty.jmx.ConnectorServer; -import org.eclipse.jetty.jmx.MBeanContainer; -import org.eclipse.jetty.jmx.ObjectMBean; -import org.eclipse.jetty.server.Server; -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; -import org.eclipse.jetty.util.ssl.SslContextFactory; - -@SuppressWarnings("unused") -public class JMXDocs -{ - public void server() - { - // tag::server[] - Server server = new Server(); - - // Create an MBeanContainer with the platform MBeanServer. - MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); - - // Add MBeanContainer to the root component. - server.addBean(mbeanContainer); - // end::server[] - } - - public void client() - { - // tag::client[] - HttpClient httpClient = new HttpClient(); - - // Create an MBeanContainer with the platform MBeanServer. - MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); - - // Add MBeanContainer to the root component. - httpClient.addBean(mbeanContainer); - // end::client[] - } - - public void remote() throws Exception - { - // tag::remote[] - Server server = new Server(); - - // Setup Jetty JMX. - MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); - server.addBean(mbeanContainer); - - // Setup ConnectorServer. - - // Bind the RMI server to the wildcard address and port 1999. - // Bind the RMI registry to the wildcard address and port 1099. - JMXServiceURL jmxURL = new JMXServiceURL("rmi", null, 1999, "/jndi/rmi:///jmxrmi"); - ConnectorServer jmxServer = new ConnectorServer(jmxURL, "org.eclipse.jetty.jmx:name=rmiconnectorserver"); - - // Add ConnectorServer as a bean, so it is started - // with the Server and also exported as MBean. - server.addBean(jmxServer); - - server.start(); - // end::remote[] - } - - public static void main(String[] args) throws Exception - { - new JMXDocs().remote(); - } - - public void remoteAuthorization() throws Exception - { - // tag::remoteAuthorization[] - Server server = new Server(); - - // Setup Jetty JMX. - MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); - server.addBean(mbeanContainer); - - // Setup ConnectorServer. - JMXServiceURL jmxURL = new JMXServiceURL("rmi", null, 1099, "/jndi/rmi:///jmxrmi"); - Map env = new HashMap<>(); - env.put("com.sun.management.jmxremote.access.file", "/path/to/users.access"); - env.put("com.sun.management.jmxremote.password.file", "/path/to/users.password"); - ConnectorServer jmxServer = new ConnectorServer(jmxURL, env, "org.eclipse.jetty.jmx:name=rmiconnectorserver"); - server.addBean(jmxServer); - - server.start(); - // end::remoteAuthorization[] - } - - public void tlsRemote() throws Exception - { - // tag::tlsRemote[] - Server server = new Server(); - - // Setup Jetty JMX. - MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer()); - server.addBean(mbeanContainer); - - // Setup SslContextFactory. - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore"); - sslContextFactory.setKeyStorePassword("secret"); - - // Setup ConnectorServer with SslContextFactory. - JMXServiceURL jmxURL = new JMXServiceURL("rmi", null, 1099, "/jndi/rmi:///jmxrmi"); - ConnectorServer jmxServer = new ConnectorServer(jmxURL, null, "org.eclipse.jetty.jmx:name=rmiconnectorserver", sslContextFactory); - server.addBean(jmxServer); - - server.start(); - // end::tlsRemote[] - } - - public void tlsJMXConnector() throws Exception - { - // tag::tlsJMXConnector[] - // System properties necessary for an RMI client to trust a self-signed certificate. - System.setProperty("javax.net.ssl.trustStore", "/path/to/trustStore"); - System.setProperty("javax.net.ssl.trustStorePassword", "secret"); - - JMXServiceURL jmxURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://domain.com:1100/jmxrmi"); - - Map clientEnv = new HashMap<>(); - // Required to connect to the RMI registry via TLS. - clientEnv.put(ConnectorServer.RMI_REGISTRY_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new SslRMIClientSocketFactory()); - - try (JMXConnector client = JMXConnectorFactory.connect(jmxURL, clientEnv)) - { - Set names = client.getMBeanServerConnection().queryNames(null, null); - } - // end::tlsJMXConnector[] - } - - public void jmxAnnotation() throws Exception - { - // tag::jmxAnnotation[] - // Annotate the class with @ManagedObject and provide a description. - @ManagedObject("Services that provide useful features") - class Services - { - private final Map services = new ConcurrentHashMap<>(); - private boolean enabled = true; - - // A read-only attribute with description. - @ManagedAttribute(value = "The number of services", readonly = true) - public int getServiceCount() - { - return services.size(); - } - - // A read-write attribute with description. - // Only the getter is annotated. - @ManagedAttribute(value = "Whether the services are enabled") - public boolean isEnabled() - { - return enabled; - } - - // There is no need to annotate the setter. - public void setEnabled(boolean enabled) - { - this.enabled = enabled; - } - - // An operation with description and impact. - // The @Name annotation is used to annotate parameters - // for example to display meaningful parameter names. - @ManagedOperation(value = "Retrieves the service with the given name", impact = "INFO") - public Object getService(@Name(value = "serviceName") String n) - { - return services.get(n); - } - } - // end::jmxAnnotation[] - } - - public void jmxCustomMBean() - { - // tag::jmxCustomMBean[] - //package com.acme; - @ManagedObject - class Service - { - } - - //package com.acme.jmx; - class ServiceMBean extends ObjectMBean - { - ServiceMBean(Object service) - { - super(service); - } - } - // end::jmxCustomMBean[] - } - - public void jmxCustomMBeanOverride() - { - // tag::jmxCustomMBeanOverride[] - //package com.acme; - // No Jetty JMX annotations. - class CountService - { - private int count; - - public int getCount() - { - return count; - } - - public void addCount(int value) - { - count += value; - } - } - - //package com.acme.jmx; - @ManagedObject("the count service") - class CountServiceMBean extends ObjectMBean - { - public CountServiceMBean(Object service) - { - super(service); - } - - private CountService getCountService() - { - return (CountService)super.getManagedObject(); - } - - @ManagedAttribute("the current service count") - public int getCount() - { - return getCountService().getCount(); - } - - @ManagedOperation(value = "adds the given value to the service count", impact = "ACTION") - public void addCount(@Name("count delta") int value) - { - getCountService().addCount(value); - } - } - // end::jmxCustomMBeanOverride[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/SelectorManagerDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/SelectorManagerDocs.java deleted file mode 100644 index 74ced90a8887..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/SelectorManagerDocs.java +++ /dev/null @@ -1,253 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Map; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.io.AbstractConnection; -import org.eclipse.jetty.io.EndPoint; -import org.eclipse.jetty.io.SelectorManager; -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.IteratingCallback; - -@SuppressWarnings("unused") -public class SelectorManagerDocs -{ - // tag::connect[] - public void connect(SelectorManager selectorManager, Map context) throws IOException - { - String host = "host"; - int port = 8080; - - // Create an unconnected SocketChannel. - SocketChannel socketChannel = SocketChannel.open(); - socketChannel.configureBlocking(false); - - // Connect and register to Jetty. - if (socketChannel.connect(new InetSocketAddress(host, port))) - selectorManager.accept(socketChannel, context); - else - selectorManager.connect(socketChannel, context); - } - // end::connect[] - - // tag::accept[] - public void accept(ServerSocketChannel acceptor, SelectorManager selectorManager) throws IOException - { - // Wait until a client connects. - SocketChannel socketChannel = acceptor.accept(); - socketChannel.configureBlocking(false); - - // Accept and register to Jetty. - Object attachment = null; - selectorManager.accept(socketChannel, attachment); - } - // end::accept[] - - public void connection() - { - // tag::connection[] - // Extend AbstractConnection to inherit basic implementation. - class MyConnection extends AbstractConnection - { - public MyConnection(EndPoint endPoint, Executor executor) - { - super(endPoint, executor); - } - - @Override - public void onOpen() - { - super.onOpen(); - - // Declare interest for fill events. - fillInterested(); - } - - @Override - public void onFillable() - { - // Called when a fill event happens. - } - } - // end::connection[] - } - - public void echoWrong() - { - // tag::echo-wrong[] - class WrongEchoConnection extends AbstractConnection implements Callback - { - public WrongEchoConnection(EndPoint endPoint, Executor executor) - { - super(endPoint, executor); - } - - @Override - public void onOpen() - { - super.onOpen(); - - // Declare interest for fill events. - fillInterested(); - } - - @Override - public void onFillable() - { - try - { - ByteBuffer buffer = BufferUtil.allocate(1024); - int filled = getEndPoint().fill(buffer); - if (filled > 0) - { - // Filled some bytes, echo them back. - getEndPoint().write(this, buffer); - } - else if (filled == 0) - { - // No more bytes to fill, declare - // again interest for fill events. - fillInterested(); - } - else - { - // The other peer closed the - // connection, close it back. - getEndPoint().close(); - } - } - catch (Exception x) - { - getEndPoint().close(x); - } - } - - @Override - public void succeeded() - { - // The write is complete, fill again. - onFillable(); - } - - @Override - public void failed(Throwable x) - { - getEndPoint().close(x); - } - } - // end::echo-wrong[] - } - - public void echoCorrect() - { - // tag::echo-correct[] - class EchoConnection extends AbstractConnection - { - private final IteratingCallback callback = new EchoIteratingCallback(); - - public EchoConnection(EndPoint endp, Executor executor) - { - super(endp, executor); - } - - @Override - public void onOpen() - { - super.onOpen(); - - // Declare interest for fill events. - fillInterested(); - } - - @Override - public void onFillable() - { - // Start the iteration loop that reads and echoes back. - callback.iterate(); - } - - class EchoIteratingCallback extends IteratingCallback - { - private ByteBuffer buffer; - - @Override - protected Action process() throws Throwable - { - // Obtain a buffer if we don't already have one. - if (buffer == null) - buffer = BufferUtil.allocate(1024); - - int filled = getEndPoint().fill(buffer); - if (filled > 0) - { - // We have filled some bytes, echo them back. - getEndPoint().write(this, buffer); - - // Signal that the iteration should resume - // when the write() operation is completed. - return Action.SCHEDULED; - } - else if (filled == 0) - { - // We don't need the buffer anymore, so - // don't keep it around while we are idle. - buffer = null; - - // No more bytes to read, declare - // again interest for fill events. - fillInterested(); - - // Signal that the iteration is now IDLE. - return Action.IDLE; - } - else - { - // The other peer closed the connection, - // the iteration completed successfully. - return Action.SUCCEEDED; - } - } - - @Override - protected void onCompleteSuccess() - { - // The iteration completed successfully. - getEndPoint().close(); - } - - @Override - protected void onCompleteFailure(Throwable cause) - { - // The iteration completed with a failure. - getEndPoint().close(cause); - } - - @Override - public InvocationType getInvocationType() - { - return InvocationType.NON_BLOCKING; - } - } - } - // end::echo-correct[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/WebSocketDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/WebSocketDocs.java deleted file mode 100644 index 9433a1d49194..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/WebSocketDocs.java +++ /dev/null @@ -1,492 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.nio.ByteBuffer; -import java.nio.file.Path; -import java.time.Duration; - -import org.eclipse.jetty.util.IteratingCallback; -import org.eclipse.jetty.util.NanoTime; -import org.eclipse.jetty.websocket.api.RemoteEndpoint; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.StatusCode; -import org.eclipse.jetty.websocket.api.WebSocketListener; -import org.eclipse.jetty.websocket.api.WebSocketPartialListener; -import org.eclipse.jetty.websocket.api.WebSocketPingPongListener; -import org.eclipse.jetty.websocket.api.WriteCallback; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError; -import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; -import org.eclipse.jetty.websocket.api.annotations.WebSocket; - -@SuppressWarnings("unused") -public class WebSocketDocs -{ - @SuppressWarnings("InnerClassMayBeStatic") - // tag::listenerEndpoint[] - public class ListenerEndPoint implements WebSocketListener // <1> - { - private Session session; - - @Override - public void onWebSocketConnect(Session session) - { - // The WebSocket connection is established. - - // Store the session to be able to send data to the remote peer. - this.session = session; - - // You may configure the session. - session.setMaxTextMessageSize(16 * 1024); - - // You may immediately send a message to the remote peer. - session.getRemote().sendString("connected", WriteCallback.NOOP); - } - - @Override - public void onWebSocketClose(int statusCode, String reason) - { - // The WebSocket connection is closed. - - // You may dispose resources. - disposeResources(); - } - - @Override - public void onWebSocketError(Throwable cause) - { - // The WebSocket connection failed. - - // You may log the error. - cause.printStackTrace(); - - // You may dispose resources. - disposeResources(); - } - - @Override - public void onWebSocketText(String message) - { - // A WebSocket textual message is received. - - // You may echo it back if it matches certain criteria. - if (message.startsWith("echo:")) - session.getRemote().sendString(message.substring("echo:".length()), WriteCallback.NOOP); - } - - @Override - public void onWebSocketBinary(byte[] payload, int offset, int length) - { - // A WebSocket binary message is received. - - // Save only PNG images. - byte[] pngBytes = new byte[]{(byte)0x89, 'P', 'N', 'G'}; - for (int i = 0; i < pngBytes.length; ++i) - { - if (pngBytes[i] != payload[offset + i]) - return; - } - savePNGImage(payload, offset, length); - } - } - // end::listenerEndpoint[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::streamingListenerEndpoint[] - public class StreamingListenerEndpoint implements WebSocketPartialListener - { - private Path textPath; - - @Override - public void onWebSocketPartialText(String payload, boolean fin) - { - // Forward chunks to external REST service. - forwardToREST(payload, fin); - } - - @Override - public void onWebSocketPartialBinary(ByteBuffer payload, boolean fin) - { - // Save chunks to file. - appendToFile(payload, fin); - } - } - // end::streamingListenerEndpoint[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::annotatedEndpoint[] - @WebSocket // <1> - public class AnnotatedEndPoint - { - private Session session; - - @OnWebSocketConnect // <2> - public void onConnect(Session session) - { - // The WebSocket connection is established. - - // Store the session to be able to send data to the remote peer. - this.session = session; - - // You may configure the session. - session.setMaxTextMessageSize(16 * 1024); - - // You may immediately send a message to the remote peer. - session.getRemote().sendString("connected", WriteCallback.NOOP); - } - - @OnWebSocketClose // <3> - public void onClose(int statusCode, String reason) - { - // The WebSocket connection is closed. - - // You may dispose resources. - disposeResources(); - } - - @OnWebSocketError // <4> - public void onError(Throwable cause) - { - // The WebSocket connection failed. - - // You may log the error. - cause.printStackTrace(); - - // You may dispose resources. - disposeResources(); - } - - @OnWebSocketMessage // <5> - public void onTextMessage(Session session, String message) // <3> - { - // A WebSocket textual message is received. - - // You may echo it back if it matches certain criteria. - if (message.startsWith("echo:")) - session.getRemote().sendString(message.substring("echo:".length()), WriteCallback.NOOP); - } - - @OnWebSocketMessage // <5> - public void onBinaryMessage(byte[] payload, int offset, int length) - { - // A WebSocket binary message is received. - - // Save only PNG images. - byte[] pngBytes = new byte[]{(byte)0x89, 'P', 'N', 'G'}; - for (int i = 0; i < pngBytes.length; ++i) - { - if (pngBytes[i] != payload[offset + i]) - return; - } - savePNGImage(payload, offset, length); - } - } - // end::annotatedEndpoint[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::streamingAnnotatedEndpoint[] - @WebSocket - public class StreamingAnnotatedEndpoint - { - @OnWebSocketMessage - public void onTextMessage(Reader reader) - { - // Read chunks and forward. - forwardToREST(reader); - } - - @OnWebSocketMessage - public void onBinaryMessage(InputStream stream) - { - // Save chunks to file. - appendToFile(stream); - } - } - // end::streamingAnnotatedEndpoint[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::sessionConfigure[] - public class ConfigureEndpoint implements WebSocketListener - { - @Override - public void onWebSocketConnect(Session session) - { - // Configure the max length of incoming messages. - session.setMaxTextMessageSize(16 * 1024); - - // Configure the idle timeout. - session.setIdleTimeout(Duration.ofSeconds(30)); - } - } - // end::sessionConfigure[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::sendBlocking[] - @WebSocket - public class BlockingSendEndpoint - { - @OnWebSocketMessage - public void onText(Session session, String text) - { - // Obtain the RemoteEndpoint APIs. - RemoteEndpoint remote = session.getRemote(); - - try - { - // Send textual data to the remote peer. - remote.sendString("data"); - - // Send binary data to the remote peer. - ByteBuffer bytes = readImageFromFile(); - remote.sendBytes(bytes); - - // Send a PING frame to the remote peer. - remote.sendPing(ByteBuffer.allocate(8).putLong(NanoTime.now()).flip()); - } - catch (IOException x) - { - // No need to rethrow or close the session. - System.getLogger("websocket").log(System.Logger.Level.WARNING, "could not send data", x); - } - } - } - // end::sendBlocking[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::sendNonBlocking[] - @WebSocket - public class NonBlockingSendEndpoint - { - @OnWebSocketMessage - public void onText(Session session, String text) - { - // Obtain the RemoteEndpoint APIs. - RemoteEndpoint remote = session.getRemote(); - - // Send textual data to the remote peer. - remote.sendString("data", new WriteCallback() // <1> - { - @Override - public void writeSuccess() - { - // Send binary data to the remote peer. - ByteBuffer bytes = readImageFromFile(); - remote.sendBytes(bytes, new WriteCallback() // <2> - { - @Override - public void writeSuccess() - { - // Both sends succeeded. - } - - @Override - public void writeFailed(Throwable x) - { - System.getLogger("websocket").log(System.Logger.Level.WARNING, "could not send binary data", x); - } - }); - } - - @Override - public void writeFailed(Throwable x) - { - // No need to rethrow or close the session. - System.getLogger("websocket").log(System.Logger.Level.WARNING, "could not send textual data", x); - } - }); - - // remote.sendString("wrong", WriteCallback.NOOP); // May throw WritePendingException! <3> - } - } - // end::sendNonBlocking[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::streamSendBlocking[] - @WebSocket - public class StreamSendBlockingEndpoint - { - @OnWebSocketMessage - public void onText(Session session, String text) - { - try - { - RemoteEndpoint remote = session.getRemote(); - while (true) - { - ByteBuffer chunk = readChunkToSend(); - if (chunk == null) - { - // No more bytes, finish the WebSocket message. - remote.sendPartialBytes(ByteBuffer.allocate(0), true); - break; - } - else - { - // Send the chunk. - remote.sendPartialBytes(chunk, false); - } - } - } - catch (IOException x) - { - x.printStackTrace(); - } - } - } - // end::streamSendBlocking[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::streamSendNonBlocking[] - @WebSocket - public class StreamSendNonBlockingEndpoint - { - @OnWebSocketMessage - public void onText(Session session, String text) - { - RemoteEndpoint remote = session.getRemote(); - new Sender(remote).iterate(); - } - - private class Sender extends IteratingCallback implements WriteCallback // <1> - { - private final RemoteEndpoint remote; - private boolean finished; - - private Sender(RemoteEndpoint remote) - { - this.remote = remote; - } - - @Override - protected Action process() throws Throwable // <2> - { - if (finished) - return Action.SUCCEEDED; - - ByteBuffer chunk = readChunkToSend(); - if (chunk == null) - { - // No more bytes, finish the WebSocket message. - remote.sendPartialBytes(ByteBuffer.allocate(0), true, this); // <3> - finished = true; - return Action.SCHEDULED; - } - else - { - // Send the chunk. - remote.sendPartialBytes(ByteBuffer.allocate(0), false, this); // <3> - return Action.SCHEDULED; - } - } - - @Override - public void writeSuccess() - { - // When the send succeeds, succeed this IteratingCallback. - succeeded(); - } - - @Override - public void writeFailed(Throwable x) - { - // When the send fails, fail this IteratingCallback. - failed(x); - } - - @Override - protected void onCompleteFailure(Throwable x) - { - x.printStackTrace(); - } - } - } - // end::streamSendNonBlocking[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::pingPongListener[] - public class RoundTripListenerEndpoint implements WebSocketPingPongListener // <1> - { - @Override - public void onWebSocketConnect(Session session) - { - // Send to the remote peer the local nanoTime. - ByteBuffer buffer = ByteBuffer.allocate(8).putLong(NanoTime.now()).flip(); - session.getRemote().sendPing(buffer, WriteCallback.NOOP); - } - - @Override - public void onWebSocketPong(ByteBuffer payload) - { - // The remote peer echoed back the local nanoTime. - long start = payload.getLong(); - - // Calculate the round-trip time. - long roundTrip = NanoTime.since(start); - } - } - // end::pingPongListener[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::sessionClose[] - @WebSocket - public class CloseEndpoint - { - @OnWebSocketMessage - public void onText(Session session, String text) - { - if ("close".equalsIgnoreCase(text)) - session.close(StatusCode.NORMAL, "bye"); - } - } - // end::sessionClose[] - - private static void forwardToREST(String payload, boolean fin) - { - } - - private static void forwardToREST(Reader reader) - { - } - - private static void appendToFile(ByteBuffer payload, boolean fin) - { - } - - private static void appendToFile(InputStream stream) - { - } - - private static void disposeResources() - { - } - - private static void savePNGImage(byte[] payload, int offset, int length) - { - } - - private static ByteBuffer readImageFromFile() - { - return null; - } - - private static ByteBuffer readChunkToSend() - { - return null; - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java deleted file mode 100644 index 48b155b91e70..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/ClientConnectorDocs.java +++ /dev/null @@ -1,439 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.client; - -import java.io.ByteArrayOutputStream; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; -import java.util.function.Consumer; - -import org.eclipse.jetty.io.AbstractConnection; -import org.eclipse.jetty.io.ClientConnectionFactory; -import org.eclipse.jetty.io.ClientConnector; -import org.eclipse.jetty.io.EndPoint; -import org.eclipse.jetty.io.SelectorManager; -import org.eclipse.jetty.io.ssl.SslClientConnectionFactory; -import org.eclipse.jetty.io.ssl.SslConnection; -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.Promise; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler; -import org.eclipse.jetty.util.thread.Scheduler; - -import static java.lang.System.Logger.Level.INFO; - -@SuppressWarnings("unused") -public class ClientConnectorDocs -{ - public void simplest() throws Exception - { - // tag::simplest[] - ClientConnector clientConnector = new ClientConnector(); - clientConnector.start(); - // end::simplest[] - } - - public void typical() throws Exception - { - // tag::typical[] - // Create and configure the SslContextFactory. - SslContextFactory.Client sslContextFactory = new SslContextFactory.Client(); - sslContextFactory.addExcludeProtocols("TLSv1", "TLSv1.1"); - - // Create and configure the thread pool. - QueuedThreadPool threadPool = new QueuedThreadPool(); - threadPool.setName("client"); - - // Create and configure the ClientConnector. - ClientConnector clientConnector = new ClientConnector(); - clientConnector.setSslContextFactory(sslContextFactory); - clientConnector.setExecutor(threadPool); - clientConnector.start(); - // end::typical[] - } - - public void advanced() throws Exception - { - // tag::advanced[] - class CustomClientConnector extends ClientConnector - { - @Override - protected SelectorManager newSelectorManager() - { - return new ClientSelectorManager(getExecutor(), getScheduler(), getSelectors()) - { - @Override - protected void endPointOpened(EndPoint endpoint) - { - System.getLogger("endpoint").log(INFO, "opened %s", endpoint); - } - - @Override - protected void endPointClosed(EndPoint endpoint) - { - System.getLogger("endpoint").log(INFO, "closed %s", endpoint); - } - }; - } - } - - // Create and configure the thread pool. - QueuedThreadPool threadPool = new QueuedThreadPool(); - threadPool.setName("client"); - - // Create and configure the scheduler. - Scheduler scheduler = new ScheduledExecutorScheduler("scheduler-client", false); - - // Create and configure the custom ClientConnector. - CustomClientConnector clientConnector = new CustomClientConnector(); - clientConnector.setExecutor(threadPool); - clientConnector.setScheduler(scheduler); - clientConnector.start(); - // end::advanced[] - } - - public void connect() throws Exception - { - // tag::connect[] - class CustomConnection extends AbstractConnection - { - public CustomConnection(EndPoint endPoint, Executor executor) - { - super(endPoint, executor); - } - - @Override - public void onOpen() - { - super.onOpen(); - System.getLogger("connection").log(INFO, "Opened connection {0}", this); - } - - @Override - public void onFillable() - { - } - } - - ClientConnector clientConnector = new ClientConnector(); - clientConnector.start(); - - String host = "serverHost"; - int port = 8080; - SocketAddress address = new InetSocketAddress(host, port); - - // The ClientConnectionFactory that creates CustomConnection instances. - ClientConnectionFactory connectionFactory = (endPoint, context) -> - { - System.getLogger("connection").log(INFO, "Creating connection for {0}", endPoint); - return new CustomConnection(endPoint, clientConnector.getExecutor()); - }; - - // The Promise to notify of connection creation success or failure. - CompletableFuture connectionPromise = new Promise.Completable<>(); - - // Populate the context with the mandatory keys to create and obtain connections. - Map context = new HashMap<>(); - context.put(ClientConnector.CLIENT_CONNECTION_FACTORY_CONTEXT_KEY, connectionFactory); - context.put(ClientConnector.CONNECTION_PROMISE_CONTEXT_KEY, connectionPromise); - clientConnector.connect(address, context); - - // Use the Connection when it's available. - - // Use it in a non-blocking way via CompletableFuture APIs. - connectionPromise.whenComplete((connection, failure) -> - { - System.getLogger("connection").log(INFO, "Created connection for {0}", connection); - }); - - // Alternatively, you can block waiting for the connection (or a failure). - // CustomConnection connection = connectionPromise.get(); - // end::connect[] - } - - public void telnet() throws Exception - { - // tag::telnet[] - class TelnetConnection extends AbstractConnection - { - private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - private Consumer consumer; - - public TelnetConnection(EndPoint endPoint, Executor executor) - { - super(endPoint, executor); - } - - @Override - public void onOpen() - { - super.onOpen(); - - // Declare interest for fill events. - fillInterested(); - } - - @Override - public void onFillable() - { - try - { - ByteBuffer buffer = BufferUtil.allocate(1024); - while (true) - { - int filled = getEndPoint().fill(buffer); - if (filled > 0) - { - while (buffer.hasRemaining()) - { - // Search for newline. - byte read = buffer.get(); - if (read == '\n') - { - // Notify the consumer of the line. - consumer.accept(bytes.toString(StandardCharsets.UTF_8)); - bytes.reset(); - } - else - { - bytes.write(read); - } - } - } - else if (filled == 0) - { - // No more bytes to fill, declare - // again interest for fill events. - fillInterested(); - return; - } - else - { - // The other peer closed the - // connection, close it back. - getEndPoint().close(); - return; - } - } - } - catch (Exception x) - { - getEndPoint().close(x); - } - } - - public void onLine(Consumer consumer) - { - this.consumer = consumer; - } - - public void writeLine(String line, Callback callback) - { - line = line + "\r\n"; - getEndPoint().write(callback, ByteBuffer.wrap(line.getBytes(StandardCharsets.UTF_8))); - } - } - - ClientConnector clientConnector = new ClientConnector(); - clientConnector.start(); - - String host = "wikipedia.org"; - int port = 80; - SocketAddress address = new InetSocketAddress(host, port); - - ClientConnectionFactory connectionFactory = (endPoint, context) -> - new TelnetConnection(endPoint, clientConnector.getExecutor()); - - CompletableFuture connectionPromise = new Promise.Completable<>(); - - Map context = new HashMap<>(); - context.put(ClientConnector.CLIENT_CONNECTION_FACTORY_CONTEXT_KEY, connectionFactory); - context.put(ClientConnector.CONNECTION_PROMISE_CONTEXT_KEY, connectionPromise); - clientConnector.connect(address, context); - - connectionPromise.whenComplete((connection, failure) -> - { - if (failure == null) - { - // Register a listener that receives string lines. - connection.onLine(line -> System.getLogger("app").log(INFO, "line: {0}", line)); - - // Write a line. - connection.writeLine("" + - "GET / HTTP/1.0\r\n" + - "", Callback.NOOP); - } - else - { - failure.printStackTrace(); - } - }); - // end::telnet[] - } - - public void tlsTelnet() throws Exception - { - // tag::tlsTelnet[] - class TelnetConnection extends AbstractConnection - { - private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - private Consumer consumer; - - public TelnetConnection(EndPoint endPoint, Executor executor) - { - super(endPoint, executor); - } - - @Override - public void onOpen() - { - super.onOpen(); - - // Declare interest for fill events. - fillInterested(); - } - - @Override - public void onFillable() - { - try - { - ByteBuffer buffer = BufferUtil.allocate(1024); - while (true) - { - int filled = getEndPoint().fill(buffer); - if (filled > 0) - { - while (buffer.hasRemaining()) - { - // Search for newline. - byte read = buffer.get(); - if (read == '\n') - { - // Notify the consumer of the line. - consumer.accept(bytes.toString(StandardCharsets.UTF_8)); - bytes.reset(); - } - else - { - bytes.write(read); - } - } - } - else if (filled == 0) - { - // No more bytes to fill, declare - // again interest for fill events. - fillInterested(); - return; - } - else - { - // The other peer closed the - // connection, close it back. - getEndPoint().close(); - return; - } - } - } - catch (Exception x) - { - getEndPoint().close(x); - } - } - - public void onLine(Consumer consumer) - { - this.consumer = consumer; - } - - public void writeLine(String line, Callback callback) - { - line = line + "\r\n"; - getEndPoint().write(callback, ByteBuffer.wrap(line.getBytes(StandardCharsets.UTF_8))); - } - } - - ClientConnector clientConnector = new ClientConnector(); - clientConnector.start(); - - // Use port 443 to contact the server using encrypted HTTP. - String host = "wikipedia.org"; - int port = 443; - SocketAddress address = new InetSocketAddress(host, port); - - ClientConnectionFactory connectionFactory = (endPoint, context) -> - new TelnetConnection(endPoint, clientConnector.getExecutor()); - - // Wrap the "telnet" ClientConnectionFactory with the SslClientConnectionFactory. - connectionFactory = new SslClientConnectionFactory(clientConnector.getSslContextFactory(), - clientConnector.getByteBufferPool(), clientConnector.getExecutor(), connectionFactory); - - // We will obtain a SslConnection now. - CompletableFuture connectionPromise = new Promise.Completable<>(); - - Map context = new HashMap<>(); - context.put(ClientConnector.CLIENT_CONNECTION_FACTORY_CONTEXT_KEY, connectionFactory); - context.put(ClientConnector.CONNECTION_PROMISE_CONTEXT_KEY, connectionPromise); - clientConnector.connect(address, context); - - connectionPromise.whenComplete((sslConnection, failure) -> - { - if (failure == null) - { - // Unwrap the SslConnection to access the "line" APIs in TelnetConnection. - TelnetConnection connection = (TelnetConnection)sslConnection.getDecryptedEndPoint().getConnection(); - // Register a listener that receives string lines. - connection.onLine(line -> System.getLogger("app").log(INFO, "line: {0}", line)); - - // Write a line. - connection.writeLine("" + - "GET / HTTP/1.0\r\n" + - "", Callback.NOOP); - } - else - { - failure.printStackTrace(); - } - }); - // end::tlsTelnet[] - } - - public void unixDomain() throws Exception - { - // tag::unixDomain[] - // This is the path where the server "listens" on. - Path unixDomainPath = Path.of("/path/to/server.sock"); - - // Creates a ClientConnector that uses Unix-Domain - // sockets, not the network, to connect to the server. - ClientConnector clientConnector = ClientConnector.forUnixDomain(unixDomainPath); - clientConnector.start(); - // end::unixDomain[] - } - - public static void main(String[] args) throws Exception - { - new ClientConnectorDocs().tlsTelnet(); - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java deleted file mode 100644 index 2954db451894..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http/HTTPClientDocs.java +++ /dev/null @@ -1,930 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.client.http; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.CookieStore; -import java.net.HttpCookie; -import java.net.URI; -import java.nio.ByteBuffer; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.function.LongConsumer; - -import org.eclipse.jetty.client.ConnectionPool; -import org.eclipse.jetty.client.HttpClient; -import org.eclipse.jetty.client.HttpClientTransport; -import org.eclipse.jetty.client.HttpDestination; -import org.eclipse.jetty.client.HttpProxy; -import org.eclipse.jetty.client.ProxyConfiguration; -import org.eclipse.jetty.client.RoundRobinConnectionPool; -import org.eclipse.jetty.client.Socks5; -import org.eclipse.jetty.client.Socks5Proxy; -import org.eclipse.jetty.client.api.Authentication; -import org.eclipse.jetty.client.api.AuthenticationStore; -import org.eclipse.jetty.client.api.ContentResponse; -import org.eclipse.jetty.client.api.Request; -import org.eclipse.jetty.client.api.Response; -import org.eclipse.jetty.client.api.Result; -import org.eclipse.jetty.client.dynamic.HttpClientTransportDynamic; -import org.eclipse.jetty.client.http.HttpClientConnectionFactory; -import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP; -import org.eclipse.jetty.client.util.AsyncRequestContent; -import org.eclipse.jetty.client.util.BasicAuthentication; -import org.eclipse.jetty.client.util.BufferingResponseListener; -import org.eclipse.jetty.client.util.BytesRequestContent; -import org.eclipse.jetty.client.util.DigestAuthentication; -import org.eclipse.jetty.client.util.FutureResponseListener; -import org.eclipse.jetty.client.util.InputStreamRequestContent; -import org.eclipse.jetty.client.util.InputStreamResponseListener; -import org.eclipse.jetty.client.util.OutputStreamRequestContent; -import org.eclipse.jetty.client.util.PathRequestContent; -import org.eclipse.jetty.client.util.StringRequestContent; -import org.eclipse.jetty.fcgi.client.http.HttpClientTransportOverFCGI; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.http.HttpMethod; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.http2.client.HTTP2Client; -import org.eclipse.jetty.http2.client.http.ClientConnectionFactoryOverHTTP2; -import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2; -import org.eclipse.jetty.http3.client.HTTP3Client; -import org.eclipse.jetty.http3.client.http.HttpClientTransportOverHTTP3; -import org.eclipse.jetty.io.ByteBufferPool; -import org.eclipse.jetty.io.ClientConnectionFactory; -import org.eclipse.jetty.io.ClientConnector; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.HttpCookieStore; -import org.eclipse.jetty.util.component.LifeCycle; -import org.eclipse.jetty.util.ssl.SslContextFactory; - -import static java.lang.System.Logger.Level.INFO; - -@SuppressWarnings("unused") -public class HTTPClientDocs -{ - public void start() throws Exception - { - // tag::start[] - // Instantiate HttpClient. - HttpClient httpClient = new HttpClient(); - - // Configure HttpClient, for example: - httpClient.setFollowRedirects(false); - - // Start HttpClient. - httpClient.start(); - // end::start[] - } - - public void stop() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - // tag::stop[] - // Stop HttpClient. - httpClient.stop(); - // end::stop[] - } - - public void stopFromOtherThread() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - // tag::stopFromOtherThread[] - // Stop HttpClient from a new thread. - // Use LifeCycle.stop(...) to rethrow checked exceptions as unchecked. - new Thread(() -> LifeCycle.stop(httpClient)).start(); - // end::stopFromOtherThread[] - } - - public void tlsExplicit() throws Exception - { - // tag::tlsExplicit[] - SslContextFactory.Client sslContextFactory = new SslContextFactory.Client(); - - ClientConnector clientConnector = new ClientConnector(); - clientConnector.setSslContextFactory(sslContextFactory); - - HttpClient httpClient = new HttpClient(new HttpClientTransportDynamic(clientConnector)); - httpClient.start(); - // end::tlsExplicit[] - } - - public void tlsNoValidation() - { - // tag::tlsNoValidation[] - SslContextFactory.Client sslContextFactory = new SslContextFactory.Client(); - // Disable the validation of the server host name at the TLS level. - sslContextFactory.setEndpointIdentificationAlgorithm(null); - // end::tlsNoValidation[] - } - - public void tlsAppValidation() - { - // tag::tlsAppValidation[] - SslContextFactory.Client sslContextFactory = new SslContextFactory.Client(); - // Only allow to connect to subdomains of domain.com. - sslContextFactory.setHostnameVerifier((hostName, session) -> hostName.endsWith(".domain.com")); - // end::tlsAppValidation[] - } - - public void simpleBlockingGet() throws Exception - { - // tag::simpleBlockingGet[] - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // Perform a simple GET and wait for the response. - ContentResponse response = httpClient.GET("http://domain.com/path?query"); - // end::simpleBlockingGet[] - } - - public void headFluent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::headFluent[] - ContentResponse response = httpClient.newRequest("http://domain.com/path?query") - .method(HttpMethod.HEAD) - .agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0") - .send(); - // end::headFluent[] - } - - public void headNonFluent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::headNonFluent[] - Request request = httpClient.newRequest("http://domain.com/path?query"); - request.method(HttpMethod.HEAD); - request.agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0"); - ContentResponse response = request.send(); - // end::headNonFluent[] - } - - public void postFluent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::postFluent[] - ContentResponse response = httpClient.POST("http://domain.com/entity/1") - .param("p", "value") - .send(); - // end::postFluent[] - } - - public void fileFluent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::fileFluent[] - ContentResponse response = httpClient.POST("http://domain.com/upload") - .file(Paths.get("file_to_upload.txt"), "text/plain") - .send(); - // end::fileFluent[] - } - - public void totalTimeout() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::totalTimeout[] - ContentResponse response = httpClient.newRequest("http://domain.com/path?query") - .timeout(5, TimeUnit.SECONDS) - .send(); - // end::totalTimeout[] - } - - public void simpleNonBlocking() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::simpleNonBlocking[] - httpClient.newRequest("http://domain.com/path") - .send(result -> - { - // Your logic here - }); - // end::simpleNonBlocking[] - } - - public void nonBlockingTotalTimeout() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::nonBlockingTotalTimeout[] - httpClient.newRequest("http://domain.com/path") - .timeout(3, TimeUnit.SECONDS) - .send(result -> - { - /* Your logic here */ - }); - // end::nonBlockingTotalTimeout[] - } - - // @checkstyle-disable-check : LeftCurly - public void listeners() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::listeners[] - httpClient.newRequest("http://domain.com/path") - // Add request hooks. - .onRequestQueued(request -> { /* ... */ }) - .onRequestBegin(request -> { /* ... */ }) - .onRequestHeaders(request -> { /* ... */ }) - .onRequestCommit(request -> { /* ... */ }) - .onRequestContent((request, content) -> { /* ... */ }) - .onRequestFailure((request, failure) -> { /* ... */ }) - .onRequestSuccess(request -> { /* ... */ }) - // Add response hooks. - .onResponseBegin(response -> { /* ... */ }) - .onResponseHeader((response, field) -> true) - .onResponseHeaders(response -> { /* ... */ }) - .onResponseContentAsync((response, buffer, callback) -> callback.succeeded()) - .onResponseFailure((response, failure) -> { /* ... */ }) - .onResponseSuccess(response -> { /* ... */ }) - // Result hook. - .send(result -> { /* ... */ }); - // end::listeners[] - } - - public void pathRequestContent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::pathRequestContent[] - ContentResponse response = httpClient.POST("http://domain.com/upload") - .body(new PathRequestContent("text/plain", Paths.get("file_to_upload.txt"))) - .send(); - // end::pathRequestContent[] - } - - public void inputStreamRequestContent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::inputStreamRequestContent[] - ContentResponse response = httpClient.POST("http://domain.com/upload") - .body(new InputStreamRequestContent("text/plain", new FileInputStream("file_to_upload.txt"))) - .send(); - // end::inputStreamRequestContent[] - } - - public void bytesStringRequestContent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - byte[] bytes = new byte[1024]; - String string = new String(bytes); - // tag::bytesStringRequestContent[] - ContentResponse bytesResponse = httpClient.POST("http://domain.com/upload") - .body(new BytesRequestContent("text/plain", bytes)) - .send(); - - ContentResponse stringResponse = httpClient.POST("http://domain.com/upload") - .body(new StringRequestContent("text/plain", string)) - .send(); - // end::bytesStringRequestContent[] - } - - public void asyncRequestContent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::asyncRequestContent[] - AsyncRequestContent content = new AsyncRequestContent(); - httpClient.POST("http://domain.com/upload") - .body(content) - .send(result -> - { - // Your logic here - }); - - // Content not available yet here. - - // An event happens in some other class, in some other thread. - class ContentPublisher - { - void publish(ByteBufferPool bufferPool, byte[] bytes, boolean lastContent) - { - // Wrap the bytes into a new ByteBuffer. - ByteBuffer buffer = ByteBuffer.wrap(bytes); - - // Offer the content, and release the ByteBuffer - // to the pool when the Callback is completed. - content.offer(buffer, Callback.from(() -> bufferPool.release(buffer))); - - // Close AsyncRequestContent when all the content is arrived. - if (lastContent) - content.close(); - } - } - // end::asyncRequestContent[] - } - - public void outputStreamRequestContent() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::outputStreamRequestContent[] - OutputStreamRequestContent content = new OutputStreamRequestContent(); - - // Use try-with-resources to close the OutputStream when all content is written. - try (OutputStream output = content.getOutputStream()) - { - httpClient.POST("http://localhost:8080/") - .body(content) - .send(result -> - { - // Your logic here - }); - - // Content not available yet here. - - // Content is now available. - byte[] bytes = new byte[]{'h', 'e', 'l', 'l', 'o'}; - output.write(bytes); - } - // End of try-with-resource, output.close() called automatically to signal end of content. - // end::outputStreamRequestContent[] - } - - public void futureResponseListener() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::futureResponseListener[] - Request request = httpClient.newRequest("http://domain.com/path"); - - // Limit response content buffer to 512 KiB. - FutureResponseListener listener = new FutureResponseListener(request, 512 * 1024); - - request.send(listener); - - // Wait at most 5 seconds for request+response to complete. - ContentResponse response = listener.get(5, TimeUnit.SECONDS); - // end::futureResponseListener[] - } - - public void bufferingResponseListener() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::bufferingResponseListener[] - httpClient.newRequest("http://domain.com/path") - // Buffer response content up to 8 MiB - .send(new BufferingResponseListener(8 * 1024 * 1024) - { - @Override - public void onComplete(Result result) - { - if (!result.isFailed()) - { - byte[] responseContent = getContent(); - // Your logic here - } - } - }); - // end::bufferingResponseListener[] - } - - public void inputStreamResponseListener() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::inputStreamResponseListener[] - InputStreamResponseListener listener = new InputStreamResponseListener(); - httpClient.newRequest("http://domain.com/path") - .send(listener); - - // Wait for the response headers to arrive. - Response response = listener.get(5, TimeUnit.SECONDS); - - // Look at the response before streaming the content. - if (response.getStatus() == HttpStatus.OK_200) - { - // Use try-with-resources to close input stream. - try (InputStream responseContent = listener.getInputStream()) - { - // Your logic here - } - } - else - { - response.abort(new IOException("Unexpected HTTP response")); - } - // end::inputStreamResponseListener[] - } - - public void demandedContentListener() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - String host1 = "localhost"; - String host2 = "localhost"; - int port1 = 8080; - int port2 = 8080; - // tag::demandedContentListener[] - // Prepare a request to server1, the source. - Request request1 = httpClient.newRequest(host1, port1) - .path("/source"); - - // Prepare a request to server2, the sink. - AsyncRequestContent content2 = new AsyncRequestContent(); - Request request2 = httpClient.newRequest(host2, port2) - .path("/sink") - .body(content2); - - request1.onResponseContentDemanded(new Response.DemandedContentListener() - { - @Override - public void onBeforeContent(Response response, LongConsumer demand) - { - request2.onRequestCommit(request -> - { - // Only when the request to server2 has been sent, - // then demand response content from server1. - demand.accept(1); - }); - - // Send the request to server2. - request2.send(result -> System.getLogger("forwarder").log(INFO, "Forwarding to server2 complete")); - } - - @Override - public void onContent(Response response, LongConsumer demand, ByteBuffer content, Callback callback) - { - // When response content is received from server1, forward it to server2. - content2.offer(content, Callback.from(() -> - { - // When the request content to server2 is sent, - // succeed the callback to recycle the buffer. - callback.succeeded(); - // Then demand more response content from server1. - demand.accept(1); - }, callback::failed)); - } - }); - - // When the response content from server1 is complete, - // complete also the request content to server2. - request1.onResponseSuccess(response -> content2.close()); - - // Send the request to server1. - request1.send(result -> System.getLogger("forwarder").log(INFO, "Sourcing from server1 complete")); - // end::demandedContentListener[] - } - - public void getCookies() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::getCookies[] - CookieStore cookieStore = httpClient.getCookieStore(); - List cookies = cookieStore.get(URI.create("http://domain.com/path")); - // end::getCookies[] - } - - public void setCookie() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::setCookie[] - CookieStore cookieStore = httpClient.getCookieStore(); - HttpCookie cookie = new HttpCookie("foo", "bar"); - cookie.setDomain("domain.com"); - cookie.setPath("/"); - cookie.setMaxAge(TimeUnit.DAYS.toSeconds(1)); - cookieStore.add(URI.create("http://domain.com"), cookie); - // end::setCookie[] - } - - public void requestCookie() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::requestCookie[] - ContentResponse response = httpClient.newRequest("http://domain.com/path") - .cookie(new HttpCookie("foo", "bar")) - .send(); - // end::requestCookie[] - } - - public void removeCookie() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::removeCookie[] - CookieStore cookieStore = httpClient.getCookieStore(); - URI uri = URI.create("http://domain.com"); - List cookies = cookieStore.get(uri); - for (HttpCookie cookie : cookies) - { - cookieStore.remove(uri, cookie); - } - // end::removeCookie[] - } - - public void emptyCookieStore() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::emptyCookieStore[] - httpClient.setCookieStore(new HttpCookieStore.Empty()); - // end::emptyCookieStore[] - } - - public void filteringCookieStore() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::filteringCookieStore[] - class GoogleOnlyCookieStore extends HttpCookieStore - { - @Override - public void add(URI uri, HttpCookie cookie) - { - if (uri.getHost().endsWith("google.com")) - super.add(uri, cookie); - } - } - - httpClient.setCookieStore(new GoogleOnlyCookieStore()); - // end::filteringCookieStore[] - } - - public void addAuthentication() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::addAuthentication[] - // Add authentication credentials. - AuthenticationStore auth = httpClient.getAuthenticationStore(); - - URI uri1 = new URI("http://mydomain.com/secure"); - auth.addAuthentication(new BasicAuthentication(uri1, "MyRealm", "userName1", "password1")); - - URI uri2 = new URI("http://otherdomain.com/admin"); - auth.addAuthentication(new BasicAuthentication(uri1, "AdminRealm", "admin", "password")); - // end::addAuthentication[] - } - - public void clearResults() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::clearResults[] - httpClient.getAuthenticationStore().clearAuthenticationResults(); - // end::clearResults[] - } - - public void preemptedResult() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::preemptedResult[] - AuthenticationStore auth = httpClient.getAuthenticationStore(); - URI uri = URI.create("http://domain.com/secure"); - auth.addAuthenticationResult(new BasicAuthentication.BasicResult(uri, "username", "password")); - // end::preemptedResult[] - } - - public void requestPreemptedResult() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::requestPreemptedResult[] - URI uri = URI.create("http://domain.com/secure"); - Authentication.Result authn = new BasicAuthentication.BasicResult(uri, "username", "password"); - Request request = httpClient.newRequest(uri); - authn.apply(request); - request.send(); - // end::requestPreemptedResult[] - } - - public void proxy() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::proxy[] - HttpProxy proxy = new HttpProxy("proxyHost", 8888); - - // Do not proxy requests for localhost:8080. - proxy.getExcludedAddresses().add("localhost:8080"); - - // Add the new proxy to the list of proxies already registered. - ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration(); - proxyConfig.addProxy(proxy); - - ContentResponse response = httpClient.GET("http://domain.com/path"); - // end::proxy[] - } - - public void proxySocks5() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::proxySocks5[] - Socks5Proxy proxy = new Socks5Proxy("proxyHost", 8888); - String socks5User = "jetty"; - String socks5Pass = "secret"; - var socks5AuthenticationFactory = new Socks5.UsernamePasswordAuthenticationFactory(socks5User, socks5Pass); - // Add the authentication method to the proxy. - proxy.putAuthenticationFactory(socks5AuthenticationFactory); - - // Do not proxy requests for localhost:8080. - proxy.getExcludedAddresses().add("localhost:8080"); - - // Add the new proxy to the list of proxies already registered. - ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration(); - proxyConfig.addProxy(proxy); - - ContentResponse response = httpClient.GET("http://domain.com/path"); - // end::proxySocks5[] - } - - public void proxyAuthentication() throws Exception - { - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // tag::proxyAuthentication[] - AuthenticationStore auth = httpClient.getAuthenticationStore(); - - // Proxy credentials. - URI proxyURI = new URI("http://proxy.net:8080"); - auth.addAuthentication(new BasicAuthentication(proxyURI, "ProxyRealm", "proxyUser", "proxyPass")); - - // Server credentials. - URI serverURI = new URI("http://domain.com/secure"); - auth.addAuthentication(new DigestAuthentication(serverURI, "ServerRealm", "serverUser", "serverPass")); - - // Proxy configuration. - ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration(); - HttpProxy proxy = new HttpProxy("proxy.net", 8080); - proxyConfig.addProxy(proxy); - - ContentResponse response = httpClient.newRequest(serverURI).send(); - // end::proxyAuthentication[] - } - - public void defaultTransport() throws Exception - { - // tag::defaultTransport[] - // No transport specified, using default. - HttpClient httpClient = new HttpClient(); - httpClient.start(); - // end::defaultTransport[] - } - - public void http11Transport() throws Exception - { - // tag::http11Transport[] - // Configure HTTP/1.1 transport. - HttpClientTransportOverHTTP transport = new HttpClientTransportOverHTTP(); - transport.setHeaderCacheSize(16384); - - HttpClient client = new HttpClient(transport); - client.start(); - // end::http11Transport[] - } - - public void http2Transport() throws Exception - { - // tag::http2Transport[] - // The HTTP2Client powers the HTTP/2 transport. - HTTP2Client h2Client = new HTTP2Client(); - h2Client.setInitialSessionRecvWindow(64 * 1024 * 1024); - - // Create and configure the HTTP/2 transport. - HttpClientTransportOverHTTP2 transport = new HttpClientTransportOverHTTP2(h2Client); - transport.setUseALPN(true); - - HttpClient client = new HttpClient(transport); - client.start(); - // end::http2Transport[] - } - - public void http3Transport() throws Exception - { - // tag::http3Transport[] - // The HTTP3Client powers the HTTP/3 transport. - HTTP3Client h3Client = new HTTP3Client(); - h3Client.getQuicConfiguration().setSessionRecvWindow(64 * 1024 * 1024); - - // Create and configure the HTTP/3 transport. - HttpClientTransportOverHTTP3 transport = new HttpClientTransportOverHTTP3(h3Client); - - HttpClient client = new HttpClient(transport); - client.start(); - // end::http3Transport[] - } - - public void fcgiTransport() throws Exception - { - // tag::fcgiTransport[] - String scriptRoot = "/var/www/wordpress"; - HttpClientTransportOverFCGI transport = new HttpClientTransportOverFCGI(scriptRoot); - - HttpClient client = new HttpClient(transport); - client.start(); - // end::fcgiTransport[] - } - - public void dynamicDefault() throws Exception - { - // tag::dynamicDefault[] - // Dynamic transport speaks HTTP/1.1 by default. - HttpClientTransportDynamic transport = new HttpClientTransportDynamic(); - - HttpClient client = new HttpClient(transport); - client.start(); - // end::dynamicDefault[] - } - - public void dynamicOneProtocol() - { - // tag::dynamicOneProtocol[] - ClientConnector connector = new ClientConnector(); - - // Equivalent to HttpClientTransportOverHTTP. - HttpClientTransportDynamic http11Transport = new HttpClientTransportDynamic(connector, HttpClientConnectionFactory.HTTP11); - - // Equivalent to HttpClientTransportOverHTTP2. - HTTP2Client http2Client = new HTTP2Client(connector); - HttpClientTransportDynamic http2Transport = new HttpClientTransportDynamic(connector, new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client)); - // end::dynamicOneProtocol[] - } - - public void dynamicH1H2() throws Exception - { - // tag::dynamicH1H2[] - ClientConnector connector = new ClientConnector(); - - ClientConnectionFactory.Info http1 = HttpClientConnectionFactory.HTTP11; - - HTTP2Client http2Client = new HTTP2Client(connector); - ClientConnectionFactoryOverHTTP2.HTTP2 http2 = new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client); - - HttpClientTransportDynamic transport = new HttpClientTransportDynamic(connector, http1, http2); - - HttpClient client = new HttpClient(transport); - client.start(); - // end::dynamicH1H2[] - } - - public void dynamicClearText() throws Exception - { - // tag::dynamicClearText[] - ClientConnector connector = new ClientConnector(); - ClientConnectionFactory.Info http1 = HttpClientConnectionFactory.HTTP11; - HTTP2Client http2Client = new HTTP2Client(connector); - ClientConnectionFactoryOverHTTP2.HTTP2 http2 = new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client); - HttpClientTransportDynamic transport = new HttpClientTransportDynamic(connector, http1, http2); - HttpClient client = new HttpClient(transport); - client.start(); - - // The server supports both HTTP/1.1 and HTTP/2 clear-text on port 8080. - - // Make a clear-text request without explicit version. - // The first protocol specified to HttpClientTransportDynamic - // is picked, in this example will be HTTP/1.1. - ContentResponse http1Response = client.newRequest("host", 8080).send(); - - // Make a clear-text request with explicit version. - // Clear-text HTTP/2 is used for this request. - ContentResponse http2Response = client.newRequest("host", 8080) - // Specify the version explicitly. - .version(HttpVersion.HTTP_2) - .send(); - - // Make a clear-text upgrade request from HTTP/1.1 to HTTP/2. - // The request will start as HTTP/1.1, but the response will be HTTP/2. - ContentResponse upgradedResponse = client.newRequest("host", 8080) - .headers(headers -> headers - .put(HttpHeader.UPGRADE, "h2c") - .put(HttpHeader.HTTP2_SETTINGS, "") - .put(HttpHeader.CONNECTION, "Upgrade, HTTP2-Settings")) - .send(); - // end::dynamicClearText[] - } - - public void getConnectionPool() throws Exception - { - // tag::getConnectionPool[] - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - ConnectionPool connectionPool = httpClient.getDestinations().stream() - // Cast to HttpDestination. - .map(HttpDestination.class::cast) - // Find the destination by filtering on the Origin. - .filter(destination -> destination.getOrigin().getAddress().getHost().equals("domain.com")) - .findAny() - // Get the ConnectionPool. - .map(HttpDestination::getConnectionPool) - .orElse(null); - // end::getConnectionPool[] - } - - public void setConnectionPool() throws Exception - { - // tag::setConnectionPool[] - HttpClient httpClient = new HttpClient(); - httpClient.start(); - - // The max number of connections in the pool. - int maxConnectionsPerDestination = httpClient.getMaxConnectionsPerDestination(); - - // The max number of requests per connection (multiplexing). - // Start with 1, since this value is dynamically set to larger values if - // the transport supports multiplexing requests on the same connection. - int maxRequestsPerConnection = 1; - - HttpClientTransport transport = httpClient.getTransport(); - - // Set the ConnectionPool.Factory using a lambda. - transport.setConnectionPoolFactory(destination -> - new RoundRobinConnectionPool(destination, - maxConnectionsPerDestination, - destination, - maxRequestsPerConnection)); - // end::setConnectionPool[] - } - - public void unixDomain() throws Exception - { - // tag::unixDomain[] - // This is the path where the server "listens" on. - Path unixDomainPath = Path.of("/path/to/server.sock"); - - // Creates a ClientConnector that uses Unix-Domain - // sockets, not the network, to connect to the server. - ClientConnector unixDomainClientConnector = ClientConnector.forUnixDomain(unixDomainPath); - - // Use Unix-Domain for HTTP/1.1. - HttpClientTransportOverHTTP http1Transport = new HttpClientTransportOverHTTP(unixDomainClientConnector); - - // You can use Unix-Domain also for HTTP/2. - HTTP2Client http2Client = new HTTP2Client(unixDomainClientConnector); - HttpClientTransportOverHTTP2 http2Transport = new HttpClientTransportOverHTTP2(http2Client); - - // You can also use UnixDomain for the dynamic transport. - ClientConnectionFactory.Info http1 = HttpClientConnectionFactory.HTTP11; - ClientConnectionFactoryOverHTTP2.HTTP2 http2 = new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client); - HttpClientTransportDynamic dynamicTransport = new HttpClientTransportDynamic(unixDomainClientConnector, http1, http2); - - // Choose the transport you prefer for HttpClient, for example the dynamic transport. - HttpClient httpClient = new HttpClient(dynamicTransport); - httpClient.start(); - // end::unixDomain[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java deleted file mode 100644 index 8d4447db3363..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java +++ /dev/null @@ -1,377 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.client.http2; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -import org.eclipse.jetty.http.HttpFields; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.http.HttpURI; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.http.MetaData; -import org.eclipse.jetty.http2.ErrorCode; -import org.eclipse.jetty.http2.api.Session; -import org.eclipse.jetty.http2.api.Stream; -import org.eclipse.jetty.http2.client.HTTP2Client; -import org.eclipse.jetty.http2.frames.DataFrame; -import org.eclipse.jetty.http2.frames.HeadersFrame; -import org.eclipse.jetty.http2.frames.PushPromiseFrame; -import org.eclipse.jetty.http2.frames.ResetFrame; -import org.eclipse.jetty.http2.frames.SettingsFrame; -import org.eclipse.jetty.io.ClientConnector; -import org.eclipse.jetty.util.Callback; - -import static java.lang.System.Logger.Level.INFO; - -@SuppressWarnings("unused") -public class HTTP2ClientDocs -{ - public void start() throws Exception - { - // tag::start[] - // Instantiate HTTP2Client. - HTTP2Client http2Client = new HTTP2Client(); - - // Configure HTTP2Client, for example: - http2Client.setStreamIdleTimeout(15000); - - // Start HTTP2Client. - http2Client.start(); - // end::start[] - } - - public void stop() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - // tag::stop[] - // Stop HTTP2Client. - http2Client.stop(); - // end::stop[] - } - - public void clearTextConnect() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - // tag::clearTextConnect[] - // Address of the server's clear-text port. - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - - // Connect to the server, the CompletableFuture will be - // notified when the connection is succeeded (or failed). - CompletableFuture sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); - - // Block to obtain the Session. - // Alternatively you can use the CompletableFuture APIs to avoid blocking. - Session session = sessionCF.get(); - // end::clearTextConnect[] - } - - public void encryptedConnect() throws Exception - { - // tag::encryptedConnect[] - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - - ClientConnector connector = http2Client.getClientConnector(); - - // Address of the server's encrypted port. - SocketAddress serverAddress = new InetSocketAddress("localhost", 8443); - - // Connect to the server, the CompletableFuture will be - // notified when the connection is succeeded (or failed). - CompletableFuture sessionCF = http2Client.connect(connector.getSslContextFactory(), serverAddress, new Session.Listener.Adapter()); - - // Block to obtain the Session. - // Alternatively you can use the CompletableFuture APIs to avoid blocking. - Session session = sessionCF.get(); - // end::encryptedConnect[] - } - - public void configure() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - - // tag::configure[] - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - http2Client.connect(serverAddress, new Session.Listener.Adapter() - { - @Override - public Map onPreface(Session session) - { - Map configuration = new HashMap<>(); - - // Disable push from the server. - configuration.put(SettingsFrame.ENABLE_PUSH, 0); - - // Override HTTP2Client.initialStreamRecvWindow for this session. - configuration.put(SettingsFrame.INITIAL_WINDOW_SIZE, 1024 * 1024); - - return configuration; - } - }); - // end::configure[] - } - - public void newStream() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - // tag::newStream[] - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - CompletableFuture sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - // Configure the request headers. - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); - - // The request metadata with method, URI and headers. - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - - // The HTTP/2 HEADERS frame, with endStream=true - // to signal that this request has no content. - HeadersFrame headersFrame = new HeadersFrame(request, null, true); - - // Open a Stream by sending the HEADERS frame. - session.newStream(headersFrame, new Stream.Listener.Adapter()); - // end::newStream[] - } - - public void newStreamWithData() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - // tag::newStreamWithData[] - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - CompletableFuture sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - // Configure the request headers. - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.CONTENT_TYPE, "application/json"); - - // The request metadata with method, URI and headers. - MetaData.Request request = new MetaData.Request("POST", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - - // The HTTP/2 HEADERS frame, with endStream=false to - // signal that there will be more frames in this stream. - HeadersFrame headersFrame = new HeadersFrame(request, null, false); - - // Open a Stream by sending the HEADERS frame. - CompletableFuture streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter()); - - // Block to obtain the Stream. - // Alternatively you can use the CompletableFuture APIs to avoid blocking. - Stream stream = streamCF.get(); - - // The request content, in two chunks. - String content1 = "{\"greet\": \"hello world\"}"; - ByteBuffer buffer1 = StandardCharsets.UTF_8.encode(content1); - String content2 = "{\"user\": \"jetty\"}"; - ByteBuffer buffer2 = StandardCharsets.UTF_8.encode(content2); - - // Send the first DATA frame on the stream, with endStream=false - // to signal that there are more frames in this stream. - CompletableFuture dataCF1 = stream.data(new DataFrame(stream.getId(), buffer1, false)); - - // Only when the first chunk has been sent we can send the second, - // with endStream=true to signal that there are no more frames. - dataCF1.thenCompose(s -> s.data(new DataFrame(s.getId(), buffer2, true))); - // end::newStreamWithData[] - } - - public void responseListener() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - CompletableFuture sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, null, true); - - // tag::responseListener[] - // Open a Stream by sending the HEADERS frame. - session.newStream(headersFrame, new Stream.Listener.Adapter() - { - @Override - public void onHeaders(Stream stream, HeadersFrame frame) - { - MetaData metaData = frame.getMetaData(); - - // Is this HEADERS frame the response or the trailers? - if (metaData.isResponse()) - { - MetaData.Response response = (MetaData.Response)metaData; - System.getLogger("http2").log(INFO, "Received response {0}", response); - } - else - { - System.getLogger("http2").log(INFO, "Received trailers {0}", metaData.getFields()); - } - } - - @Override - public void onData(Stream stream, DataFrame frame, Callback callback) - { - // Get the content buffer. - ByteBuffer buffer = frame.getData(); - - // Consume the buffer, here - as an example - just log it. - System.getLogger("http2").log(INFO, "Consuming buffer {0}", buffer); - - // Tell the implementation that the buffer has been consumed. - callback.succeeded(); - - // By returning from the method, implicitly tell the implementation - // to deliver to this method more DATA frames when they are available. - } - }); - // end::responseListener[] - } - - public void reset() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - CompletableFuture sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, null, true); - - // tag::reset[] - // Open a Stream by sending the HEADERS frame. - CompletableFuture streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter() - { - @Override - public void onReset(Stream stream, ResetFrame frame) - { - // The server reset this stream. - } - }); - Stream stream = streamCF.get(); - - // Reset this stream (for example, the user closed the application). - stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); - // end::reset[] - } - - public void push() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - CompletableFuture sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, null, true); - - // tag::push[] - // Open a Stream by sending the HEADERS frame. - CompletableFuture streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter() - { - @Override - public Stream.Listener onPush(Stream pushedStream, PushPromiseFrame frame) - { - // The "request" the client would make for the pushed resource. - MetaData.Request pushedRequest = frame.getMetaData(); - // The pushed "request" URI. - HttpURI pushedURI = pushedRequest.getURI(); - // The pushed "request" headers. - HttpFields pushedRequestHeaders = pushedRequest.getFields(); - - // If needed, retrieve the primary stream that triggered the push. - Stream primaryStream = pushedStream.getSession().getStream(frame.getStreamId()); - - // Return a Stream.Listener to listen for the pushed "response" events. - return new Stream.Listener.Adapter() - { - @Override - public void onHeaders(Stream stream, HeadersFrame frame) - { - // Handle the pushed stream "response". - - MetaData metaData = frame.getMetaData(); - if (metaData.isResponse()) - { - // The pushed "response" headers. - HttpFields pushedResponseHeaders = metaData.getFields(); - } - } - - @Override - public void onData(Stream stream, DataFrame frame, Callback callback) - { - // Handle the pushed stream "response" content. - - // The pushed stream "response" content bytes. - ByteBuffer buffer = frame.getData(); - // Consume the buffer and complete the callback. - callback.succeeded(); - } - }; - } - }); - // end::push[] - } - - public void pushReset() throws Exception - { - HTTP2Client http2Client = new HTTP2Client(); - http2Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8080); - CompletableFuture sessionCF = http2Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, null, true); - - // tag::pushReset[] - // Open a Stream by sending the HEADERS frame. - CompletableFuture streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter() - { - @Override - public Stream.Listener onPush(Stream pushedStream, PushPromiseFrame frame) - { - // Reset the pushed stream to tell the server we are not interested. - pushedStream.reset(new ResetFrame(pushedStream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); - - // Not interested in listening to pushed response events. - return null; - } - }); - // end::pushReset[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java deleted file mode 100644 index 6af744c01e9f..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java +++ /dev/null @@ -1,356 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.client.http3; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CompletableFuture; - -import org.eclipse.jetty.http.HttpFields; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.http.HttpURI; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.http.MetaData; -import org.eclipse.jetty.http3.api.Session; -import org.eclipse.jetty.http3.api.Stream; -import org.eclipse.jetty.http3.client.HTTP3Client; -import org.eclipse.jetty.http3.frames.DataFrame; -import org.eclipse.jetty.http3.frames.HeadersFrame; -import org.eclipse.jetty.http3.internal.HTTP3ErrorCode; - -import static java.lang.System.Logger.Level.INFO; - -@SuppressWarnings("unused") -public class HTTP3ClientDocs -{ - public void start() throws Exception - { - // tag::start[] - // Instantiate HTTP3Client. - HTTP3Client http3Client = new HTTP3Client(); - - // Configure HTTP3Client, for example: - http3Client.getHTTP3Configuration().setStreamIdleTimeout(15000); - - // Start HTTP3Client. - http3Client.start(); - // end::start[] - } - - public void stop() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - // tag::stop[] - // Stop HTTP3Client. - http3Client.stop(); - // end::stop[] - } - - public void connect() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - // tag::connect[] - // Address of the server's port. - SocketAddress serverAddress = new InetSocketAddress("localhost", 8444); - - // Connect to the server, the CompletableFuture will be - // notified when the connection is succeeded (or failed). - CompletableFuture sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {}); - - // Block to obtain the Session. - // Alternatively you can use the CompletableFuture APIs to avoid blocking. - Session session = sessionCF.get(); - // end::connect[] - } - - public void configure() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - - // tag::configure[] - SocketAddress serverAddress = new InetSocketAddress("localhost", 8444); - http3Client.connect(serverAddress, new Session.Client.Listener() - { - @Override - public Map onPreface(Session session) - { - Map configuration = new HashMap<>(); - - // Add here configuration settings. - - return configuration; - } - }); - // end::configure[] - } - - public void newStream() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - // tag::newStream[] - SocketAddress serverAddress = new InetSocketAddress("localhost", 8444); - CompletableFuture sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {}); - Session.Client session = sessionCF.get(); - - // Configure the request headers. - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); - - // The request metadata with method, URI and headers. - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8444/path"), HttpVersion.HTTP_3, requestHeaders); - - // The HTTP/3 HEADERS frame, with endStream=true - // to signal that this request has no content. - HeadersFrame headersFrame = new HeadersFrame(request, true); - - // Open a Stream by sending the HEADERS frame. - session.newRequest(headersFrame, new Stream.Client.Listener() {}); - // end::newStream[] - } - - public void newStreamWithData() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - // tag::newStreamWithData[] - SocketAddress serverAddress = new InetSocketAddress("localhost", 8444); - CompletableFuture sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {}); - Session.Client session = sessionCF.get(); - - // Configure the request headers. - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.CONTENT_TYPE, "application/json"); - - // The request metadata with method, URI and headers. - MetaData.Request request = new MetaData.Request("POST", HttpURI.from("http://localhost:8444/path"), HttpVersion.HTTP_3, requestHeaders); - - // The HTTP/3 HEADERS frame, with endStream=false to - // signal that there will be more frames in this stream. - HeadersFrame headersFrame = new HeadersFrame(request, false); - - // Open a Stream by sending the HEADERS frame. - CompletableFuture streamCF = session.newRequest(headersFrame, new Stream.Client.Listener() {}); - - // Block to obtain the Stream. - // Alternatively you can use the CompletableFuture APIs to avoid blocking. - Stream stream = streamCF.get(); - - // The request content, in two chunks. - String content1 = "{\"greet\": \"hello world\"}"; - ByteBuffer buffer1 = StandardCharsets.UTF_8.encode(content1); - String content2 = "{\"user\": \"jetty\"}"; - ByteBuffer buffer2 = StandardCharsets.UTF_8.encode(content2); - - // Send the first DATA frame on the stream, with endStream=false - // to signal that there are more frames in this stream. - CompletableFuture dataCF1 = stream.data(new DataFrame(buffer1, false)); - - // Only when the first chunk has been sent we can send the second, - // with endStream=true to signal that there are no more frames. - dataCF1.thenCompose(s -> s.data(new DataFrame(buffer2, true))); - // end::newStreamWithData[] - } - - public void responseListener() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8444); - CompletableFuture sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {}); - Session.Client session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8444/path"), HttpVersion.HTTP_3, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, true); - - // tag::responseListener[] - // Open a Stream by sending the HEADERS frame. - session.newRequest(headersFrame, new Stream.Client.Listener() - { - @Override - public void onResponse(Stream.Client stream, HeadersFrame frame) - { - MetaData metaData = frame.getMetaData(); - MetaData.Response response = (MetaData.Response)metaData; - System.getLogger("http3").log(INFO, "Received response {0}", response); - } - - @Override - public void onDataAvailable(Stream.Client stream) - { - // Read a chunk of the content. - Stream.Data data = stream.readData(); - if (data == null) - { - // No data available now, demand to be called back. - stream.demand(); - } - else - { - // Process the content. - process(data.getByteBuffer()); - - // Notify the implementation that the content has been consumed. - data.complete(); - - if (!data.isLast()) - { - // Demand to be called back. - stream.demand(); - } - } - } - }); - // end::responseListener[] - } - - private void process(ByteBuffer byteBuffer) - { - } - - public void reset() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8444); - CompletableFuture sessionCF = http3Client.connect(serverAddress, new Session.Client.Listener() {}); - Session.Client session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, true); - - // tag::reset[] - // Open a Stream by sending the HEADERS frame. - CompletableFuture streamCF = session.newRequest(headersFrame, new Stream.Client.Listener() - { - @Override - public void onFailure(Stream.Client stream, long error, Throwable failure) - { - // The server reset this stream. - } - }); - Stream stream = streamCF.get(); - - // Reset this stream (for example, the user closed the application). - stream.reset(HTTP3ErrorCode.REQUEST_CANCELLED_ERROR.code(), new ClosedChannelException()); - // end::reset[] - } - - // TODO: push not yet implemented in HTTP/3 -/* - public void push() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8444); - CompletableFuture sessionCF = http3Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, null, true); - - // tag::push[] - // Open a Stream by sending the HEADERS frame. - CompletableFuture streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter() - { - @Override - public Stream.Listener onPush(Stream pushedStream, PushPromiseFrame frame) - { - // The "request" the client would make for the pushed resource. - MetaData.Request pushedRequest = frame.getMetaData(); - // The pushed "request" URI. - HttpURI pushedURI = pushedRequest.getURI(); - // The pushed "request" headers. - HttpFields pushedRequestHeaders = pushedRequest.getFields(); - - // If needed, retrieve the primary stream that triggered the push. - Stream primaryStream = pushedStream.getSession().getStream(frame.getStreamId()); - - // Return a Stream.Listener to listen for the pushed "response" events. - return new Adapter() - { - @Override - public void onHeaders(Stream stream, HeadersFrame frame) - { - // Handle the pushed stream "response". - - MetaData metaData = frame.getMetaData(); - if (metaData.isResponse()) - { - // The pushed "response" headers. - HttpFields pushedResponseHeaders = metaData.getFields(); - } - } - - @Override - public void onData(Stream stream, DataFrame frame, Callback callback) - { - // Handle the pushed stream "response" content. - - // The pushed stream "response" content bytes. - ByteBuffer buffer = frame.getData(); - // Consume the buffer and complete the callback. - callback.succeeded(); - } - }; - } - }); - // end::push[] - } - - public void pushReset() throws Exception - { - HTTP3Client http3Client = new HTTP3Client(); - http3Client.start(); - SocketAddress serverAddress = new InetSocketAddress("localhost", 8444); - CompletableFuture sessionCF = http3Client.connect(serverAddress, new Session.Listener.Adapter()); - Session session = sessionCF.get(); - - HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); - MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); - HeadersFrame headersFrame = new HeadersFrame(request, null, true); - - // tag::pushReset[] - // Open a Stream by sending the HEADERS frame. - CompletableFuture streamCF = session.newStream(headersFrame, new Stream.Listener.Adapter() - { - @Override - public Stream.Listener onPush(Stream pushedStream, PushPromiseFrame frame) - { - // Reset the pushed stream to tell the server we are not interested. - pushedStream.reset(new ResetFrame(pushedStream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP); - - // Not interested in listening to pushed response events. - return null; - } - }); - // end::pushReset[] - } - */ -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java deleted file mode 100644 index aed23eb61e1f..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/client/websocket/WebSocketClientDocs.java +++ /dev/null @@ -1,193 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.client.websocket; - -import java.net.HttpCookie; -import java.net.URI; -import java.util.concurrent.CompletableFuture; - -import org.eclipse.jetty.client.HttpClient; -import org.eclipse.jetty.client.HttpProxy; -import org.eclipse.jetty.client.HttpRequest; -import org.eclipse.jetty.client.HttpResponse; -import org.eclipse.jetty.client.dynamic.HttpClientTransportDynamic; -import org.eclipse.jetty.http2.client.HTTP2Client; -import org.eclipse.jetty.http2.client.http.ClientConnectionFactoryOverHTTP2; -import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2; -import org.eclipse.jetty.util.component.LifeCycle; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; -import org.eclipse.jetty.websocket.client.JettyUpgradeListener; -import org.eclipse.jetty.websocket.client.WebSocketClient; - -@SuppressWarnings("unused") -public class WebSocketClientDocs -{ - public void start() throws Exception - { - // tag::start[] - // Instantiate WebSocketClient. - WebSocketClient webSocketClient = new WebSocketClient(); - - // Configure WebSocketClient, for example: - webSocketClient.setMaxTextMessageSize(8 * 1024); - - // Start WebSocketClient. - webSocketClient.start(); - // end::start[] - } - - public void startWithHttpClient() throws Exception - { - // tag::startWithHttpClient[] - // Instantiate and configure HttpClient. - HttpClient httpClient = new HttpClient(); - // For example, configure a proxy. - httpClient.getProxyConfiguration().addProxy(new HttpProxy("localhost", 8888)); - - // Instantiate WebSocketClient, passing HttpClient to the constructor. - WebSocketClient webSocketClient = new WebSocketClient(httpClient); - // Configure WebSocketClient, for example: - webSocketClient.setMaxTextMessageSize(8 * 1024); - - // Start WebSocketClient; this implicitly starts also HttpClient. - webSocketClient.start(); - // end::startWithHttpClient[] - } - - public void stop() throws Exception - { - WebSocketClient webSocketClient = new WebSocketClient(); - webSocketClient.start(); - // tag::stop[] - // Stop WebSocketClient. - // Use LifeCycle.stop(...) to rethrow checked exceptions as unchecked. - new Thread(() -> LifeCycle.stop(webSocketClient)).start(); - // end::stop[] - } - - public void connectHTTP11() throws Exception - { - // tag::connectHTTP11[] - // Use a standard, HTTP/1.1, HttpClient. - HttpClient httpClient = new HttpClient(); - - // Create and start WebSocketClient. - WebSocketClient webSocketClient = new WebSocketClient(httpClient); - webSocketClient.start(); - - // The client-side WebSocket EndPoint that - // receives WebSocket messages from the server. - ClientEndPoint clientEndPoint = new ClientEndPoint(); - // The server URI to connect to. - URI serverURI = URI.create("ws://domain.com/path"); - - // Connect the client EndPoint to the server. - CompletableFuture clientSessionPromise = webSocketClient.connect(clientEndPoint, serverURI); - // end::connectHTTP11[] - } - - public void connectHTTP2() throws Exception - { - // tag::connectHTTP2[] - // Use the HTTP/2 transport for HttpClient. - HTTP2Client http2Client = new HTTP2Client(); - HttpClient httpClient = new HttpClient(new HttpClientTransportOverHTTP2(http2Client)); - - // Create and start WebSocketClient. - WebSocketClient webSocketClient = new WebSocketClient(httpClient); - webSocketClient.start(); - - // The client-side WebSocket EndPoint that - // receives WebSocket messages from the server. - ClientEndPoint clientEndPoint = new ClientEndPoint(); - // The server URI to connect to. - URI serverURI = URI.create("wss://domain.com/path"); - - // Connect the client EndPoint to the server. - CompletableFuture clientSessionPromise = webSocketClient.connect(clientEndPoint, serverURI); - // end::connectHTTP2[] - } - - public void connectHTTP2Dynamic() throws Exception - { - // tag::connectHTTP2Dynamic[] - // Use the dynamic HTTP/2 transport for HttpClient. - HTTP2Client http2Client = new HTTP2Client(); - HttpClient httpClient = new HttpClient(new HttpClientTransportDynamic(new ClientConnectionFactoryOverHTTP2.HTTP2(http2Client))); - - // Create and start WebSocketClient. - WebSocketClient webSocketClient = new WebSocketClient(httpClient); - webSocketClient.start(); - - ClientEndPoint clientEndPoint = new ClientEndPoint(); - URI serverURI = URI.create("wss://domain.com/path"); - - // Connect the client EndPoint to the server. - CompletableFuture clientSessionPromise = webSocketClient.connect(clientEndPoint, serverURI); - // end::connectHTTP2Dynamic[] - } - - public void customHTTPRequest() throws Exception - { - WebSocketClient webSocketClient = new WebSocketClient(new HttpClient()); - webSocketClient.start(); - - // tag::customHTTPRequest[] - ClientEndPoint clientEndPoint = new ClientEndPoint(); - URI serverURI = URI.create("ws://domain.com/path"); - - // Create a custom HTTP request. - ClientUpgradeRequest customRequest = new ClientUpgradeRequest(); - // Specify a cookie. - customRequest.getCookies().add(new HttpCookie("name", "value")); - // Specify a custom header. - customRequest.setHeader("X-Token", "0123456789ABCDEF"); - // Specify a custom sub-protocol. - customRequest.setSubProtocols("chat"); - - // Connect the client EndPoint to the server with a custom HTTP request. - CompletableFuture clientSessionPromise = webSocketClient.connect(clientEndPoint, serverURI, customRequest); - // end::customHTTPRequest[] - } - - public void inspectHTTPResponse() throws Exception - { - WebSocketClient webSocketClient = new WebSocketClient(new HttpClient()); - webSocketClient.start(); - - // tag::inspectHTTPResponse[] - ClientEndPoint clientEndPoint = new ClientEndPoint(); - URI serverURI = URI.create("ws://domain.com/path"); - - // The listener to inspect the HTTP response. - JettyUpgradeListener listener = new JettyUpgradeListener() - { - @Override - public void onHandshakeResponse(HttpRequest request, HttpResponse response) - { - // Inspect the HTTP response here. - } - }; - - // Connect the client EndPoint to the server with a custom HTTP request. - CompletableFuture clientSessionPromise = webSocketClient.connect(clientEndPoint, serverURI, null, listener); - // end::inspectHTTPResponse[] - } - - @SuppressWarnings("InnerClassMayBeStatic") - public class ClientEndPoint - { - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/ServerDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/ServerDocs.java deleted file mode 100644 index a109be5ed6d3..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/ServerDocs.java +++ /dev/null @@ -1,335 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.server; - -import java.nio.ByteBuffer; -import java.nio.file.Path; -import java.util.Map; -import java.util.concurrent.Executor; - -import org.eclipse.jetty.http.CookieCompliance; -import org.eclipse.jetty.http.HttpCompliance; -import org.eclipse.jetty.http.UriCompliance; -import org.eclipse.jetty.io.AbstractConnection; -import org.eclipse.jetty.io.Connection; -import org.eclipse.jetty.io.EndPoint; -import org.eclipse.jetty.server.AbstractConnectionFactory; -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.DetectorConnectionFactory; -import org.eclipse.jetty.server.HttpConfiguration; -import org.eclipse.jetty.server.HttpConnectionFactory; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.server.SslConnectionFactory; -import org.eclipse.jetty.unixdomain.server.UnixDomainServerConnector; -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.IteratingCallback; -import org.eclipse.jetty.util.ajax.AsyncJSON; -import org.eclipse.jetty.util.ssl.SslContextFactory; - -@SuppressWarnings("unused") -public class ServerDocs -{ - public void http() throws Exception - { - // tag::http[] - // Create the HTTP/1.1 ConnectionFactory. - HttpConnectionFactory http = new HttpConnectionFactory(); - - Server server = new Server(); - - // Create the connector with the ConnectionFactory. - ServerConnector connector = new ServerConnector(server, http); - connector.setPort(8080); - - server.addConnector(connector); - server.start(); - // end::http[] - } - - public void httpUnix() throws Exception - { - // tag::httpUnix[] - // Create the HTTP/1.1 ConnectionFactory. - HttpConnectionFactory http = new HttpConnectionFactory(); - - Server server = new Server(); - - // Create the connector with the ConnectionFactory. - UnixDomainServerConnector connector = new UnixDomainServerConnector(server, http); - connector.setUnixDomainPath(Path.of("/tmp/jetty.sock")); - - server.addConnector(connector); - server.start(); - // end::httpUnix[] - } - - public void tlsHttp() throws Exception - { - // tag::tlsHttp[] - // Create the HTTP/1.1 ConnectionFactory. - HttpConnectionFactory http = new HttpConnectionFactory(); - - // Create and configure the TLS context factory. - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore.p12"); - sslContextFactory.setKeyStorePassword("secret"); - - // Create the TLS ConnectionFactory, - // setting HTTP/1.1 as the wrapped protocol. - SslConnectionFactory tls = new SslConnectionFactory(sslContextFactory, http.getProtocol()); - - Server server = new Server(); - - // Create the connector with both ConnectionFactories. - ServerConnector connector = new ServerConnector(server, tls, http); - connector.setPort(8443); - - server.addConnector(connector); - server.start(); - // end::tlsHttp[] - } - - public void detector() throws Exception - { - // tag::detector[] - // Create the HTTP/1.1 ConnectionFactory. - HttpConnectionFactory http = new HttpConnectionFactory(); - - // Create and configure the TLS context factory. - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore.p12"); - sslContextFactory.setKeyStorePassword("secret"); - - // Create the TLS ConnectionFactory, - // setting HTTP/1.1 as the wrapped protocol. - SslConnectionFactory tls = new SslConnectionFactory(sslContextFactory, http.getProtocol()); - - Server server = new Server(); - - // Create the detector ConnectionFactory to - // detect whether the initial bytes are TLS. - DetectorConnectionFactory tlsDetector = new DetectorConnectionFactory(tls); // <1> - - // Create the connector with both ConnectionFactories. - ServerConnector connector = new ServerConnector(server, tlsDetector, http); // <2> - connector.setPort(8181); - - server.addConnector(connector); - server.start(); - // end::detector[] - } - - // tag::jsonHttpConnectionFactory[] - public class JSONHTTPConnectionFactory extends AbstractConnectionFactory - { - public JSONHTTPConnectionFactory() - { - super("JSONHTTP"); - } - - @Override - public Connection newConnection(Connector connector, EndPoint endPoint) - { - JSONHTTPConnection connection = new JSONHTTPConnection(endPoint, connector.getExecutor()); - // Call configure() to apply configurations common to all connections. - return configure(connection, connector, endPoint); - } - } - // end::jsonHttpConnectionFactory[] - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::jsonHttpConnection[] - public class JSONHTTPConnection extends AbstractConnection - { - // The asynchronous JSON parser. - private final AsyncJSON parser = new AsyncJSON.Factory().newAsyncJSON(); - private final IteratingCallback callback = new JSONHTTPIteratingCallback(); - - public JSONHTTPConnection(EndPoint endPoint, Executor executor) - { - super(endPoint, executor); - } - - @Override - public void onOpen() - { - super.onOpen(); - - // Declare interest in being called back when - // there are bytes to read from the network. - fillInterested(); - } - - @Override - public void onFillable() - { - callback.iterate(); - } - - private class JSONHTTPIteratingCallback extends IteratingCallback - { - private ByteBuffer buffer; - - @Override - protected Action process() throws Throwable - { - if (buffer == null) - buffer = BufferUtil.allocate(getInputBufferSize(), true); - - while (true) - { - int filled = getEndPoint().fill(buffer); - if (filled > 0) - { - boolean parsed = parser.parse(buffer); - if (parsed) - { - Map request = parser.complete(); - - // Allow applications to process the request. - invokeApplication(request, this); - - // Signal that the iteration should resume when - // the application completed the request processing. - return Action.SCHEDULED; - } - else - { - // Did not receive enough JSON bytes, - // loop around to try to read more. - } - } - else if (filled == 0) - { - // We don't need the buffer anymore, so - // don't keep it around while we are idle. - buffer = null; - - // No more bytes to read, declare - // again interest for fill events. - fillInterested(); - - // Signal that the iteration is now IDLE. - return Action.IDLE; - } - else - { - // The other peer closed the connection, - // the iteration completed successfully. - return Action.SUCCEEDED; - } - } - } - - @Override - protected void onCompleteSuccess() - { - getEndPoint().close(); - } - - @Override - protected void onCompleteFailure(Throwable cause) - { - getEndPoint().close(cause); - } - } - } - // end::jsonHttpConnection[] - - private void invokeApplication(Map request, Callback callback) - { - } - - // tag::jsonHttpAPI[] - class JSONHTTPRequest - { - // Request APIs - } - - class JSONHTTPResponse - { - // Response APIs - } - - interface JSONHTTPService - { - void service(JSONHTTPRequest request, JSONHTTPResponse response, Callback callback); - } - // end::jsonHttpAPI[] - - public void httpCompliance() - { - // tag::httpCompliance[] - HttpConfiguration httpConfiguration = new HttpConfiguration(); - httpConfiguration.setHttpCompliance(HttpCompliance.RFC7230); - // end::httpCompliance[] - } - - public void httpComplianceCustom() - { - // tag::httpComplianceCustom[] - HttpConfiguration httpConfiguration = new HttpConfiguration(); - - // RFC7230 compliance, but allow Violation.MULTIPLE_CONTENT_LENGTHS. - HttpCompliance customHttpCompliance = HttpCompliance.from("RFC7230,MULTIPLE_CONTENT_LENGTHS"); - - httpConfiguration.setHttpCompliance(customHttpCompliance); - // end::httpComplianceCustom[] - } - - public void uriCompliance() - { - // tag::uriCompliance[] - HttpConfiguration httpConfiguration = new HttpConfiguration(); - httpConfiguration.setUriCompliance(UriCompliance.RFC3986); - // end::uriCompliance[] - } - - public void uriComplianceCustom() - { - // tag::uriComplianceCustom[] - HttpConfiguration httpConfiguration = new HttpConfiguration(); - - // RFC3986 compliance, but enforce Violation.AMBIGUOUS_PATH_SEPARATOR. - UriCompliance customUriCompliance = UriCompliance.from("RFC3986,-AMBIGUOUS_PATH_SEPARATOR"); - - httpConfiguration.setUriCompliance(customUriCompliance); - // end::uriComplianceCustom[] - } - - public void cookieCompliance() - { - // tag::cookieCompliance[] - HttpConfiguration httpConfiguration = new HttpConfiguration(); - httpConfiguration.setRequestCookieCompliance(CookieCompliance.RFC6265); - httpConfiguration.setResponseCookieCompliance(CookieCompliance.RFC6265); - // end::cookieCompliance[] - } - - public void cookieComplianceCustom() - { - // tag::cookieComplianceCustom[] - HttpConfiguration httpConfiguration = new HttpConfiguration(); - - // RFC6265 compliance, but enforce Violation.RESERVED_NAMES_NOT_DOLLAR_PREFIXED. - CookieCompliance customUriCompliance = CookieCompliance.from("RFC6265,-RESERVED_NAMES_NOT_DOLLAR_PREFIXED"); - httpConfiguration.setRequestCookieCompliance(customUriCompliance); - - httpConfiguration.setResponseCookieCompliance(CookieCompliance.RFC6265); - - // end::cookieComplianceCustom[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java deleted file mode 100644 index 7fe7431075a3..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http/HTTPServerDocs.java +++ /dev/null @@ -1,1076 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.server.http; - -import java.io.IOException; -import java.nio.file.Path; -import java.security.Security; -import java.util.EnumSet; -import java.util.TimeZone; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import javax.servlet.DispatcherType; -import javax.servlet.ServletException; -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.conscrypt.OpenSSLProvider; -import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory; -import org.eclipse.jetty.http.HttpCompliance; -import org.eclipse.jetty.http.HttpHeaderValue; -import org.eclipse.jetty.http.HttpMethod; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.http.HttpURI; -import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory; -import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory; -import org.eclipse.jetty.http3.server.HTTP3ServerConnectionFactory; -import org.eclipse.jetty.http3.server.HTTP3ServerConnector; -import org.eclipse.jetty.rewrite.handler.CompactPathRule; -import org.eclipse.jetty.rewrite.handler.RedirectRegexRule; -import org.eclipse.jetty.rewrite.handler.RewriteHandler; -import org.eclipse.jetty.rewrite.handler.RewriteRegexRule; -import org.eclipse.jetty.server.Connector; -import org.eclipse.jetty.server.CustomRequestLog; -import org.eclipse.jetty.server.HttpChannel; -import org.eclipse.jetty.server.HttpConfiguration; -import org.eclipse.jetty.server.HttpConnectionFactory; -import org.eclipse.jetty.server.ProxyConnectionFactory; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.RequestLogWriter; -import org.eclipse.jetty.server.SecureRequestCustomizer; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.server.Slf4jRequestLogWriter; -import org.eclipse.jetty.server.SslConnectionFactory; -import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.server.handler.ContextHandler; -import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.eclipse.jetty.server.handler.DefaultHandler; -import org.eclipse.jetty.server.handler.HandlerCollection; -import org.eclipse.jetty.server.handler.HandlerList; -import org.eclipse.jetty.server.handler.HandlerWrapper; -import org.eclipse.jetty.server.handler.RequestLogHandler; -import org.eclipse.jetty.server.handler.ResourceHandler; -import org.eclipse.jetty.server.handler.SecuredRedirectHandler; -import org.eclipse.jetty.server.handler.StatisticsHandler; -import org.eclipse.jetty.server.handler.gzip.GzipHandler; -import org.eclipse.jetty.servlet.DefaultServlet; -import org.eclipse.jetty.servlet.FilterHolder; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.servlets.CrossOriginFilter; -import org.eclipse.jetty.unixdomain.server.UnixDomainServerConnector; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.NanoTime; -import org.eclipse.jetty.util.resource.Resource; -import org.eclipse.jetty.util.resource.ResourceCollection; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.eclipse.jetty.util.thread.QueuedThreadPool; -import org.eclipse.jetty.webapp.WebAppContext; - -import static java.lang.System.Logger.Level.INFO; - -@SuppressWarnings("unused") -public class HTTPServerDocs -{ - public void simple() throws Exception - { - // tag::simple[] - // Create and configure a ThreadPool. - QueuedThreadPool threadPool = new QueuedThreadPool(); - threadPool.setName("server"); - - // Create a Server instance. - Server server = new Server(threadPool); - - // Create a ServerConnector to accept connections from clients. - Connector connector = new ServerConnector(server); - - // Add the Connector to the Server - server.addConnector(connector); - - // Set a simple Handler to handle requests/responses. - server.setHandler(new AbstractHandler() - { - @Override - public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) - { - // Mark the request as handled so that it - // will not be processed by other handlers. - jettyRequest.setHandled(true); - } - }); - - // Start the Server so it starts accepting connections from clients. - server.start(); - // end::simple[] - } - - public void httpChannelListener() throws Exception - { - // tag::httpChannelListener[] - class TimingHttpChannelListener implements HttpChannel.Listener - { - private final ConcurrentMap times = new ConcurrentHashMap<>(); - - @Override - public void onRequestBegin(Request request) - { - times.put(request, NanoTime.now()); - } - - @Override - public void onComplete(Request request) - { - long begin = times.remove(request); - long elapsed = NanoTime.since(begin); - System.getLogger("timing").log(INFO, "Request {0} took {1} ns", request, elapsed); - } - } - - Server server = new Server(); - - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Add the HttpChannel.Listener as bean to the connector. - connector.addBean(new TimingHttpChannelListener()); - - // Set a simple Handler to handle requests/responses. - server.setHandler(new AbstractHandler() - { - @Override - public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) - { - jettyRequest.setHandled(true); - } - }); - - server.start(); - // end::httpChannelListener[] - } - - public void serverRequestLogSLF4J() - { - // tag::serverRequestLogSLF4J[] - Server server = new Server(); - - // Sets the RequestLog to log to an SLF4J logger named "org.eclipse.jetty.server.RequestLog" at INFO level. - server.setRequestLog(new CustomRequestLog(new Slf4jRequestLogWriter(), CustomRequestLog.EXTENDED_NCSA_FORMAT)); - // end::serverRequestLogSLF4J[] - } - - public void serverRequestLogFile() - { - // tag::serverRequestLogFile[] - Server server = new Server(); - - // Use a file name with the pattern 'yyyy_MM_dd' so rolled over files retain their date. - RequestLogWriter logWriter = new RequestLogWriter("/var/log/yyyy_MM_dd.jetty.request.log"); - // Retain rolled over files for 2 weeks. - logWriter.setRetainDays(14); - // Log times are in the current time zone. - logWriter.setTimeZone(TimeZone.getDefault().getID()); - - // Set the RequestLog to log to the given file, rolling over at midnight. - server.setRequestLog(new CustomRequestLog(logWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT)); - // end::serverRequestLogFile[] - } - - public void contextRequestLog() - { - // tag::contextRequestLog[] - Server server = new Server(); - - // Create a first ServletContextHandler for your main application. - ServletContextHandler mainContext = new ServletContextHandler(); - mainContext.setContextPath("/main"); - - // Create a RequestLogHandler to log requests for your main application. - RequestLogHandler requestLogHandler = new RequestLogHandler(); - requestLogHandler.setRequestLog(new CustomRequestLog()); - // Wrap the main application with the request log handler. - requestLogHandler.setHandler(mainContext); - - // Create a second ServletContextHandler for your other application. - // No request logging for this application. - ServletContextHandler otherContext = new ServletContextHandler(); - mainContext.setContextPath("/other"); - - server.setHandler(new HandlerList(requestLogHandler, otherContext)); - // end::contextRequestLog[] - } - - public void configureConnector() throws Exception - { - // tag::configureConnector[] - Server server = new Server(); - - // The number of acceptor threads. - int acceptors = 1; - - // The number of selectors. - int selectors = 1; - - // Create a ServerConnector instance. - ServerConnector connector = new ServerConnector(server, acceptors, selectors, new HttpConnectionFactory()); - - // Configure TCP/IP parameters. - - // The port to listen to. - connector.setPort(8080); - // The address to bind to. - connector.setHost("127.0.0.1"); - - // The TCP accept queue size. - connector.setAcceptQueueSize(128); - - server.addConnector(connector); - server.start(); - // end::configureConnector[] - } - - public void configureConnectorUnix() throws Exception - { - // tag::configureConnectorUnix[] - Server server = new Server(); - - // The number of acceptor threads. - int acceptors = 1; - - // The number of selectors. - int selectors = 1; - - // Create a ServerConnector instance. - UnixDomainServerConnector connector = new UnixDomainServerConnector(server, acceptors, selectors, new HttpConnectionFactory()); - - // Configure Unix-Domain parameters. - - // The Unix-Domain path to listen to. - connector.setUnixDomainPath(Path.of("/tmp/jetty.sock")); - - // The TCP accept queue size. - connector.setAcceptQueueSize(128); - - server.addConnector(connector); - server.start(); - // end::configureConnectorUnix[] - } - - public void configureConnectors() throws Exception - { - // tag::configureConnectors[] - Server server = new Server(); - - // Create a ServerConnector instance on port 8080. - ServerConnector connector1 = new ServerConnector(server, 1, 1, new HttpConnectionFactory()); - connector1.setPort(8080); - server.addConnector(connector1); - - // Create another ServerConnector instance on port 9090, - // for example with a different HTTP configuration. - HttpConfiguration httpConfig2 = new HttpConfiguration(); - httpConfig2.setHttpCompliance(HttpCompliance.LEGACY); - ServerConnector connector2 = new ServerConnector(server, 1, 1, new HttpConnectionFactory(httpConfig2)); - connector2.setPort(9090); - server.addConnector(connector2); - - server.start(); - // end::configureConnectors[] - } - - public void http11() throws Exception - { - // tag::http11[] - Server server = new Server(); - - // The HTTP configuration object. - HttpConfiguration httpConfig = new HttpConfiguration(); - // Configure the HTTP support, for example: - httpConfig.setSendServerVersion(false); - - // The ConnectionFactory for HTTP/1.1. - HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig); - - // Create the ServerConnector. - ServerConnector connector = new ServerConnector(server, http11); - connector.setPort(8080); - - server.addConnector(connector); - server.start(); - // end::http11[] - } - - public void proxyHTTP() throws Exception - { - // tag::proxyHTTP[] - Server server = new Server(); - - // The HTTP configuration object. - HttpConfiguration httpConfig = new HttpConfiguration(); - // Configure the HTTP support, for example: - httpConfig.setSendServerVersion(false); - - // The ConnectionFactory for HTTP/1.1. - HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig); - - // The ConnectionFactory for the PROXY protocol. - ProxyConnectionFactory proxy = new ProxyConnectionFactory(http11.getProtocol()); - - // Create the ServerConnector. - ServerConnector connector = new ServerConnector(server, proxy, http11); - connector.setPort(8080); - - server.addConnector(connector); - server.start(); - // end::proxyHTTP[] - } - - public void proxyHTTPUnix() throws Exception - { - // tag::proxyHTTPUnix[] - Server server = new Server(); - - // The HTTP configuration object. - HttpConfiguration httpConfig = new HttpConfiguration(); - // Configure the HTTP support, for example: - httpConfig.setSendServerVersion(false); - - // The ConnectionFactory for HTTP/1.1. - HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig); - - // The ConnectionFactory for the PROXY protocol. - ProxyConnectionFactory proxy = new ProxyConnectionFactory(http11.getProtocol()); - - // Create the ServerConnector. - UnixDomainServerConnector connector = new UnixDomainServerConnector(server, proxy, http11); - connector.setUnixDomainPath(Path.of("/tmp/jetty.sock")); - - server.addConnector(connector); - server.start(); - // end::proxyHTTPUnix[] - } - - public void tlsHttp11() throws Exception - { - // tag::tlsHttp11[] - Server server = new Server(); - - // The HTTP configuration object. - HttpConfiguration httpConfig = new HttpConfiguration(); - // Add the SecureRequestCustomizer because we are using TLS. - httpConfig.addCustomizer(new SecureRequestCustomizer()); - - // The ConnectionFactory for HTTP/1.1. - HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig); - - // Configure the SslContextFactory with the keyStore information. - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore"); - sslContextFactory.setKeyStorePassword("secret"); - - // The ConnectionFactory for TLS. - SslConnectionFactory tls = new SslConnectionFactory(sslContextFactory, http11.getProtocol()); - - // The ServerConnector instance. - ServerConnector connector = new ServerConnector(server, tls, http11); - connector.setPort(8443); - - server.addConnector(connector); - server.start(); - // end::tlsHttp11[] - } - - public void http11H2C() throws Exception - { - // tag::http11H2C[] - Server server = new Server(); - - // The HTTP configuration object. - HttpConfiguration httpConfig = new HttpConfiguration(); - - // The ConnectionFactory for HTTP/1.1. - HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig); - - // The ConnectionFactory for clear-text HTTP/2. - HTTP2CServerConnectionFactory h2c = new HTTP2CServerConnectionFactory(httpConfig); - - // The ServerConnector instance. - ServerConnector connector = new ServerConnector(server, http11, h2c); - connector.setPort(8080); - - server.addConnector(connector); - server.start(); - // end::http11H2C[] - } - - public void tlsALPNHTTP() throws Exception - { - // tag::tlsALPNHTTP[] - Server server = new Server(); - - // The HTTP configuration object. - HttpConfiguration httpConfig = new HttpConfiguration(); - // Add the SecureRequestCustomizer because we are using TLS. - httpConfig.addCustomizer(new SecureRequestCustomizer()); - - // The ConnectionFactory for HTTP/1.1. - HttpConnectionFactory http11 = new HttpConnectionFactory(httpConfig); - - // The ConnectionFactory for HTTP/2. - HTTP2ServerConnectionFactory h2 = new HTTP2ServerConnectionFactory(httpConfig); - - // The ALPN ConnectionFactory. - ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory(); - // The default protocol to use in case there is no negotiation. - alpn.setDefaultProtocol(http11.getProtocol()); - - // Configure the SslContextFactory with the keyStore information. - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore"); - sslContextFactory.setKeyStorePassword("secret"); - - // The ConnectionFactory for TLS. - SslConnectionFactory tls = new SslConnectionFactory(sslContextFactory, alpn.getProtocol()); - - // The ServerConnector instance. - ServerConnector connector = new ServerConnector(server, tls, alpn, h2, http11); - connector.setPort(8443); - - server.addConnector(connector); - server.start(); - // end::tlsALPNHTTP[] - } - - public void h3() throws Exception - { - // tag::h3[] - Server server = new Server(); - - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore"); - sslContextFactory.setKeyStorePassword("secret"); - - HttpConfiguration httpConfig = new HttpConfiguration(); - httpConfig.addCustomizer(new SecureRequestCustomizer()); - - // Create and configure the HTTP/3 connector. - HTTP3ServerConnector connector = new HTTP3ServerConnector(server, sslContextFactory, new HTTP3ServerConnectionFactory(httpConfig)); - connector.setPort(843); - server.addConnector(connector); - - server.start(); - // end::h3[] - } - - public void conscrypt() - { - // tag::conscrypt[] - // Configure the JDK with the Conscrypt provider. - Security.addProvider(new OpenSSLProvider()); - - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore"); - sslContextFactory.setKeyStorePassword("secret"); - // Configure Jetty's SslContextFactory to use Conscrypt. - sslContextFactory.setProvider("Conscrypt"); - // end::conscrypt[] - } - - public void handlerTree() - { - class LoggingHandler extends AbstractHandler - { - @Override - public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) - { - } - } - - class App1Handler extends AbstractHandler - { - @Override - public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) - { - } - } - - class App2Handler extends HandlerWrapper - { - @Override - public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) - { - } - } - - // tag::handlerTree[] - // Create a Server instance. - Server server = new Server(); - - HandlerCollection collection = new HandlerCollection(); - // Link the root Handler with the Server. - server.setHandler(collection); - - HandlerList list = new HandlerList(); - collection.addHandler(list); - collection.addHandler(new LoggingHandler()); - - list.addHandler(new App1Handler()); - HandlerWrapper wrapper = new HandlerWrapper(); - list.addHandler(wrapper); - - wrapper.setHandler(new App2Handler()); - // end::handlerTree[] - } - - public void handlerAPI() - { - class MyHandler extends AbstractHandler - { - @Override - // tag::handlerAPI[] - public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) - { - } - // end::handlerAPI[] - } - } - - public void handlerHello() throws Exception - { - // tag::handlerHello[] - class HelloWorldHandler extends AbstractHandler - { - @Override - public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException - { - // Mark the request as handled by this Handler. - jettyRequest.setHandled(true); - - response.setStatus(200); - response.setContentType("text/html; charset=UTF-8"); - - // Write a Hello World response. - response.getWriter().print("" + - "" + - "" + - "" + - " Jetty Hello World Handler" + - "" + - "" + - "

Hello World

" + - "" + - "" + - ""); - } - } - - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Set the Hello World Handler. - server.setHandler(new HelloWorldHandler()); - - server.start(); - // end::handlerHello[] - } - - public void handlerFilter() throws Exception - { - class HelloWorldHandler extends AbstractHandler - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) - { - } - } - - // tag::handlerFilter[] - class FilterHandler extends HandlerWrapper - { - @Override - public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - String path = request.getRequestURI(); - if (path.startsWith("/old_path/")) - { - // Rewrite old paths to new paths. - HttpURI uri = jettyRequest.getHttpURI(); - String newPath = "/new_path/" + path.substring("/old_path/".length()); - HttpURI newURI = HttpURI.build(uri).path(newPath); - // Modify the request object. - jettyRequest.setHttpURI(newURI); - } - - // This Handler is not handling the request, so - // it does not call jettyRequest.setHandled(true). - - // Forward to the next Handler. - super.handle(target, jettyRequest, request, response); - } - } - - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Link the Handlers. - FilterHandler filter = new FilterHandler(); - filter.setHandler(new HelloWorldHandler()); - server.setHandler(filter); - - server.start(); - // end::handlerFilter[] - } - - public void contextHandler() throws Exception - { - // tag::contextHandler[] - class ShopHandler extends AbstractHandler - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) - { - baseRequest.setHandled(true); - // Implement the shop. - } - } - - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Create a ContextHandler with contextPath. - ContextHandler context = new ContextHandler(); - context.setContextPath("/shop"); - context.setHandler(new ShopHandler()); - - // Link the context to the server. - server.setHandler(context); - - server.start(); - // end::contextHandler[] - } - - public void contextHandlerCollection() throws Exception - { - // tag::contextHandlerCollection[] - class ShopHandler extends AbstractHandler - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) - { - baseRequest.setHandled(true); - // Implement the shop. - } - } - - class RESTHandler extends AbstractHandler - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) - { - baseRequest.setHandled(true); - // Implement the REST APIs. - } - } - - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Create a ContextHandlerCollection to hold contexts. - ContextHandlerCollection contextCollection = new ContextHandlerCollection(); - // Link the ContextHandlerCollection to the Server. - server.setHandler(contextCollection); - - // Create the context for the shop web application. - ContextHandler shopContext = new ContextHandler("/shop"); - shopContext.setHandler(new ShopHandler()); - // Add it to ContextHandlerCollection. - contextCollection.addHandler(shopContext); - - server.start(); - - // Create the context for the API web application. - ContextHandler apiContext = new ContextHandler("/api"); - apiContext.setHandler(new RESTHandler()); - // Web applications can be deployed after the Server is started. - contextCollection.deployHandler(apiContext, Callback.NOOP); - // end::contextHandlerCollection[] - } - - public void servletContextHandler() throws Exception - { - // tag::servletContextHandler[] - class ShopCartServlet extends HttpServlet - { - @Override - protected void service(HttpServletRequest request, HttpServletResponse response) - { - // Implement the shop cart functionality. - } - } - - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Create a ServletContextHandler with contextPath. - ServletContextHandler context = new ServletContextHandler(); - context.setContextPath("/shop"); - - // Add the Servlet implementing the cart functionality to the context. - ServletHolder servletHolder = context.addServlet(ShopCartServlet.class, "/cart/*"); - // Configure the Servlet with init-parameters. - servletHolder.setInitParameter("maxItems", "128"); - - // Add the CrossOriginFilter to protect from CSRF attacks. - FilterHolder filterHolder = context.addFilter(CrossOriginFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); - // Configure the filter. - filterHolder.setAsyncSupported(true); - - // Link the context to the server. - server.setHandler(context); - - server.start(); - // end::servletContextHandler[] - } - - public void webAppContextHandler() throws Exception - { - // tag::webAppContextHandler[] - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Create a WebAppContext. - WebAppContext context = new WebAppContext(); - // Configure the path of the packaged web application (file or directory). - context.setWar("/path/to/webapp.war"); - // Configure the contextPath. - context.setContextPath("/app"); - - // Link the context to the server. - server.setHandler(context); - - server.start(); - // end::webAppContextHandler[] - } - - public void resourceHandler() throws Exception - { - // tag::resourceHandler[] - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Create and configure a ResourceHandler. - ResourceHandler handler = new ResourceHandler(); - // Configure the directory where static resources are located. - handler.setBaseResource(Resource.newResource("/path/to/static/resources/")); - // Configure directory listing. - handler.setDirectoriesListed(false); - // Configure welcome files. - handler.setWelcomeFiles(new String[]{"index.html"}); - // Configure whether to accept range requests. - handler.setAcceptRanges(true); - - // Link the context to the server. - server.setHandler(handler); - - server.start(); - // end::resourceHandler[] - } - - public void multipleResourcesHandler() throws Exception - { - // tag::multipleResourcesHandler[] - ResourceHandler handler = new ResourceHandler(); - - // For multiple directories, use ResourceCollection. - ResourceCollection directories = new ResourceCollection(); - directories.addPath("/path/to/static/resources/"); - directories.addPath("/another/path/to/static/resources/"); - - handler.setBaseResource(directories); - // end::multipleResourcesHandler[] - } - - public void defaultServlet() - { - // tag::defaultServlet[] - // Create a ServletContextHandler with contextPath. - ServletContextHandler context = new ServletContextHandler(); - context.setContextPath("/app"); - - // Add the DefaultServlet to serve static content. - ServletHolder servletHolder = context.addServlet(DefaultServlet.class, "/"); - // Configure the DefaultServlet with init-parameters. - servletHolder.setInitParameter("resourceBase", "/path/to/static/resources/"); - servletHolder.setAsyncSupported(true); - // end::defaultServlet[] - } - - public void serverGzipHandler() throws Exception - { - // tag::serverGzipHandler[] - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Create and configure GzipHandler. - GzipHandler gzipHandler = new GzipHandler(); - // Only compress response content larger than this. - gzipHandler.setMinGzipSize(1024); - // Do not compress these URI paths. - gzipHandler.setExcludedPaths("/uncompressed"); - // Also compress POST responses. - gzipHandler.addIncludedMethods("POST"); - // Do not compress these mime types. - gzipHandler.addExcludedMimeTypes("font/ttf"); - - // Link a ContextHandlerCollection to manage contexts. - ContextHandlerCollection contexts = new ContextHandlerCollection(); - gzipHandler.setHandler(contexts); - - // Link the GzipHandler to the Server. - server.setHandler(gzipHandler); - - server.start(); - // end::serverGzipHandler[] - } - - public void contextGzipHandler() throws Exception - { - class ShopHandler extends AbstractHandler - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException - { - baseRequest.setHandled(true); - // Implement the shop. - } - } - - class RESTHandler extends AbstractHandler - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) - { - baseRequest.setHandled(true); - // Implement the REST APIs. - } - } - - Server server = new Server(); - ServerConnector connector = new ServerConnector(server); - server.addConnector(connector); - - // tag::contextGzipHandler[] - // Create a ContextHandlerCollection to hold contexts. - ContextHandlerCollection contextCollection = new ContextHandlerCollection(); - // Link the ContextHandlerCollection to the Server. - server.setHandler(contextCollection); - - // Create the context for the shop web application. - ContextHandler shopContext = new ContextHandler("/shop"); - shopContext.setHandler(new ShopHandler()); - - // You want to gzip the shop web application only. - GzipHandler shopGzipHandler = new GzipHandler(); - shopGzipHandler.setHandler(shopContext); - - // Add it to ContextHandlerCollection. - contextCollection.addHandler(shopGzipHandler); - - // Create the context for the API web application. - ContextHandler apiContext = new ContextHandler("/api"); - apiContext.setHandler(new RESTHandler()); - - // Add it to ContextHandlerCollection. - contextCollection.addHandler(apiContext); - // end::contextGzipHandler[] - - server.start(); - } - - public void rewriteHandler() throws Exception - { - // tag::rewriteHandler[] - Server server = new Server(); - ServerConnector connector = new ServerConnector(server); - server.addConnector(connector); - - RewriteHandler rewriteHandler = new RewriteHandler(); - // Compacts URI paths with double slashes, e.g. /ctx//path/to//resource. - rewriteHandler.addRule(new CompactPathRule()); - // Rewrites */products/* to */p/*. - rewriteHandler.addRule(new RewriteRegexRule("/(.*)/product/(.*)", "/$1/p/$2")); - // Redirects permanently to a different URI. - RedirectRegexRule redirectRule = new RedirectRegexRule("/documentation/(.*)", "https://docs.domain.com/$1"); - redirectRule.setStatusCode(HttpStatus.MOVED_PERMANENTLY_301); - rewriteHandler.addRule(redirectRule); - - // Link the RewriteHandler to the Server. - server.setHandler(rewriteHandler); - - // Create a ContextHandlerCollection to hold contexts. - ContextHandlerCollection contextCollection = new ContextHandlerCollection(); - // Link the ContextHandlerCollection to the RewriteHandler. - rewriteHandler.setHandler(contextCollection); - - server.start(); - // end::rewriteHandler[] - } - - public void statsHandler() throws Exception - { - // tag::statsHandler[] - Server server = new Server(); - ServerConnector connector = new ServerConnector(server); - server.addConnector(connector); - - StatisticsHandler statsHandler = new StatisticsHandler(); - - // Link the StatisticsHandler to the Server. - server.setHandler(statsHandler); - - // Create a ContextHandlerCollection to hold contexts. - ContextHandlerCollection contextCollection = new ContextHandlerCollection(); - // Link the ContextHandlerCollection to the StatisticsHandler. - statsHandler.setHandler(contextCollection); - - server.start(); - // end::statsHandler[] - } - - public void securedHandler() throws Exception - { - // tag::securedHandler[] - Server server = new Server(); - - // Configure the HttpConfiguration for the clear-text connector. - int securePort = 8443; - HttpConfiguration httpConfig = new HttpConfiguration(); - httpConfig.setSecurePort(securePort); - - // The clear-text connector. - ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfig)); - connector.setPort(8080); - server.addConnector(connector); - - // Configure the HttpConfiguration for the encrypted connector. - HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); - // Add the SecureRequestCustomizer because we are using TLS. - httpConfig.addCustomizer(new SecureRequestCustomizer()); - - // The HttpConnectionFactory for the encrypted connector. - HttpConnectionFactory http11 = new HttpConnectionFactory(httpsConfig); - - // Configure the SslContextFactory with the keyStore information. - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore"); - sslContextFactory.setKeyStorePassword("secret"); - - // The ConnectionFactory for TLS. - SslConnectionFactory tls = new SslConnectionFactory(sslContextFactory, http11.getProtocol()); - - // The encrypted connector. - ServerConnector secureConnector = new ServerConnector(server, tls, http11); - secureConnector.setPort(8443); - server.addConnector(secureConnector); - - SecuredRedirectHandler securedHandler = new SecuredRedirectHandler(); - - // Link the SecuredRedirectHandler to the Server. - server.setHandler(securedHandler); - - // Create a ContextHandlerCollection to hold contexts. - ContextHandlerCollection contextCollection = new ContextHandlerCollection(); - // Link the ContextHandlerCollection to the StatisticsHandler. - securedHandler.setHandler(contextCollection); - - server.start(); - // end::securedHandler[] - } - - public void defaultHandler() throws Exception - { - // tag::defaultHandler[] - Server server = new Server(); - Connector connector = new ServerConnector(server); - server.addConnector(connector); - - // Create a HandlerList. - HandlerList handlerList = new HandlerList(); - - // Add as first a ContextHandlerCollection to manage contexts. - ContextHandlerCollection contexts = new ContextHandlerCollection(); - handlerList.addHandler(contexts); - - // Add as last a DefaultHandler. - DefaultHandler defaultHandler = new DefaultHandler(); - handlerList.addHandler(defaultHandler); - - // Link the HandlerList to the Server. - server.setHandler(handlerList); - - server.start(); - // end::defaultHandler[] - } - - public void continue100() - { - // tag::continue100[] - class Continue100HttpServlet extends HttpServlet - { - @Override - protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException - { - // Inspect the method and headers. - boolean isPost = HttpMethod.POST.is(request.getMethod()); - boolean expects100 = HttpHeaderValue.CONTINUE.is(request.getHeader("Expect")); - long contentLength = request.getContentLengthLong(); - - if (isPost && expects100) - { - if (contentLength > 1024 * 1024) - { - // Rejects uploads that are too large. - response.sendError(HttpStatus.PAYLOAD_TOO_LARGE_413); - } - else - { - // Getting the request InputStream indicates that - // the application wants to read the request content. - // Jetty will send the 100 Continue response at this - // point, and the client will send the request content. - ServletInputStream input = request.getInputStream(); - - // Read and process the request input. - } - } - else - { - // Process normal requests. - } - } - } - // end::continue100[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java deleted file mode 100644 index 8ff63a56e874..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http2/HTTP2ServerDocs.java +++ /dev/null @@ -1,310 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.server.http2; - -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.jetty.http.HttpFields; -import org.eclipse.jetty.http.HttpMethod; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.http.HttpURI; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.http.MetaData; -import org.eclipse.jetty.http2.ErrorCode; -import org.eclipse.jetty.http2.api.Session; -import org.eclipse.jetty.http2.api.Stream; -import org.eclipse.jetty.http2.api.server.ServerSessionListener; -import org.eclipse.jetty.http2.frames.DataFrame; -import org.eclipse.jetty.http2.frames.HeadersFrame; -import org.eclipse.jetty.http2.frames.PushPromiseFrame; -import org.eclipse.jetty.http2.frames.ResetFrame; -import org.eclipse.jetty.http2.frames.SettingsFrame; -import org.eclipse.jetty.http2.server.RawHTTP2ServerConnectionFactory; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.util.BufferUtil; -import org.eclipse.jetty.util.Callback; -import org.eclipse.jetty.util.resource.Resource; - -import static java.lang.System.Logger.Level.INFO; - -@SuppressWarnings("unused") -public class HTTP2ServerDocs -{ - public void setup() throws Exception - { - // tag::setup[] - // Create a Server instance. - Server server = new Server(); - - ServerSessionListener sessionListener = new ServerSessionListener.Adapter(); - - // Create a ServerConnector with RawHTTP2ServerConnectionFactory. - RawHTTP2ServerConnectionFactory http2 = new RawHTTP2ServerConnectionFactory(sessionListener); - - // Configure RawHTTP2ServerConnectionFactory, for example: - - // Configure the max number of concurrent requests. - http2.setMaxConcurrentStreams(128); - // Enable support for CONNECT. - http2.setConnectProtocolEnabled(true); - - // Create the ServerConnector. - ServerConnector connector = new ServerConnector(server, http2); - - // Add the Connector to the Server - server.addConnector(connector); - - // Start the Server so it starts accepting connections from clients. - server.start(); - // end::setup[] - } - - public void accept() - { - // tag::accept[] - ServerSessionListener sessionListener = new ServerSessionListener.Adapter() - { - @Override - public void onAccept(Session session) - { - SocketAddress remoteAddress = session.getRemoteSocketAddress(); - System.getLogger("http2").log(INFO, "Connection from {0}", remoteAddress); - } - }; - // end::accept[] - } - - public void preface() - { - // tag::preface[] - ServerSessionListener sessionListener = new ServerSessionListener.Adapter() - { - @Override - public Map onPreface(Session session) - { - // Customize the settings, for example: - Map settings = new HashMap<>(); - - // Tell the client that HTTP/2 push is disabled. - settings.put(SettingsFrame.ENABLE_PUSH, 0); - - return settings; - } - }; - // end::preface[] - } - - public void request() - { - // tag::request[] - ServerSessionListener sessionListener = new ServerSessionListener.Adapter() - { - @Override - public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) - { - // This is the "new stream" event, so it's guaranteed to be a request. - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - - // Return a Stream.Listener to handle the request events, - // for example request content events or a request reset. - return new Stream.Listener.Adapter(); - } - }; - // end::request[] - } - - public void requestContent() - { - // tag::requestContent[] - ServerSessionListener sessionListener = new ServerSessionListener.Adapter() - { - @Override - public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) - { - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - // Return a Stream.Listener to handle the request events. - return new Stream.Listener.Adapter() - { - @Override - public void onData(Stream stream, DataFrame frame, Callback callback) - { - // Get the content buffer. - ByteBuffer buffer = frame.getData(); - - // Consume the buffer, here - as an example - just log it. - System.getLogger("http2").log(INFO, "Consuming buffer {0}", buffer); - - // Tell the implementation that the buffer has been consumed. - callback.succeeded(); - - // By returning from the method, implicitly tell the implementation - // to deliver to this method more DATA frames when they are available. - } - }; - } - }; - // end::requestContent[] - } - - public void response() - { - // tag::response[] - ServerSessionListener sessionListener = new ServerSessionListener.Adapter() - { - @Override - public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) - { - // Send a response after reading the request. - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - if (frame.isEndStream()) - { - respond(stream, request); - return null; - } - else - { - return new Stream.Listener.Adapter() - { - @Override - public void onData(Stream stream, DataFrame frame, Callback callback) - { - // Consume the request content. - callback.succeeded(); - if (frame.isEndStream()) - respond(stream, request); - } - }; - } - } - - private void respond(Stream stream, MetaData.Request request) - { - // Prepare the response HEADERS frame. - - // The response HTTP status and HTTP headers. - MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, HttpFields.EMPTY); - - if (HttpMethod.GET.is(request.getMethod())) - { - // The response content. - ByteBuffer resourceBytes = getResourceBytes(request); - - // Send the HEADERS frame with the response status and headers, - // and a DATA frame with the response content bytes. - stream.headers(new HeadersFrame(stream.getId(), response, null, false)) - .thenCompose(s -> s.data(new DataFrame(s.getId(), resourceBytes, true))); - } - else - { - // Send just the HEADERS frame with the response status and headers. - stream.headers(new HeadersFrame(stream.getId(), response, null, true)); - } - } - // tag::exclude[] - - private ByteBuffer getResourceBytes(MetaData.Request request) - { - return ByteBuffer.allocate(1024); - } - // end::exclude[] - }; - // end::response[] - } - - public void reset() - { - float maxRequestRate = 0F; - // tag::reset[] - ServerSessionListener sessionListener = new ServerSessionListener.Adapter() - { - @Override - public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) - { - float requestRate = calculateRequestRate(); - - if (requestRate > maxRequestRate) - { - stream.reset(new ResetFrame(stream.getId(), ErrorCode.REFUSED_STREAM_ERROR.code), Callback.NOOP); - return null; - } - else - { - // The request is accepted. - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - // Return a Stream.Listener to handle the request events. - return new Stream.Listener.Adapter(); - } - } - // tag::exclude[] - - private float calculateRequestRate() - { - return 0F; - } - // end::exclude[] - }; - // end::reset[] - } - - public void push() throws Exception - { - // tag::push[] - // The favicon bytes. - ByteBuffer faviconBuffer = BufferUtil.toBuffer(Resource.newResource("/path/to/favicon.ico"), true); - - ServerSessionListener sessionListener = new ServerSessionListener.Adapter() - { - // By default, push is enabled. - private boolean pushEnabled = true; - - @Override - public void onSettings(Session session, SettingsFrame frame) - { - // Check whether the client sent an ENABLE_PUSH setting. - Map settings = frame.getSettings(); - Integer enablePush = settings.get(SettingsFrame.ENABLE_PUSH); - if (enablePush != null) - pushEnabled = enablePush == 1; - } - - @Override - public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) - { - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - if (pushEnabled && request.getURIString().endsWith("/index.html")) - { - // Push the favicon. - HttpURI pushedURI = HttpURI.build(request.getURI()).path("/favicon.ico"); - MetaData.Request pushedRequest = new MetaData.Request("GET", pushedURI, HttpVersion.HTTP_2, HttpFields.EMPTY); - PushPromiseFrame promiseFrame = new PushPromiseFrame(stream.getId(), 0, pushedRequest); - stream.push(promiseFrame, new Stream.Listener.Adapter()) - .thenCompose(pushedStream -> - { - // Send the favicon "response". - MetaData.Response pushedResponse = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, HttpFields.EMPTY); - return pushedStream.headers(new HeadersFrame(pushedStream.getId(), pushedResponse, null, false)) - .thenCompose(pushed -> pushed.data(new DataFrame(pushed.getId(), faviconBuffer, true))); - }); - } - // Return a Stream.Listener to handle the request events. - return new Stream.Listener.Adapter(); - } - }; - // end::push[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java deleted file mode 100644 index e113bbd686d2..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/http3/HTTP3ServerDocs.java +++ /dev/null @@ -1,334 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.server.http3; - -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.RejectedExecutionException; - -import org.eclipse.jetty.http.HttpFields; -import org.eclipse.jetty.http.HttpMethod; -import org.eclipse.jetty.http.HttpStatus; -import org.eclipse.jetty.http.HttpVersion; -import org.eclipse.jetty.http.MetaData; -import org.eclipse.jetty.http3.api.Session; -import org.eclipse.jetty.http3.api.Stream; -import org.eclipse.jetty.http3.frames.DataFrame; -import org.eclipse.jetty.http3.frames.HeadersFrame; -import org.eclipse.jetty.http3.internal.HTTP3ErrorCode; -import org.eclipse.jetty.http3.server.HTTP3ServerConnector; -import org.eclipse.jetty.http3.server.RawHTTP3ServerConnectionFactory; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.util.ssl.SslContextFactory; - -import static java.lang.System.Logger.Level.INFO; - -@SuppressWarnings("unused") -public class HTTP3ServerDocs -{ - public void setup() throws Exception - { - // tag::setup[] - // Create a Server instance. - Server server = new Server(); - - // HTTP/3 is always secure, so it always need a SslContextFactory. - SslContextFactory.Server sslContextFactory = new SslContextFactory.Server(); - sslContextFactory.setKeyStorePath("/path/to/keystore"); - sslContextFactory.setKeyStorePassword("secret"); - - // The listener for session events. - Session.Server.Listener sessionListener = new Session.Server.Listener() {}; - - // Create and configure the RawHTTP3ServerConnectionFactory. - RawHTTP3ServerConnectionFactory http3 = new RawHTTP3ServerConnectionFactory(sessionListener); - http3.getHTTP3Configuration().setStreamIdleTimeout(15000); - - // Create and configure the HTTP3ServerConnector. - HTTP3ServerConnector connector = new HTTP3ServerConnector(server, sslContextFactory, http3); - // Configure the max number of requests per QUIC connection. - connector.getQuicConfiguration().setMaxBidirectionalRemoteStreams(1024); - - // Add the Connector to the Server. - server.addConnector(connector); - - // Start the Server so it starts accepting connections from clients. - server.start(); - // end::setup[] - } - - public void accept() - { - // tag::accept[] - Session.Server.Listener sessionListener = new Session.Server.Listener() - { - @Override - public void onAccept(Session session) - { - SocketAddress remoteAddress = session.getRemoteSocketAddress(); - System.getLogger("http3").log(INFO, "Connection from {0}", remoteAddress); - } - }; - // end::accept[] - } - - public void preface() - { - // tag::preface[] - Session.Server.Listener sessionListener = new Session.Server.Listener() - { - @Override - public Map onPreface(Session session) - { - Map settings = new HashMap<>(); - - // Customize the settings - - return settings; - } - }; - // end::preface[] - } - - public void request() - { - // tag::request[] - Session.Server.Listener sessionListener = new Session.Server.Listener() - { - @Override - public Stream.Server.Listener onRequest(Stream.Server stream, HeadersFrame frame) - { - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - - // Return a Stream.Server.Listener to handle the request events, - // for example request content events or a request reset. - return new Stream.Server.Listener() {}; - } - }; - // end::request[] - } - - public void requestContent() - { - // tag::requestContent[] - Session.Server.Listener sessionListener = new Session.Server.Listener() - { - @Override - public Stream.Server.Listener onRequest(Stream.Server stream, HeadersFrame frame) - { - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - - // Demand to be called back when data is available. - stream.demand(); - - // Return a Stream.Server.Listener to handle the request content. - return new Stream.Server.Listener() - { - @Override - public void onDataAvailable(Stream.Server stream) - { - // Read a chunk of the request content. - Stream.Data data = stream.readData(); - - if (data == null) - { - // No data available now, demand to be called back. - stream.demand(); - } - else - { - // Get the content buffer. - ByteBuffer buffer = data.getByteBuffer(); - - // Consume the buffer, here - as an example - just log it. - System.getLogger("http3").log(INFO, "Consuming buffer {0}", buffer); - - // Tell the implementation that the buffer has been consumed. - data.complete(); - - if (!data.isLast()) - { - // Demand to be called back. - stream.demand(); - } - } - } - }; - } - }; - // end::requestContent[] - } - - public void response() - { - // tag::response[] - Session.Server.Listener sessionListener = new Session.Server.Listener() - { - @Override - public Stream.Server.Listener onRequest(Stream.Server stream, HeadersFrame frame) - { - // Send a response after reading the request. - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - if (frame.isLast()) - { - respond(stream, request); - return null; - } - else - { - // Demand to be called back when data is available. - stream.demand(); - return new Stream.Server.Listener() - { - @Override - public void onDataAvailable(Stream.Server stream) - { - Stream.Data data = stream.readData(); - if (data == null) - { - stream.demand(); - } - else - { - // Consume the request content. - data.complete(); - if (data.isLast()) - respond(stream, request); - } - } - }; - } - } - - private void respond(Stream.Server stream, MetaData.Request request) - { - // Prepare the response HEADERS frame. - - // The response HTTP status and HTTP headers. - MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_3, HttpStatus.OK_200, HttpFields.EMPTY); - - if (HttpMethod.GET.is(request.getMethod())) - { - // The response content. - ByteBuffer resourceBytes = getResourceBytes(request); - - // Send the HEADERS frame with the response status and headers, - // and a DATA frame with the response content bytes. - stream.respond(new HeadersFrame(response, false)) - .thenCompose(s -> s.data(new DataFrame(resourceBytes, true))); - } - else - { - // Send just the HEADERS frame with the response status and headers. - stream.respond(new HeadersFrame(response, true)); - } - } - // tag::exclude[] - - private ByteBuffer getResourceBytes(MetaData.Request request) - { - return ByteBuffer.allocate(1024); - } - // end::exclude[] - }; - // end::response[] - } - - public void reset() - { - float maxRequestRate = 0F; - // tag::reset[] - Session.Server.Listener sessionListener = new Session.Server.Listener() - { - @Override - public Stream.Server.Listener onRequest(Stream.Server stream, HeadersFrame frame) - { - float requestRate = calculateRequestRate(); - - if (requestRate > maxRequestRate) - { - stream.reset(HTTP3ErrorCode.REQUEST_REJECTED_ERROR.code(), new RejectedExecutionException()); - return null; - } - else - { - // The request is accepted. - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - // Return a Stream.Listener to handle the request events. - return new Stream.Server.Listener() {}; - } - } - // tag::exclude[] - - private float calculateRequestRate() - { - return 0F; - } - // end::exclude[] - }; - // end::reset[] - } - - // TODO: push not yet implemented in HTTP/3. -/* - public void push() throws Exception - { - // tag::push[] - // The favicon bytes. - ByteBuffer faviconBuffer = BufferUtil.toBuffer(Resource.newResource("/path/to/favicon.ico"), true); - - ServerSessionListener sessionListener = new ServerSessionListener.Adapter() - { - // By default, push is enabled. - private boolean pushEnabled = true; - - @Override - public void onSettings(Session session, SettingsFrame frame) - { - // Check whether the client sent an ENABLE_PUSH setting. - Map settings = frame.getSettings(); - Integer enablePush = settings.get(SettingsFrame.ENABLE_PUSH); - if (enablePush != null) - pushEnabled = enablePush == 1; - } - - @Override - public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) - { - MetaData.Request request = (MetaData.Request)frame.getMetaData(); - if (pushEnabled && request.getURIString().endsWith("/index.html")) - { - // Push the favicon. - HttpURI pushedURI = HttpURI.build(request.getURI()).path("/favicon.ico"); - MetaData.Request pushedRequest = new MetaData.Request("GET", pushedURI, HttpVersion.HTTP_2, HttpFields.EMPTY); - PushPromiseFrame promiseFrame = new PushPromiseFrame(stream.getId(), 0, pushedRequest); - stream.push(promiseFrame, new Stream.Listener.Adapter()) - .thenCompose(pushedStream -> - { - // Send the favicon "response". - MetaData.Response pushedResponse = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, HttpFields.EMPTY); - return pushedStream.headers(new HeadersFrame(pushedStream.getId(), pushedResponse, null, false)) - .thenCompose(pushed -> pushed.data(new DataFrame(pushed.getId(), faviconBuffer, true))); - }); - } - // Return a Stream.Listener to handle the request events. - return new Stream.Listener.Adapter(); - } - }; - // end::push[] - } - */ -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java deleted file mode 100644 index 8a4b42f4dd5b..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/session/SessionDocs.java +++ /dev/null @@ -1,307 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.server.session; - -import java.io.File; -import java.net.InetSocketAddress; - -import org.eclipse.jetty.memcached.session.MemcachedSessionDataMapFactory; -import org.eclipse.jetty.nosql.mongodb.MongoSessionDataStoreFactory; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.eclipse.jetty.server.session.CachingSessionDataStoreFactory; -import org.eclipse.jetty.server.session.DatabaseAdaptor; -import org.eclipse.jetty.server.session.DefaultSessionCache; -import org.eclipse.jetty.server.session.DefaultSessionCacheFactory; -import org.eclipse.jetty.server.session.DefaultSessionIdManager; -import org.eclipse.jetty.server.session.FileSessionDataStore; -import org.eclipse.jetty.server.session.FileSessionDataStoreFactory; -import org.eclipse.jetty.server.session.HouseKeeper; -import org.eclipse.jetty.server.session.NullSessionCache; -import org.eclipse.jetty.server.session.NullSessionCacheFactory; -import org.eclipse.jetty.server.session.NullSessionDataStore; -import org.eclipse.jetty.server.session.SessionCache; -import org.eclipse.jetty.server.session.SessionHandler; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.webapp.WebAppContext; - -@SuppressWarnings("unused") -public class SessionDocs -{ - public void minimumDefaultSessionIdManager() - { - //tag::default[] - Server server = new Server(); - DefaultSessionIdManager idMgr = new DefaultSessionIdManager(server); - //you must set the workerName unless you set the env viable JETTY_WORKER_NAME - idMgr.setWorkerName("server3"); - server.setSessionIdManager(idMgr); - //end::default[] - } - - public void defaultSessionIdManagerWithHouseKeeper() - { - try - { - //tag::housekeeper[] - Server server = new Server(); - DefaultSessionIdManager idMgr = new DefaultSessionIdManager(server); - idMgr.setWorkerName("server7"); - server.setSessionIdManager(idMgr); - - HouseKeeper houseKeeper = new HouseKeeper(); - houseKeeper.setSessionIdManager(idMgr); - //set the frequency of scavenge cycles - houseKeeper.setIntervalSec(600L); - idMgr.setSessionHouseKeeper(houseKeeper); - //end::housekeeper[] - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - public void servletContextWithSessionHandler() - { - //tag:schsession[] - Server server = new Server(); - - ServletContextHandler context = new ServletContextHandler(server, "/foo", ServletContextHandler.SESSIONS); - SessionHandler sessions = context.getSessionHandler(); - //make idle sessions valid for only 5mins - sessions.setMaxInactiveInterval(300); - //turn off use of cookies - sessions.setUsingCookies(false); - - server.setHandler(context); - //end::schsession[] - } - - public void webAppWithSessionHandler() - { - //tag:wacsession[] - Server server = new Server(); - - WebAppContext context = new WebAppContext(); - SessionHandler sessions = context.getSessionHandler(); - //make idle sessions valid for only 5mins - sessions.setMaxInactiveInterval(300); - //turn off use of cookies - sessions.setUsingCookies(false); - - server.setHandler(context); - //end::wacsession[] - } - - public void defaultSessionCache() - { - //tag::defaultsessioncache[] - Server server = new Server(); - - DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory(); - //EVICT_ON_INACTIVE: evict a session after 60sec inactivity - cacheFactory.setEvictionPolicy(60); - //Only useful with the EVICT_ON_INACTIVE policy - cacheFactory.setSaveOnInactiveEvict(true); - cacheFactory.setFlushOnResponseCommit(true); - cacheFactory.setInvalidateOnShutdown(false); - cacheFactory.setRemoveUnloadableSessions(true); - cacheFactory.setSaveOnCreate(true); - - //Add the factory as a bean to the server, now whenever a - //SessionHandler starts it will consult the bean to create a new DefaultSessionCache - server.addBean(cacheFactory); - //end::defaultsessioncache[] - } - - public void nullSessionCache() - { - //tag::nullsessioncache[] - Server server = new Server(); - NullSessionCacheFactory cacheFactory = new NullSessionCacheFactory(); - cacheFactory.setFlushOnResponseCommit(true); - cacheFactory.setRemoveUnloadableSessions(true); - cacheFactory.setSaveOnCreate(true); - - //Add the factory as a bean to the server, now whenever a - //SessionHandler starts it will consult the bean to create a new NullSessionCache - server.addBean(cacheFactory); - //end::nullsessioncache[] - } - - public void mixedSessionCache() - { - //tag::mixedsessioncache[] - Server server = new Server(); - - DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory(); - //NEVER_EVICT - cacheFactory.setEvictionPolicy(SessionCache.NEVER_EVICT); - cacheFactory.setFlushOnResponseCommit(true); - cacheFactory.setInvalidateOnShutdown(false); - cacheFactory.setRemoveUnloadableSessions(true); - cacheFactory.setSaveOnCreate(true); - - //Add the factory as a bean to the server, now whenever a - //SessionHandler starts it will consult the bean to create a new DefaultSessionCache - server.addBean(cacheFactory); - - ContextHandlerCollection contexts = new ContextHandlerCollection(); - server.setHandler(contexts); - - //Add a webapp that will use a DefaultSessionCache via the DefaultSessionCacheFactory - WebAppContext app1 = new WebAppContext(); - app1.setContextPath("/app1"); - contexts.addHandler(app1); - - //Add a webapp that uses an explicit NullSessionCache instead - WebAppContext app2 = new WebAppContext(); - app2.setContextPath("/app2"); - NullSessionCache nullSessionCache = new NullSessionCache(app2.getSessionHandler()); - nullSessionCache.setFlushOnResponseCommit(true); - nullSessionCache.setRemoveUnloadableSessions(true); - nullSessionCache.setSaveOnCreate(true); - //If we pass an existing SessionCache instance to the SessionHandler, it must be - //fully configured: this means we must also provide SessionDataStore - nullSessionCache.setSessionDataStore(new NullSessionDataStore()); - app2.getSessionHandler().setSessionCache(nullSessionCache); - //end::mixedsessioncache[] - } - - public void fileSessionDataStoreFactory() - { - //tag::filesessiondatastorefactory[] - Server server = new Server(); - - //First lets configure a DefaultSessionCacheFactory - DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory(); - //NEVER_EVICT - cacheFactory.setEvictionPolicy(SessionCache.NEVER_EVICT); - cacheFactory.setFlushOnResponseCommit(true); - cacheFactory.setInvalidateOnShutdown(false); - cacheFactory.setRemoveUnloadableSessions(true); - cacheFactory.setSaveOnCreate(true); - - //Add the factory as a bean to the server, now whenever a - //SessionHandler starts it will consult the bean to create a new DefaultSessionCache - server.addBean(cacheFactory); - - //Now, lets configure a FileSessionDataStoreFactory - FileSessionDataStoreFactory storeFactory = new FileSessionDataStoreFactory(); - storeFactory.setStoreDir(new File("/tmp/sessions")); - storeFactory.setGracePeriodSec(3600); - storeFactory.setSavePeriodSec(0); - - //Add the factory as a bean on the server, now whenever a - //SessionHandler starts, it will consult the bean to create a new FileSessionDataStore - //for use by the DefaultSessionCache - server.addBean(storeFactory); - //end::filesessiondatastorefactory[] - } - - public void fileSessionDataStore() - { - //tag::filesessiondatastore[] - - //create a context - WebAppContext app1 = new WebAppContext(); - app1.setContextPath("/app1"); - - //First, we create a DefaultSessionCache - DefaultSessionCache cache = new DefaultSessionCache(app1.getSessionHandler()); - cache.setEvictionPolicy(SessionCache.NEVER_EVICT); - cache.setFlushOnResponseCommit(true); - cache.setInvalidateOnShutdown(false); - cache.setRemoveUnloadableSessions(true); - cache.setSaveOnCreate(true); - - //Now, we configure a FileSessionDataStore - FileSessionDataStore store = new FileSessionDataStore(); - store.setStoreDir(new File("/tmp/sessions")); - store.setGracePeriodSec(3600); - store.setSavePeriodSec(0); - - //Tell the cache to use the store - cache.setSessionDataStore(store); - - //Tell the contex to use the cache/store combination - app1.getSessionHandler().setSessionCache(cache); - - //end::filesessiondatastore[] - } - - public void cachingSessionDataStore() - { - //tag::cachingsds[] - Server server = new Server(); - - //Make a factory for memcached L2 caches for SessionData - MemcachedSessionDataMapFactory mapFactory = new MemcachedSessionDataMapFactory(); - mapFactory.setExpirySec(0); //items in memcached don't expire - mapFactory.setHeartbeats(true); //tell memcached to use heartbeats - mapFactory.setAddresses(new InetSocketAddress("localhost", 11211)); //use a local memcached instance - mapFactory.setWeights(new int[] {100}); //set the weighting - - - //Make a FileSessionDataStoreFactory for creating FileSessionDataStores - //to persist the session data - FileSessionDataStoreFactory storeFactory = new FileSessionDataStoreFactory(); - storeFactory.setStoreDir(new File("/tmp/sessions")); - storeFactory.setGracePeriodSec(3600); - storeFactory.setSavePeriodSec(0); - - //Make a factory that plugs the L2 cache into the SessionDataStore - CachingSessionDataStoreFactory cachingSessionDataStoreFactory = new CachingSessionDataStoreFactory(); - cachingSessionDataStoreFactory.setSessionDataMapFactory(mapFactory); - cachingSessionDataStoreFactory.setSessionStoreFactory(storeFactory); - - //Register it as a bean so that all SessionHandlers will use it - //to make FileSessionDataStores that use memcached as an L2 SessionData cache. - server.addBean(cachingSessionDataStoreFactory); - //end::cachingsds[] - } - - public void jdbcSessionDataStore() - { - //tag::dbaDatasource[] - DatabaseAdaptor datasourceAdaptor = new DatabaseAdaptor(); - datasourceAdaptor.setDatasourceName("/jdbc/myDS"); - //end::dbaDatasource[] - - //tag::dbaDriver[] - DatabaseAdaptor driverAdaptor = new DatabaseAdaptor(); - driverAdaptor.setDriverInfo("com.mysql.jdbc.Driver", "jdbc:mysql://127.0.0.1:3306/sessions?user=sessionsadmin"); - //end::dbaDriver[] - } - - public void mongoSessionDataStore() - { - //tag::mongosdfactory[] - Server server = new Server(); - - MongoSessionDataStoreFactory mongoSessionDataStoreFactory = new MongoSessionDataStoreFactory(); - mongoSessionDataStoreFactory.setGracePeriodSec(3600); - mongoSessionDataStoreFactory.setSavePeriodSec(0); - mongoSessionDataStoreFactory.setDbName("HttpSessions"); - mongoSessionDataStoreFactory.setCollectionName("JettySessions"); - - // Either set the connectionString - mongoSessionDataStoreFactory.setConnectionString("mongodb:://localhost:27017"); - // or alternatively set the host and port. - mongoSessionDataStoreFactory.setHost("localhost"); - mongoSessionDataStoreFactory.setPort(27017); - //end::mongosdfactory[] - } -} diff --git a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java b/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java deleted file mode 100644 index 50eee4261465..000000000000 --- a/documentation/jetty-documentation/src/main/java/org/eclipse/jetty/docs/programming/server/websocket/WebSocketServerDocs.java +++ /dev/null @@ -1,388 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others. -// -// This program and the accompanying materials are made available under the -// terms of the Eclipse Public License v. 2.0 which is available at -// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 -// which is available at https://www.apache.org/licenses/LICENSE-2.0. -// -// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 -// ======================================================================== -// - -package org.eclipse.jetty.docs.programming.server.websocket; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.websocket.DeploymentException; -import javax.websocket.server.ServerContainer; -import javax.websocket.server.ServerEndpoint; -import javax.websocket.server.ServerEndpointConfig; - -import org.eclipse.jetty.http.pathmap.PathSpec; -import org.eclipse.jetty.http.pathmap.UriTemplatePathSpec; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.webapp.WebAppContext; -import org.eclipse.jetty.websocket.api.annotations.WebSocket; -import org.eclipse.jetty.websocket.javax.server.config.JavaxWebSocketServletContainerInitializer; -import org.eclipse.jetty.websocket.server.JettyWebSocketCreator; -import org.eclipse.jetty.websocket.server.JettyWebSocketServerContainer; -import org.eclipse.jetty.websocket.server.JettyWebSocketServlet; -import org.eclipse.jetty.websocket.server.JettyWebSocketServletFactory; -import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; - -@SuppressWarnings("unused") -public class WebSocketServerDocs -{ - public void standardContainerWebAppContext() throws Exception - { - // tag::standardContainerWebAppContext[] - // Create a Server with a ServerConnector listening on port 8080. - Server server = new Server(8080); - - // Create a WebAppContext with the given context path. - WebAppContext handler = new WebAppContext("/path/to/webapp", "/ctx"); - server.setHandler(handler); - - // Starting the Server will start the WebAppContext. - server.start(); - // end::standardContainerWebAppContext[] - } - - public void standardContainerServletContextHandler() throws Exception - { - // tag::standardContainerServletContextHandler[] - // Create a Server with a ServerConnector listening on port 8080. - Server server = new Server(8080); - - // Create a ServletContextHandler with the given context path. - ServletContextHandler handler = new ServletContextHandler(server, "/ctx"); - server.setHandler(handler); - - // Ensure that JavaxWebSocketServletContainerInitializer is initialized, - // to setup the ServerContainer for this web application context. - JavaxWebSocketServletContainerInitializer.configure(handler, null); - - // Starting the Server will start the ServletContextHandler. - server.start(); - // end::standardContainerServletContextHandler[] - } - - public void standardEndpointsInitialization() throws Exception - { - // tag::standardEndpointsInitialization[] - // Create a Server with a ServerConnector listening on port 8080. - Server server = new Server(8080); - - // Create a ServletContextHandler with the given context path. - ServletContextHandler handler = new ServletContextHandler(server, "/ctx"); - server.setHandler(handler); - - // Ensure that JavaxWebSocketServletContainerInitializer is initialized, - // to setup the ServerContainer for this web application context. - JavaxWebSocketServletContainerInitializer.configure(handler, null); - - // Add a WebSocket-initializer Servlet to register WebSocket endpoints. - handler.addServlet(MyJavaxWebSocketInitializerServlet.class, "/*"); - - // Starting the Server will start the ServletContextHandler. - server.start(); - // end::standardEndpointsInitialization[] - } - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::standardWebSocketInitializerServlet[] - public class MyJavaxWebSocketInitializerServlet extends HttpServlet - { - @Override - public void init() throws ServletException - { - try - { - // Retrieve the ServerContainer from the ServletContext attributes. - ServerContainer container = (ServerContainer)getServletContext().getAttribute(ServerContainer.class.getName()); - - // Configure the ServerContainer. - container.setDefaultMaxTextMessageBufferSize(128 * 1024); - - // Simple registration of your WebSocket endpoints. - container.addEndpoint(MyJavaxWebSocketEndPoint.class); - - // Advanced registration of your WebSocket endpoints. - container.addEndpoint( - ServerEndpointConfig.Builder.create(MyJavaxWebSocketEndPoint.class, "/ws") - .subprotocols(List.of("my-ws-protocol")) - .build() - ); - } - catch (DeploymentException x) - { - throw new ServletException(x); - } - } - } - // end::standardWebSocketInitializerServlet[] - - public void standardContainerAndEndpoints() throws Exception - { - // tag::standardContainerAndEndpoints[] - // Create a Server with a ServerConnector listening on port 8080. - Server server = new Server(8080); - - // Create a ServletContextHandler with the given context path. - ServletContextHandler handler = new ServletContextHandler(server, "/ctx"); - server.setHandler(handler); - - // Setup the ServerContainer and the WebSocket endpoints for this web application context. - JavaxWebSocketServletContainerInitializer.configure(handler, (servletContext, container) -> - { - // Configure the ServerContainer. - container.setDefaultMaxTextMessageBufferSize(128 * 1024); - - // Simple registration of your WebSocket endpoints. - container.addEndpoint(MyJavaxWebSocketEndPoint.class); - - // Advanced registration of your WebSocket endpoints. - container.addEndpoint( - ServerEndpointConfig.Builder.create(MyJavaxWebSocketEndPoint.class, "/ws") - .subprotocols(List.of("my-ws-protocol")) - .build() - ); - }); - - // Starting the Server will start the ServletContextHandler. - server.start(); - // end::standardContainerAndEndpoints[] - } - - public void jettyContainerServletContextHandler() throws Exception - { - // tag::jettyContainerServletContextHandler[] - // Create a Server with a ServerConnector listening on port 8080. - Server server = new Server(8080); - - // Create a ServletContextHandler with the given context path. - ServletContextHandler handler = new ServletContextHandler(server, "/ctx"); - server.setHandler(handler); - - // Ensure that JettyWebSocketServletContainerInitializer is initialized, - // to setup the JettyWebSocketServerContainer for this web application context. - JettyWebSocketServletContainerInitializer.configure(handler, null); - - // Starting the Server will start the ServletContextHandler. - server.start(); - // end::jettyContainerServletContextHandler[] - } - - public void jettyEndpointsInitialization() throws Exception - { - // tag::jettyEndpointsInitialization[] - // Create a Server with a ServerConnector listening on port 8080. - Server server = new Server(8080); - - // Create a ServletContextHandler with the given context path. - ServletContextHandler handler = new ServletContextHandler(server, "/ctx"); - server.setHandler(handler); - - // Ensure that JettyWebSocketServletContainerInitializer is initialized, - // to setup the JettyWebSocketServerContainer for this web application context. - JettyWebSocketServletContainerInitializer.configure(handler, null); - - // Add a WebSocket-initializer Servlet to register WebSocket endpoints. - handler.addServlet(MyJettyWebSocketInitializerServlet.class, "/*"); - - // Starting the Server will start the ServletContextHandler. - server.start(); - // end::jettyEndpointsInitialization[] - } - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::jettyWebSocketInitializerServlet[] - public class MyJettyWebSocketInitializerServlet extends HttpServlet - { - @Override - public void init() throws ServletException - { - // Retrieve the JettyWebSocketServerContainer. - JettyWebSocketServerContainer container = JettyWebSocketServerContainer.getContainer(getServletContext()); - - // Configure the JettyWebSocketServerContainer. - container.setMaxTextMessageSize(128 * 1024); - - // Simple registration of your WebSocket endpoints. - container.addMapping("/ws/myURI", MyJettyWebSocketEndPoint.class); - - // Advanced registration of your WebSocket endpoints. - container.addMapping("/ws/myOtherURI", (upgradeRequest, upgradeResponse) -> - new MyOtherJettyWebSocketEndPoint() - ); - } - } - // end::jettyWebSocketInitializerServlet[] - - public void jettyContainerAndEndpoints() throws Exception - { - // tag::jettyContainerAndEndpoints[] - // Create a Server with a ServerConnector listening on port 8080. - Server server = new Server(8080); - - // Create a ServletContextHandler with the given context path. - ServletContextHandler handler = new ServletContextHandler(server, "/ctx"); - server.setHandler(handler); - - // Setup the JettyWebSocketServerContainer and the WebSocket endpoints for this web application context. - JettyWebSocketServletContainerInitializer.configure(handler, (servletContext, container) -> - { - // Configure the ServerContainer. - container.setMaxTextMessageSize(128 * 1024); - - // Add your WebSocket endpoint(s) to the JettyWebSocketServerContainer. - container.addMapping("/ws/myURI", MyJettyWebSocketEndPoint.class); - - // Use JettyWebSocketCreator to have more control on the WebSocket endpoint creation. - container.addMapping("/ws/myOtherURI", (upgradeRequest, upgradeResponse) -> - { - // Possibly inspect the upgrade request and modify the upgrade response. - upgradeResponse.setAcceptedSubProtocol("my-ws-protocol"); - - // Create the new WebSocket endpoint. - return new MyOtherJettyWebSocketEndPoint(); - }); - }); - - // Starting the Server will start the ServletContextHandler. - server.start(); - // end::jettyContainerAndEndpoints[] - } - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::jettyContainerUpgrade[] - public class ProgrammaticWebSocketUpgradeServlet extends HttpServlet - { - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException - { - if (requiresWebSocketUpgrade(request)) - { - // Retrieve the JettyWebSocketServerContainer. - JettyWebSocketServerContainer container = JettyWebSocketServerContainer.getContainer(getServletContext()); - - // Use a JettyWebSocketCreator to inspect the upgrade request, - // possibly modify the upgrade response, and create the WebSocket endpoint. - JettyWebSocketCreator creator = (upgradeRequest, upgradeResponse) -> new MyJettyWebSocketEndPoint(); - - // Perform the direct WebSocket upgrade. - container.upgrade(creator, request, response); - } - else - { - // Normal handling of the HTTP request/response. - } - } - } - // end::jettyContainerUpgrade[] - - private boolean requiresWebSocketUpgrade(HttpServletRequest request) - { - return false; - } - - public void jettyWebSocketServletMain() throws Exception - { - // tag::jettyWebSocketServletMain[] - // Create a Server with a ServerConnector listening on port 8080. - Server server = new Server(8080); - - // Create a ServletContextHandler with the given context path. - ServletContextHandler handler = new ServletContextHandler(server, "/ctx"); - server.setHandler(handler); - - // Setup the JettyWebSocketServerContainer to initialize WebSocket components. - JettyWebSocketServletContainerInitializer.configure(handler, null); - - // Add your WebSocketServlet subclass to the ServletContextHandler. - handler.addServlet(MyJettyWebSocketServlet.class, "/ws/*"); - - // Starting the Server will start the ServletContextHandler. - server.start(); - // end::jettyWebSocketServletMain[] - } - - @SuppressWarnings("InnerClassMayBeStatic") - // tag::jettyWebSocketServlet[] - public class MyJettyWebSocketServlet extends JettyWebSocketServlet - { - @Override - protected void configure(JettyWebSocketServletFactory factory) - { - // At most 1 MiB text messages. - factory.setMaxTextMessageSize(1048576); - - // Add the WebSocket endpoint. - factory.addMapping("/ws/someURI", (upgradeRequest, upgradeResponse) -> - { - // Possibly inspect the upgrade request and modify the upgrade response. - - // Create the new WebSocket endpoint. - return new MyJettyWebSocketEndPoint(); - }); - } - } - // end::jettyWebSocketServlet[] - - @ServerEndpoint("/ws") - private static class MyJavaxWebSocketEndPoint - { - } - - @WebSocket - private static class MyJettyWebSocketEndPoint - { - } - - @WebSocket - private static class MyOtherJettyWebSocketEndPoint - { - } - - public void uriTemplatePathSpec() - { - Server server = new Server(8080); - - // tag::uriTemplatePathSpec[] - ServletContextHandler handler = new ServletContextHandler(server, "/ctx"); - - // Configure the JettyWebSocketServerContainer. - JettyWebSocketServletContainerInitializer.configure(handler, (servletContext, container) -> - { - container.addMapping("/ws/chat/{room}", (upgradeRequest, upgradeResponse) -> - { - // Retrieve the URI template. - UriTemplatePathSpec pathSpec = (UriTemplatePathSpec)upgradeRequest.getServletAttribute(PathSpec.class.getName()); - - // Match the URI template. - Map params = pathSpec.getPathParams(upgradeRequest.getRequestPath()); - String room = params.get("room"); - - // Create the new WebSocket endpoint with the URI template information. - return new MyWebSocketRoomEndPoint(room); - }); - }); - // end::uriTemplatePathSpec[] - } - - @WebSocket - private static class MyWebSocketRoomEndPoint - { - public MyWebSocketRoomEndPoint(String room) - { - } - } -} diff --git a/documentation/jetty/antora.yml b/documentation/jetty/antora.yml index f6078de1f1a6..0d4cd6233ee2 100644 --- a/documentation/jetty/antora.yml +++ b/documentation/jetty/antora.yml @@ -3,10 +3,9 @@ version: '10' title: Eclipse Jetty asciidoc: attributes: - javadoc-url: https://jetty.org/javadoc/jetty-10 - jdurl: '{javadoc-url}' + javadoc-url: https://javadoc.jetty.org/jetty-10 jetty-home: ${jetty.home}@ - version: 10.0.21-SNAPSHOT + jetty-version: ${project.version} idprefix: '' idseparator: '' run-jetty-classpath: ${settings.localRepository}/org/eclipse/jetty/tests/jetty-home-tester/${project.version}/jetty-home-tester-${project.version}.jar${path.separator}${run.jetty.classpath} diff --git a/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/HTTP2Docs.java b/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/HTTP2Docs.java index 5bc4f08d1766..099a7171b5e5 100644 --- a/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/HTTP2Docs.java +++ b/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/HTTP2Docs.java @@ -44,7 +44,7 @@ public void dataDemanded() throws Exception Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); diff --git a/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java b/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java index 8d4447db3363..3494ea76877c 100644 --- a/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java +++ b/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/client/http2/HTTP2ClientDocs.java @@ -143,7 +143,7 @@ public void newStream() throws Exception // Configure the request headers. HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {jetty-version}"); // The request metadata with method, URI and headers. MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); @@ -209,7 +209,7 @@ public void responseListener() throws Exception Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); @@ -262,7 +262,7 @@ public void reset() throws Exception Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); @@ -292,7 +292,7 @@ public void push() throws Exception Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); @@ -354,7 +354,7 @@ public void pushReset() throws Exception Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP2Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); diff --git a/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java b/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java index 6af744c01e9f..5617db5cf2d2 100644 --- a/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java +++ b/documentation/jetty/modules/code/examples/src/main/java/org/eclipse/jetty/docs/programming/client/http3/HTTP3ClientDocs.java @@ -114,7 +114,7 @@ public void newStream() throws Exception // Configure the request headers. HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {jetty-version}"); // The request metadata with method, URI and headers. MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8444/path"), HttpVersion.HTTP_3, requestHeaders); @@ -180,7 +180,7 @@ public void responseListener() throws Exception Session.Client session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8444/path"), HttpVersion.HTTP_3, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, true); @@ -238,7 +238,7 @@ public void reset() throws Exception Session.Client session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, true); @@ -270,7 +270,7 @@ public void push() throws Exception Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); @@ -332,7 +332,7 @@ public void pushReset() throws Exception Session session = sessionCF.get(); HttpFields requestHeaders = HttpFields.build() - .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {version}"); + .put(HttpHeader.USER_AGENT, "Jetty HTTP3Client {jetty-version}"); MetaData.Request request = new MetaData.Request("GET", HttpURI.from("http://localhost:8080/path"), HttpVersion.HTTP_2, requestHeaders); HeadersFrame headersFrame = new HeadersFrame(request, null, true); diff --git a/documentation/jetty/modules/operations-guide/pages/begin/index.adoc b/documentation/jetty/modules/operations-guide/pages/begin/index.adoc index 017f57255867..69191bdd57d3 100644 --- a/documentation/jetty/modules/operations-guide/pages/begin/index.adoc +++ b/documentation/jetty/modules/operations-guide/pages/begin/index.adoc @@ -63,7 +63,7 @@ The Eclipse Jetty distribution is available in both `zip` and `gzip` formats; do [[install]] == Installing Jetty -After the download, unpacking Eclipse Jetty will extract the files into a directory called `jetty-home-VERSION`, where `VERSION` is the version that you downloaded, for example `{version}`, so that the directory is called `jetty-home-{version}`. +After the download, unpacking Eclipse Jetty will extract the files into a directory called `jetty-home-VERSION`, where `VERSION` is the version that you downloaded, for example `{jetty-version}`, so that the directory is called `jetty-home-{jetty-version}`. Unpack Eclipse Jetty compressed file in a convenient location, for example under `/opt`. diff --git a/documentation/jetty/modules/operations-guide/pages/modules/standard.adoc b/documentation/jetty/modules/operations-guide/pages/modules/standard.adoc index ab1c25bdb6b4..0dca53211788 100644 --- a/documentation/jetty/modules/operations-guide/pages/modules/standard.adoc +++ b/documentation/jetty/modules/operations-guide/pages/modules/standard.adoc @@ -294,7 +294,7 @@ Whether you want to send the `Server` header in every HTTP response: ---- HTTP/1.1 200 OK Content-Length: 0 -Server: Jetty({version}) +Server: Jetty({jetty-version}) ---- [[server-config]] diff --git a/documentation/jetty/modules/operations-guide/pages/session/index.adoc b/documentation/jetty/modules/operations-guide/pages/session/index.adoc index 483bc9da9322..71a3ef9e070e 100644 --- a/documentation/jetty/modules/operations-guide/pages/session/index.adoc +++ b/documentation/jetty/modules/operations-guide/pages/session/index.adoc @@ -612,8 +612,9 @@ IMPORTANT: We recommend that you backup your stored sessions before running the How to use the converter: +[,screen,subs=attributes] ---- -java -cp jetty-servlet-api-4.0.2.jar:jetty-util-{VERSION}.jar:jetty-server-{VERSION}.jar:infinispan-remote-9.1.0.Final.jar:jetty-infinispan-{VERSION}.jar:[other classpath] org.eclipse.jetty.session.infinispan.InfinispanSessionLegacyConverter +java -cp jetty-servlet-api-4.0.2.jar:jetty-util-{jetty-version}.jar:jetty-server-{jetty-version}.jar:infinispan-remote-9.1.0.Final.jar:jetty-infinispan-{jetty-version}.jar:[other classpath] org.eclipse.jetty.session.infinispan.InfinispanSessionLegacyConverter Usage: InfinispanSessionLegacyConverter [-Dhost=127.0.0.1] [-Dverbose=true|false] [check] ---- @@ -631,8 +632,9 @@ check::: the optional check command will verify sessions have been converted. Us To perform the conversion, run the InfinispanSessionLegacyConverter with just the `cache-name`, and optionally the `host` system property. The following command will attempt to convert all sessions in the cached named `my-remote-cache` on the machine `myhost`, ensuring that application classes in the `/my/custom/classes` directory are on the classpath: +[,screen,subs=attributes] ---- -java -cp jetty-servlet-api-4.0.2.jar:jetty-util-{VERSION}.jar:jetty-server-{VERSION}.jar:infinispan-remote-9.1.0.Final.jar:jetty-infinispan-{VERSION}.jar:/my/custom/classes org.eclipse.jetty.session.infinispan.InfinispanSessionLegacyConverter -Dhost=myhost my-remote-cache +java -cp jetty-servlet-api-4.0.2.jar:jetty-util-{jetty-version}.jar:jetty-server-{jetty-version}.jar:infinispan-remote-9.1.0.Final.jar:jetty-infinispan-{jetty-version}.jar:/my/custom/classes org.eclipse.jetty.session.infinispan.InfinispanSessionLegacyConverter -Dhost=myhost my-remote-cache ---- If the converter fails to convert a session, an error message and stacktrace will be printed and the conversion will abort. The failed session should be untouched, however _it is prudent to take a backup of your cache before attempting the conversion_. diff --git a/documentation/jetty/modules/programming-guide/pages/arch/io.adoc b/documentation/jetty/modules/programming-guide/pages/arch/io.adoc index c6452411c11b..90fdcff1e5c5 100644 --- a/documentation/jetty/modules/programming-guide/pages/arch/io.adoc +++ b/documentation/jetty/modules/programming-guide/pages/arch/io.adoc @@ -74,7 +74,7 @@ This allows to use the HTTP/1.1 `Connection` during the initial communication an Creating `Connection` instances is performed on the server-side by link:{javadoc-url}/org/eclipse/jetty/server/ConnectionFactory.html[`ConnectionFactory`]s and on the client-side by link:{javadoc-url}/org/eclipse/jetty/io/ClientConnectionFactory.html[`ClientConnectionFactory`]s. -On the server-side, the component that aggregates a `SelectorManager` with a set of ``ConnectionFactory``s is link:{javadoc-url}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`] for TCP sockets, link:{javadoc-url}/org/eclipse/jetty/quic/server/QuicServerConnector.html[`QuicServerConnector`] for QUIC sockets, and link:{JDURL}/org/eclipse/jetty/unixdomain/server/UnixDomainServerConnector.html[`UnixDomainServerConnector`] for Unix-Domain sockets (see the xref:server/io-arch.adoc[server-side architecture section] for more information). +On the server-side, the component that aggregates a `SelectorManager` with a set of ``ConnectionFactory``s is link:{javadoc-url}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`] for TCP sockets, link:{javadoc-url}/org/eclipse/jetty/quic/server/QuicServerConnector.html[`QuicServerConnector`] for QUIC sockets, and link:{javadoc-url}/org/eclipse/jetty/unixdomain/server/UnixDomainServerConnector.html[`UnixDomainServerConnector`] for Unix-Domain sockets (see the xref:server/io-arch.adoc[server-side architecture section] for more information). On the client-side, the components that aggregates a `SelectorManager` with a set of ``ClientConnectionFactory``s are link:{javadoc-url}/org/eclipse/jetty/client/HttpClientTransport.html[`HttpClientTransport`] subclasses (see the xref:client/io-arch.adoc[client-side architecture section] for more information). diff --git a/documentation/jetty/modules/programming-guide/pages/arch/jmx.adoc b/documentation/jetty/modules/programming-guide/pages/arch/jmx.adoc index 32ed9944693f..f61b53c2a31f 100644 --- a/documentation/jetty/modules/programming-guide/pages/arch/jmx.adoc +++ b/documentation/jetty/modules/programming-guide/pages/arch/jmx.adoc @@ -33,7 +33,7 @@ The Maven coordinates for the Jetty JMX support are: org.eclipse.jetty jetty-jmx - {version} + {jetty-version} ---- diff --git a/documentation/jetty/modules/programming-guide/pages/client/http.adoc b/documentation/jetty/modules/programming-guide/pages/client/http.adoc index 216ef408245c..fc889d5d7c2b 100644 --- a/documentation/jetty/modules/programming-guide/pages/client/http.adoc +++ b/documentation/jetty/modules/programming-guide/pages/client/http.adoc @@ -53,7 +53,7 @@ The Maven artifact coordinates are the following: org.eclipse.jetty jetty-client - {version} + {jetty-version} ---- diff --git a/documentation/jetty/modules/programming-guide/pages/client/http2.adoc b/documentation/jetty/modules/programming-guide/pages/client/http2.adoc index f0ce0f3412e0..49b7e2b61eb2 100644 --- a/documentation/jetty/modules/programming-guide/pages/client/http2.adoc +++ b/documentation/jetty/modules/programming-guide/pages/client/http2.adoc @@ -31,7 +31,7 @@ The Maven artifact coordinates for the HTTP/2 client library are the following: org.eclipse.jetty.http2 http2-client - {version} + {jetty-version} ---- diff --git a/documentation/jetty/modules/programming-guide/pages/client/http3.adoc b/documentation/jetty/modules/programming-guide/pages/client/http3.adoc index 238beaff43d4..81fc8936045b 100644 --- a/documentation/jetty/modules/programming-guide/pages/client/http3.adoc +++ b/documentation/jetty/modules/programming-guide/pages/client/http3.adoc @@ -31,7 +31,7 @@ The Maven artifact coordinates for the HTTP/3 client library are the following: org.eclipse.jetty.http3 http3-client - {version} + {jetty-version} ---- diff --git a/documentation/jetty/modules/programming-guide/pages/client/websocket.adoc b/documentation/jetty/modules/programming-guide/pages/client/websocket.adoc index d0a611b161ed..54fd4856704b 100644 --- a/documentation/jetty/modules/programming-guide/pages/client/websocket.adoc +++ b/documentation/jetty/modules/programming-guide/pages/client/websocket.adoc @@ -27,7 +27,7 @@ The Maven artifact coordinates are the following: org.eclipse.jetty.websocket websocket-jetty-client - {version} + {jetty-version} ---- diff --git a/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-jspc-maven-plugin.adoc b/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-jspc-maven-plugin.adoc index 47abc0025c3e..368666e4a163 100644 --- a/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-jspc-maven-plugin.adoc +++ b/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-jspc-maven-plugin.adoc @@ -25,7 +25,7 @@ Here's the basic setup required to put the jspc plugin into your build: org.eclipse.jetty jetty-jspc-maven-plugin - {VERSION} + {jetty-version} jspc @@ -152,7 +152,7 @@ For example, the following profile will only be invoked if the flag `-Dprod` is org.eclipse.jetty jetty-jspc-maven-plugin - {VERSION} + {jetty-version} @@ -226,7 +226,7 @@ Using the default settings, the `web.xml` merged with the jsp servlet definition org.eclipse.jetty jetty-jspc-maven-plugin - {VERSION} + {jetty-version} jspc diff --git a/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-maven-helloworld.adoc b/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-maven-helloworld.adoc index 5f9ccc11060a..96ffbe53c330 100644 --- a/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-maven-helloworld.adoc +++ b/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-maven-helloworld.adoc @@ -105,7 +105,7 @@ Use an editor to create the file `pom.xml` in the `JettyMavenHelloWorld` directo - {VERSION} + {jetty-version} @@ -257,7 +257,7 @@ Use an editor to create the file `pom.xml` with the following contents in the `J Jetty HelloWorld WebApp - {VERSION} + {jetty-version} diff --git a/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-maven-plugin.adoc b/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-maven-plugin.adoc index 4073432f7766..cf4665b18152 100644 --- a/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-maven-plugin.adoc +++ b/documentation/jetty/modules/programming-guide/pages/maven-jetty/jetty-maven-plugin.adoc @@ -63,7 +63,7 @@ First, add `jetty-maven-plugin` to your `pom.xml` definition: org.eclipse.jetty jetty-maven-plugin - {VERSION} + {jetty-version} ---- @@ -324,7 +324,7 @@ Here is an example, which turns on scanning for changes every ten seconds, and s org.eclipse.jetty jetty-maven-plugin - {VERSION} + {jetty-version} 10 @@ -422,7 +422,7 @@ Here's an example of a pom configuration for the plugin with the `run` goal: org.eclipse.jetty jetty-maven-plugin - {VERSION} + {jetty-version} / @@ -533,7 +533,7 @@ Here's an example of using the `pre-integration-test` and `post-integration-test org.eclipse.jetty jetty-maven-plugin - {VERSION} + {jetty-version} foo 9999 @@ -725,7 +725,7 @@ Here's a configuration example: org.eclipse.jetty jetty-maven-plugin - {VERSION} + {jetty-version} 9966 foo @@ -863,7 +863,7 @@ They are configured for the http://maven.apache.org/plugins/maven-war-plugin/ove org.apache.maven.plugins maven-war-plugin - {VERSION} + {jetty-version} @@ -954,7 +954,7 @@ Here's an example of setting up the HashLoginService for a webapp: org.eclipse.jetty jetty-maven-plugin - {VERSION} + {jetty-version} 10 @@ -1009,7 +1009,7 @@ Putting the configuration in webapp A's `pom.xml`: org.eclipse.jetty jetty-maven-plugin - {VERSION} + {jetty-version} 10 @@ -1067,7 +1067,7 @@ Then configure the location of this `jetty.xml` file into webapp A's jetty plugi org.eclipse.jetty jetty-maven-plugin - {VERSION} + {jetty-version} 10 diff --git a/documentation/jetty/modules/programming-guide/pages/server/http.adoc b/documentation/jetty/modules/programming-guide/pages/server/http.adoc index 33e90997e358..5a4bcd6ab16a 100644 --- a/documentation/jetty/modules/programming-guide/pages/server/http.adoc +++ b/documentation/jetty/modules/programming-guide/pages/server/http.adoc @@ -26,7 +26,7 @@ The Maven artifact coordinates are: org.eclipse.jetty jetty-server - {version} + {jetty-version} ---- @@ -385,7 +385,7 @@ A faster alternative, implemented natively, is Google's https://github.com/googl CAUTION: As Conscrypt eventually binds to a native library, there is a higher risk that a bug in Conscrypt or in the native library causes a JVM crash, while the Java implementation will not cause a JVM crash. -To use Conscrypt as TLS provider, you must have the Conscrypt jar and the Jetty dependency `jetty-alpn-conscrypt-server-{version}.jar` in the class-path or module-path. +To use Conscrypt as TLS provider, you must have the Conscrypt jar and the Jetty dependency `jetty-alpn-conscrypt-server-{jetty-version}.jar` in the class-path or module-path. Then, you must configure the JDK with the Conscrypt provider, and configure Jetty to use the Conscrypt provider, in this way: @@ -657,7 +657,7 @@ The Maven artifact coordinates are: org.eclipse.jetty jetty-rewrite - {version} + {jetty-version} ---- @@ -785,7 +785,7 @@ The Maven artifact coordinates are: org.eclipse.jetty jetty-servlet - {version} + {jetty-version} ---- diff --git a/documentation/jetty/modules/programming-guide/pages/server/http2.adoc b/documentation/jetty/modules/programming-guide/pages/server/http2.adoc index 65b58c8a09be..53ed870860cb 100644 --- a/documentation/jetty/modules/programming-guide/pages/server/http2.adoc +++ b/documentation/jetty/modules/programming-guide/pages/server/http2.adoc @@ -29,7 +29,7 @@ The Maven artifact coordinates for the HTTP/2 client library are the following: org.eclipse.jetty.http2 http2-server - {version} + {jetty-version} ---- diff --git a/documentation/jetty/modules/programming-guide/pages/server/http3.adoc b/documentation/jetty/modules/programming-guide/pages/server/http3.adoc index 0ae3db02fdbc..8150edfb96a7 100644 --- a/documentation/jetty/modules/programming-guide/pages/server/http3.adoc +++ b/documentation/jetty/modules/programming-guide/pages/server/http3.adoc @@ -29,7 +29,7 @@ The Maven artifact coordinates for the HTTP/3 client library are the following: org.eclipse.jetty.http3 http3-server - {version} + {jetty-version} ---- diff --git a/documentation/jetty/modules/programming-guide/pages/server/websocket.adoc b/documentation/jetty/modules/programming-guide/pages/server/websocket.adoc index 385410a35403..462bb03f0fef 100644 --- a/documentation/jetty/modules/programming-guide/pages/server/websocket.adoc +++ b/documentation/jetty/modules/programming-guide/pages/server/websocket.adoc @@ -75,7 +75,7 @@ Jetty's implementation of the standard `javax.websocket` APIs is provided by the org.eclipse.jetty.websocket websocket-javax-server - {version} + {jetty-version} ---- @@ -176,7 +176,7 @@ Jetty's WebSocket APIs are provided by the following Maven artifact: org.eclipse.jetty.websocket websocket-jetty-api - {version} + {jetty-version} ---- @@ -187,7 +187,7 @@ Jetty's implementation of the Jetty WebSocket APIs is provided by the following org.eclipse.jetty.websocket websocket-jetty-server - {version} + {jetty-version} ---- diff --git a/documentation/jetty/pom.xml b/documentation/jetty/pom.xml index 00ac83279a15..08ddf224874f 100644 --- a/documentation/jetty/pom.xml +++ b/documentation/jetty/pom.xml @@ -26,6 +26,7 @@ + jetty/jetty.website diff --git a/pom.xml b/pom.xml index 8351d9161f1a..3f2e62cc40ca 100644 --- a/pom.xml +++ b/pom.xml @@ -198,9 +198,6 @@ 1.11.3 4.5.14 4.4.16 - 2.2.6 - 2.3.1 - 2.5.13 9.7 4.2.1 6.4.1 @@ -718,16 +715,6 @@ - - org.asciidoctor - asciidoctor-maven-plugin - ${asciidoctor.maven.plugin.version} - - - org.asciidoctor - asciidoctorj - ${asciidoctorj.version} - org.awaitility awaitility @@ -1757,49 +1744,6 @@ depends-maven-plugin ${depends.maven.plugin.version} - - org.asciidoctor - asciidoctor-maven-plugin - ${asciidoctor.maven.plugin.version} - - html5 - - asciidoctor-diagram - - - https://eclipse.dev/jetty/javadoc/jetty-10 - ${basedir}/.. - https://github.com/jetty/jetty.project/tree/jetty-10.0.x - https://github.com/jetty/jetty.project/tree/jetty-10.0.x/documentation/jetty-documentation/src/main/asciidoc - http://central.maven.org/maven2 - ${project.version} - ${maven.build.timestamp} - left - font - - - - - org.asciidoctor - asciidoctorj-diagram - ${asciidoctorj-diagram.version} - - - - - index - - process-asciidoc - - generate-resources - - src/main/asciidoc - index.adoc - ${project.build.directory}/html - - - - org.codehaus.mojo build-helper-maven-plugin