Camel Components

Jetty

Since Camel 1.2

Only consumer is supported

The Jetty component provides HTTP-based endpoints for consuming and producing HTTP requests. That is, the Jetty component behaves as a simple Web server.

Stream

Jetty is stream-based, which means the input it receives is submitted to Camel as a stream. By default the consumer copies the request body into a stream cache, which can be read more than once. With disableStreamCache=true the body is the raw request stream, and you will only be able to read the content of the stream once. If you find a situation where the message body appears to be empty, or you need to access the body multiple times (e.g.: doing multicasting, or redelivery error handling), you should use Stream caching or convert the message body to a String which is safe to be re-read multiple times.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-jetty</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI format

jetty:http://hostname[:port][/resourceUri][?options]

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Jetty component supports the following options which are listed below.

Name Description Default Type

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

continuationTimeout (consumer)

The timeout in milliseconds of the asynchronous processing of a request (Servlet AsyncContext timeout), for the endpoints that do not set continuationTimeout. When it expires, the client gets a 504 Gateway Timeout response (with the default errorHandler) and the result of the route is discarded. 0 or a negative value means no timeout. Only used when useContinuation is enabled.

30000

Long

enableJmx (consumer)

Whether to register the Jetty servers as MBeans (Jetty JMX) in the MBeanServer of the CamelContext, which needs JMX to be enabled in the CamelContext. This is the default for the endpoints that do not set enableJmx.

false

boolean

maxThreads (consumer)

The maximum number of threads of the Jetty QueuedThreadPool that the component creates for each Jetty server (one per port). When only one of minThreads and maxThreads is set, the other keeps the Jetty default (8 and 200). Cannot be combined with threadPool.

Integer

minThreads (consumer)

The minimum number of threads of the Jetty QueuedThreadPool that the component creates for each Jetty server (one per port). When only one of minThreads and maxThreads is set, the other keeps the Jetty default (8 and 200). Cannot be combined with threadPool.

Integer

muteException (consumer)

Whether to keep the exception out of the response when an exchange fails on a consumer: the response is the 500 status code with an empty body. It is the default of the muteException option of the endpoints.

true

boolean

requestBufferSize (consumer)

The size in bytes of the request buffer of the connectors. Note that the jetty component does not apply it to the connectors.

Integer

requestHeaderSize (consumer)

The maximum size in bytes of the request line and headers of a request on the connectors that the component creates (the requestHeaderSize of the Jetty HttpConfiguration, 8192 by default). Jetty rejects a request with larger headers.

Integer

responseBufferSize (consumer)

The size in bytes of the response output buffer of the connectors that the component creates (the outputBufferSize of the Jetty HttpConfiguration, 32768 by default).

Integer

responseHeaderSize (consumer)

The maximum size in bytes of the response headers on the connectors that the component creates (the responseHeaderSize of the Jetty HttpConfiguration, 8192 by default).

Integer

sendServerVersion (consumer)

Whether the Jetty server sends the Server response header with the Jetty version. This is the default for the endpoints that do not set sendServerVersion. It is set on the connector of a port, so the endpoint that creates the connector decides it for all the endpoints on that port.

true

boolean

useContinuation (consumer)

Whether to process the requests asynchronously (Servlet async, known as Jetty continuations), so that a request that waits for an asynchronous route does not block a Jetty thread. This is the default for the endpoints that do not set useContinuation.

true

boolean

useXForwardedForHeader (consumer)

Whether to add the Jetty ForwardedRequestCustomizer to the connectors that the component creates, so that a request takes its client address, scheme, host and port from the Forwarded and X-Forwarded-* headers (for example X-Forwarded-For becomes HttpServletRequest.getRemoteAddr). Enable it only behind a trusted proxy, as any client can send these headers.

false

boolean

fileSizeThreshold (consumer (advanced))

The size in bytes above which a part of a multipart/form-data request is written to a file in filesLocation instead of kept in memory, for the endpoints that do not set fileSizeThreshold. With the default 0 every part is written to a file.

0

int

filesLocation (consumer (advanced))

The directory where the parts of multipart/form-data requests are written to, for the endpoints that do not set filesLocation. By default the temporary directory of the JVM (java.io.tmpdir).

String

maxFileSize (consumer (advanced))

The maximum size in bytes of one part (such as an uploaded file) of a multipart/form-data request, for the endpoints that do not set maxFileSize. -1 means no limit.

-1

long

maxRequestSize (consumer (advanced))

The maximum size in bytes of a multipart/form-data request, for the endpoints that do not set maxRequestSize. -1 means no limit.

-1

long

threadPool (consumer (advanced))

A custom Jetty ThreadPool for the Jetty servers that the component creates; the same instance is used for every server (port). Cannot be combined with minThreads or maxThreads.

ThreadPool

allowJavaSerializedObject (advanced)

Whether to allow Java serialization of a message body with Content-Type application/x-java-serialized-object: a consumer deserializes such a request body and can write a Java object as such a response, and the HTTP producer deserializes such a response body. When not allowed, such a body that is received is dropped (null). This is turned off by default: if you enable it, be aware that Java deserializes the data that the other side sends, which can be a security risk.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

errorHandler (advanced)

A custom Jetty ErrorHandler for the Jetty servers that the component creates, which writes the error responses that Jetty generates itself (for example 404 or a timeout). By default Camel uses an ErrorHandler that sends no exception details and answers 504 Gateway Timeout when the continuationTimeout expires.

ErrorHandler

httpBinding (advanced)

Not supported on the jetty component: setting it fails with an IllegalArgumentException. Set httpBinding on the endpoint instead.

HttpBinding

httpConfiguration (advanced)

Not supported: the jetty component does not use the shared HttpConfiguration, and setting it fails with an IllegalArgumentException.

HttpConfiguration

mbContainer (advanced)

A custom Jetty MBeanContainer to register the MBeans of the Jetty servers with, when enableJmx is enabled. By default the component creates one for the MBeanServer of the CamelContext.

MBeanContainer

requestLog (advanced)

A Jetty RequestLog (for example a CustomRequestLog) that logs the requests of the Jetty servers that the component creates.

RequestLog

secureRequestCustomizer (advanced)

A custom Jetty SecureRequestCustomizer for the TLS connectors that the component creates, for example to configure the SNI host check or HSTS. By default a SecureRequestCustomizer with the Jetty defaults is used.

SecureRequestCustomizer

headerFilterStrategy (filter)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message.

HeaderFilterStrategy

proxyHost (proxy)

The hostname of an HTTP proxy, copied to the endpoints. Note that the jetty endpoints only consume, so they do not use a proxy.

String

proxyPort (proxy)

The port number of an HTTP proxy, copied to the endpoints together with proxyHost. Note that the jetty endpoints only consume, so they do not use a proxy.

Integer

deserializationFilter (security)

Sets an ObjectInputFilter pattern (jdk.serialFilter syntax) applied when deserializing Java objects from requests or responses with Content-Type application/x-java-serialized-object (only used when allowJavaSerializedObject or transferException is enabled). When not set, the JVM-wide jdk.serialFilter is used if present; otherwise a default filter is applied that rejects java.net., allows java., javax.* and org.apache.camel.*, and rejects every other class.

String

keystore (security)

The path or URL of the keystore file (PKCS12 by default) that holds the X.509 certificate and private key of the Jetty server. Only used for https endpoints without SSLContextParameters; the JVM system property org.eclipse.jetty.ssl.keystore takes precedence.

String

socketConnectorProperties (security)

Properties for the http connectors that the component creates. Note that the jetty component does not apply them to the connectors.

Map

socketConnectors (security)

A map of port number to a Jetty ServerConnector, used for the http endpoints on that port instead of a connector that the component creates. The other connector options (header and buffer sizes, sendServerVersion and so on) are not applied to such a connector.

Map

sslContextParameters (security)

The SSL/TLS configuration (SSLContextParameters) for the endpoints that do not set sslContextParameters. When set, the keystore, sslPassword and sslKeyPassword options are not used.

SSLContextParameters

sslKeyPassword (security)

The password of the private key entry in the keystore (the -keypass of keytool), set as the key manager password of the Jetty SslContextFactory. When not set, Jetty uses the keystore password (sslPassword). Only used for https endpoints without SSLContextParameters; the JVM system property org.eclipse.jetty.ssl.keypassword takes precedence.

String

sslPassword (security)

The password of the keystore file (the -storepass of keytool), set as the keystore password of the Jetty SslContextFactory. Only used for https endpoints without SSLContextParameters; the JVM system property org.eclipse.jetty.ssl.password takes precedence.

String

sslSocketConnectorProperties (security)

Properties to set on the Jetty SslContextFactory.Server of the https connectors that the component creates, for example needClientAuth or excludeProtocols. A property that does not exist fails the creation of the connector.

Map

sslSocketConnectors (security)

A map of port number to a Jetty ServerConnector, used for the https endpoints on that port instead of a connector that the component creates. The other connector options (TLS, header and buffer sizes, sendServerVersion and so on) are not applied to such a connector.

Map

useGlobalSslContextParameters (security)

Whether to use the global SSLContextParameters of the CamelContext, when neither the endpoint nor the component sets sslContextParameters.

false

boolean

Endpoint Options

The Jetty endpoint is configured using URI syntax:

jetty:httpUri

With the following path and query parameters:

Path Parameters

Name Description Default Type

httpUri (common)

Required The URL of the HTTP endpoint: the URL to call for a producer, or the URL (host, port and path) to listen on for a consumer.

URI

Query Parameters

Name Description Default Type

headerFilterStrategy (common (advanced))

To use a custom HeaderFilterStrategy to filter the headers that are mapped between the Camel message and the HTTP request and response.

HeaderFilterStrategy

httpBinding (common (advanced))

To use a custom HttpBinding that reads the HTTP servlet request into the Camel message and writes the Camel message to the HTTP servlet response. The options muteException, logException, transferException, eagerCheckContentAvailable and mapHttpMessage* of the endpoint only configure the binding that Camel creates, not a custom one.

HttpBinding

chunked (consumer)

If false, the consumer writes the response with a Content-Length header, which buffers the whole body first, instead of streaming it with chunked transfer encoding. The CamelHttpChunked message header overrides this option.

true

boolean

disableStreamCache (common)

Whether to turn off the caching of the raw HTTP stream. By default the consumer (camel-servlet, camel-jetty) copies the request body into a stream cache, so it can be read more than once, and the producer (camel-http) does the same with the response body. When true, the message body is the raw input stream, which can only be read once: use it to stream a large payload directly to a file or another store, or in a proxy route that does not read the body. The producer then closes the response stream when the exchange completes.

false

boolean

transferException (common)

If enabled and an exchange fails on the consumer, the consumer sends the exception back in the response as a Java serialized object, with Content-Type application/x-java-serialized-object, instead of its stack trace as text. It has no effect while muteException is enabled (the default). The exception must be serializable. It also makes the consumer deserialize a request body of that content type. This is turned off by default: if you enable it, be aware that Java deserializes the data that the client sends, which can be a security risk.

false

boolean

async (consumer)

Whether the consumer uses the Servlet asynchronous support: the request is put in asynchronous mode (AsyncContext), the route runs on another thread of the container, and the response is written when the exchange completes. Only camel-jetty uses this option; camel-servlet takes it from the async init parameter of the CamelHttpTransportServlet.

false

boolean

continuationTimeout (consumer)

The timeout in milliseconds of the asynchronous processing of a request (Servlet AsyncContext timeout). When it expires, the client gets a 504 Gateway Timeout response (with the default errorHandler of the component) and the result of the route is discarded. 0 or a negative value means no timeout. When not set, the continuationTimeout of the component is used. Only used when useContinuation is enabled.

30000

Long

enableCORS (consumer)

Whether to add the Jetty CrossOriginFilter to the endpoint, which answers CORS requests. Configure it (allowedOrigins, allowedMethods, allowedHeaders and so on) with the filter init parameters; Camel sets allowCredentials to false unless it is configured.

false

boolean

enableJmx (consumer)

Whether to register the Jetty server of the port as MBeans (Jetty JMX) in the MBeanServer of the CamelContext, which needs JMX to be enabled in the CamelContext. Only the endpoint that creates the server of a port decides it.

false

boolean

enableMultipartFilter (consumer)

Whether to add the Camel MultiPartFilter to the endpoint path, which parses multipart/form-data requests so that their parts become attachments of the message. The component enables it unless the endpoint sets it to false. Set it to false when bridging endpoints, so that the multipart request is proxied as it is.

false

boolean

httpMethodRestrict (consumer)

Comma-separated list of the HTTP methods that the consumer accepts, such as GET,POST. A request with another method gets the 405 Method Not Allowed response.

String

logException (consumer)

Whether to log the exception, with its stack trace at ERROR level, when an exchange fails on the consumer and muteException keeps it out of the response.

false

boolean

matchOnUriPrefix (consumer)

Whether the consumer also serves the requests to paths below its own path (its path used as a URI prefix), when no consumer matches the request path exactly.

false

boolean

muteException (consumer)

Whether to keep the exception out of the response when an exchange fails on the consumer: the response is the 500 status code with an empty body. When false, the response body is the stack trace of the exception as text (or the serialized exception with transferException).

true

boolean

responseBufferSize (consumer)

The buffer size, in bytes, of the HTTP servlet response (ServletResponse.setBufferSize), which is also the size of the buffer used to copy the response body. When not set, the default of the servlet container is used.

Integer

sendDateHeader (consumer)

Whether the Jetty server sends the Date response header. Camel turns it off unless this option is true. It is set on the connector of the port, so the endpoint that creates the connector decides it for all the endpoints on that port.

false

boolean

sendServerVersion (consumer)

Whether the Jetty server sends the Server response header with the Jetty version. It is set on the connector of the port, so the endpoint that creates the connector decides it for all the endpoints on that port.

true

boolean

sessionSupport (consumer)

Whether to enable HTTP sessions, by adding a Jetty SessionHandler to the servlet context of the port. The sessions are then enabled for all the jetty endpoints on that port, and a running Jetty server is restarted to add it.

false

boolean

useContinuation (consumer)

Whether to process the requests asynchronously (Servlet async, known as Jetty continuations), so that a request that waits for an asynchronous route does not block a Jetty thread. When not set, the useContinuation of the component is used (true by default).

Boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

eagerCheckContentAvailable (consumer (advanced))

Whether to check that the request input stream has data available when the request has no Content-Length header; the message body is null when no data is available right away. Turn it on for HTTP clients that do not stream the body. A request with Content-Length 0 always has a null body.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

fileSizeThreshold (consumer (advanced))

The size in bytes above which a part of a multipart/form-data request is written to a file in filesLocation instead of kept in memory. When not set, the fileSizeThreshold of the component is used (0: every part is written to a file). Only the endpoint that creates the server of a port decides it.

Integer

filesLocation (consumer (advanced))

The directory where the parts of multipart/form-data requests are written to. When not set, the filesLocation of the component is used, by default the temporary directory of the JVM. Only the endpoint that creates the server of a port decides it.

String

filterInitParameters (consumer (advanced))

The init parameters of the filters of the endpoint (filters, and the CrossOriginFilter of enableCORS), given to each filter when it is added. This is a multi-value option with prefix: filter.

Map

filters (consumer (advanced))

Servlet Filter beans from the registry, comma-separated, to add in front of the endpoint path (and the paths below it with matchOnUriPrefix). Each filter gets the filter init parameters.

List

handlers (consumer (advanced))

Jetty Handler beans from the registry, comma-separated, to add to the Jetty server of the port (for example a SecurityHandler): a Handler.Wrapper wraps the existing handlers, another handler is added next to them. The handlers belong to the port, so all the jetty endpoints on that port share them; use another port for other handlers.

List

idleTimeout (consumer (advanced))

The idle timeout in milliseconds of an HTTP request for I/O operations (the idleTimeout of the Jetty HttpConfiguration). 0 means no timeout; -1 keeps the idle timeout of the connector (30 seconds by default). It is set on the connector of the port, so the endpoint that creates the connector decides it for all the endpoints on that port.

-1

long

mapHttpMessageBody (consumer (advanced))

If this option is true then the HTTP request body is mapped to the IN message body. If this option is false then the request body is not read and the message body is null, and no attachments, Java serialized objects or form fields are mapped.

true

boolean

mapHttpMessageFormUrlEncodedBody (consumer (advanced))

Whether to map the fields of a POST request with an application/x-www-form-urlencoded body to Camel message headers. It only applies when mapHttpMessageBody and mapHttpMessageHeaders are true too.

true

boolean

mapHttpMessageHeaders (consumer (advanced))

Whether to map the HTTP request headers and the request parameters (such as the query parameters) to Camel message headers, filtered by the headerFilterStrategy. When false, only the CamelHttp* headers (method, URI, URL, path and query) and Content-Type are set.

true

boolean

maxFileSize (consumer (advanced))

The maximum size in bytes of one part (such as an uploaded file) of a multipart/form-data request; -1 means no limit. When not set, the maxFileSize of the component is used. Only the endpoint that creates the server of a port decides it.

Long

maxRequestSize (consumer (advanced))

The maximum size in bytes of a multipart/form-data request; -1 means no limit. When not set, the maxRequestSize of the component is used. Only the endpoint that creates the server of a port decides it.

Long

multipartFilter (consumer (advanced))

A custom servlet Filter to use instead of the Camel MultiPartFilter for multipart/form-data requests. Setting it also enables enableMultipartFilter.

Filter

optionsEnabled (consumer (advanced))

Whether the consumer routes HTTP OPTIONS requests. When false, the consumer answers an OPTIONS request itself, with status 200 and an Allow header that lists the HTTP methods it accepts.

false

boolean

traceEnabled (consumer (advanced))

Whether the consumer accepts HTTP TRACE requests and routes them. When false, a TRACE request gets the 405 Method Not Allowed response.

false

boolean

oauthProfile (security)

OAuth profile name for validating incoming Authorization: Bearer tokens. When set, the request is authenticated before the route is processed. This requires an OAuthTokenValidationFactory; camel-oauth provides the default implementation. This is Camel endpoint-level validation and does not replace Jetty handlers or container security.

String

sslContextParameters (security)

The SSL/TLS configuration (SSLContextParameters) of the connector that this endpoint creates for its port. When not set, the sslContextParameters of the component is used, or the global ones with useGlobalSslContextParameters.

SSLContextParameters

Message Headers

The Jetty component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelServletContextPath (consumer)

Constant: SERVLET_CONTEXT_PATH

The path of the endpoint that received the request, for example /myapp for jetty:http://0.0.0.0:8080/myapp.

String

CamelHttpPath (consumer)

Constant: HTTP_PATH

The path of the request without the path of the endpoint (CamelServletContextPath), as received (not URL-decoded), for example /orders/1 for a request to /myapp/orders/1 on the endpoint jetty:http://0.0.0.0:8080/myapp?matchOnUriPrefix=true.

String

Message Body

The message body at each side of the Jetty component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

stream or null

The request body as a stream cache, which can be read again (the raw stream, read once, with disableStreamCache); an empty one for a GET, null with Content-Length 0 or eagerCheckContentAvailable. The fields of a form are also headers; a multipart upload leaves the body empty and gives its files as attachments and DataHandler headers.

Not known when transferException or httpBinding is set.

Consumer reply

null, text, bytes, stream or file

The response body: text, bytes, a stream or a file. A Map, a List or a POJO is sent as an empty body (as its toString with chunked=false): marshal it first.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

OAuth Bearer token validation

Jetty consumers can validate incoming Authorization: Bearer tokens by setting the oauthProfile endpoint option. The profile is resolved through Camel’s OAuthTokenValidationFactory SPI. The camel-oauth component provides the default implementation for standalone Camel applications; see its documentation for validation profile options and production hardening (expected issuer and audience, HTTPS for JWKS, OIDC discovery, and introspection endpoints). Runtimes can also provide their own implementation.

If oauthProfile is set but no OAuthTokenValidationFactory is available, the route fails to start. Add camel-oauth for the default provider or include a runtime-specific provider from the platform integration.

  • Java

  • XML

  • YAML

from("jetty:http://0.0.0.0:8080/secure?oauthProfile=myprofile")
    .to("direct:businessLogic");
<route>
  <from uri="jetty:http://0.0.0.0:8080/secure?oauthProfile=myprofile"/>
  <to uri="direct:businessLogic"/>
</route>
- route:
    from:
      uri: jetty:http://0.0.0.0:8080/secure
      parameters:
        oauthProfile: myprofile
      steps:
        - to:
            uri: direct:businessLogic

When oauthProfile is set, static profile configuration is resolved and validated at route startup. Updates to OAuth profile properties require restarting the route or Camel context before they take effect. Requests without a Bearer token or with an invalid token are rejected with HTTP 401 before the route is processed; missing credentials receive a WWW-Authenticate: Bearer response header and invalid tokens receive WWW-Authenticate: Bearer error="invalid_token". Malformed Authorization headers are rejected with HTTP 400 and WWW-Authenticate: Bearer error="invalid_request". Token validation infrastructure failures are rejected with HTTP 503. For valid tokens, the token validation result is stored on the exchange as the CamelOAuthTokenValidationResult exchange property. The raw Authorization header is removed from the Camel message before the route is invoked.

Automatic OPTIONS handling runs before OAuth validation when optionsEnabled=false, so unauthenticated CORS preflight and Allow requests keep the existing Jetty behavior. If an OPTIONS route is explicitly enabled, that route is protected by OAuth like other methods.

This is Camel endpoint-level validation and does not replace Jetty handlers or other container security mechanisms. If route code accesses the native servlet request object directly, the container request still reflects the original inbound HTTP headers. When combining OAuth validation with custom Jetty handlers or container-managed security, see the Jetty handlers and security configuration section below.

Message Headers

Camel uses the same message headers as the HTTP component. It also uses a header (Exchange.HTTP_CHUNKED, CamelHttpChunked) to turn on or turn off the chunked encoding on the camel-jetty consumer.

Camel also populates all request.parameter and request.headers. For example, given a client request with the URL, http://myserver/myserver?orderid=123, the exchange will contain a header named orderid with the value 123.

You can get the request.parameter from the message header not only from Get Method, but also other HTTP methods.

Usage

The Jetty component supports consumer endpoints.

Consumer

In this sample we define a route that exposes an HTTP service at http://localhost:8080/myapp/myservice:

Usage of localhost

When you specify localhost in a URL, Camel exposes the endpoint only on the local TCP/IP network interface, so it cannot be accessed from outside the machine it operates on.

If you need to expose a Jetty endpoint on a specific network interface, the numerical IP address of this interface should be used as the host. If you need to expose a Jetty endpoint on all network interfaces, the 0.0.0.0 address should be used.

To listen across an entire URI prefix, see below.

How do I let Jetty match wildcards?

By default, Jetty will only match on exact uri’s. But you can instruct Jetty to match prefixes. For example:

  • Java

  • XML

  • YAML

from("jetty://0.0.0.0:8123/foo").to("mock:foo");
<route>
  <from uri="jetty:http://0.0.0.0:8123/foo"/>
  <to uri="mock:foo"/>
</route>
- route:
    from:
      uri: jetty:http://0.0.0.0:8123/foo
      steps:
        - to:
            uri: mock:foo

In the route above Jetty will only match if the uri is an exact match, so it will match if you enter http://0.0.0.0:8123/foo but not match if you do http://0.0.0.0:8123/foo/bar.

So if you want to enable wildcard matching you need to set matchOnUriPrefix=true as follows:

  • Java

  • XML

  • YAML

from("jetty://0.0.0.0:8123/foo?matchOnUriPrefix=true").to("mock:foo");
<route>
  <from uri="jetty:http://0.0.0.0:8123/foo?matchOnUriPrefix=true"/>
  <to uri="mock:foo"/>
</route>
- route:
    from:
      uri: jetty:http://0.0.0.0:8123/foo
      parameters:
        matchOnUriPrefix: true
      steps:
        - to:
            uri: mock:foo

So now Jetty matches any endpoints with starts with foo.

To match any endpoint you can remove the prefix so it will match anything from the root:

  • Java

  • XML

  • YAML

from("jetty://0.0.0.0:8123?matchOnUriPrefix=true").to("mock:foo");
<route>
  <from uri="jetty:http://0.0.0.0:8123?matchOnUriPrefix=true"/>
  <to uri="mock:foo"/>
</route>
- route:
    from:
      uri: jetty:http://0.0.0.0:8123
      parameters:
        matchOnUriPrefix: true
      steps:
        - to:
            uri: mock:foo

Servlets

If you actually want to expose routes by HTTP and already have a Servlet, you should instead refer to the Servlet Transport.

HTTP Request Parameters

So if a client sends the HTTP request, http://serverUri?one=hello, the Jetty component will copy the HTTP request parameter, one to the exchange’s in.header. We can then use the simple language to route exchanges that contain this header to a specific endpoint and all others to another. If we used a language more powerful than Simple, we could also test for the parameter value and do routing based on the header value as well.

Session Support

The session support option, sessionSupport, can be used to enable a HttpSession object and access the session object while processing the exchange. For example, the following route enables sessions:

  • Java

  • XML

  • YAML

from("jetty:http://0.0.0.0/myapp/myservice/?sessionSupport=true")
    .process("myCode");
<route>
    <from uri="jetty:http://0.0.0.0/myapp/myservice/?sessionSupport=true"/>
    <process ref="myCode"/>
</route>
- route:
    from:
      uri: jetty:http://0.0.0.0/myapp/myservice/
      parameters:
        sessionSupport: true
      steps:
        - process:
            ref: myCode

The myCode Processor can be instantiated by a Spring bean element:

XML-only: Spring bean definition for Processor
<bean id="myCode" class="com.mycompany.MyCodeProcessor"/>

Where the processor implementation can access the HttpSession as follows:

Java-only: inline Processor accessing HttpSession
public void process(Exchange exchange) throws Exception {
    HttpSession session = exchange.getIn(HttpMessage.class).getRequest().getSession();
    ...
}

SSL Support (HTTPS)

Using the JSSE Configuration Utility

The Jetty component supports SSL/TLS configuration through the Camel JSSE Configuration Utility. This utility greatly decreases the amount of component-specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Jetty component.

Programmatic configuration of the component

Java-only: programmatic SSL configuration with KeyStore and SSLContext parameters
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("/users/home/server/keystore.jks");
ksp.setPassword("keystorePassword");

KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyStore(ksp);
kmp.setKeyPassword("keyPassword");

SSLContextParameters scp = new SSLContextParameters();
scp.setKeyManagers(kmp);

JettyComponent jettyComponent = getContext().getComponent("jetty", JettyComponent.class);
jettyComponent.setSslContextParameters(scp);

Spring DSL based configuration of endpoint

XML-only: Spring XML configuration for SSL context parameters
  <camel:sslContextParameters
      id="sslContextParameters">
    <camel:keyManagers
        keyPassword="keyPassword">
      <camel:keyStore
          resource="/users/home/server/keystore.jks"
          password="keystorePassword"/>
    </camel:keyManagers>
  </camel:sslContextParameters>

  <to uri="jetty:https://127.0.0.1/mail/?sslContextParameters=#sslContextParameters"/>

Configuring Jetty Directly

Jetty provides SSL support out of the box. To enable Jetty to run in SSL mode, format the URI with the \https:// prefix---for example:

  • Java

  • XML

  • YAML

from("jetty:https://0.0.0.0/myapp/myservice/");
<from uri="jetty:https://0.0.0.0/myapp/myservice/"/>
- from:
    uri: jetty:https://0.0.0.0/myapp/myservice/
    steps:
      - log:
          message: "${body}"

Jetty also needs to know where to load your keystore from and what passwords to use to load the correct SSL certificate. Set the following JVM System Properties:

  • org.eclipse.jetty.ssl.keystore specify the location of the Java keystore file, which contains the Jetty server’s own X.509 certificate in a key entry. A key entry stores the X.509 certificate (effectively, the public key) and also its associated private key.

  • org.eclipse.jetty.ssl.password the store password, which is required to access the keystore file (this is the same password that is supplied to the keystore command’s -storepass option).

  • org.eclipse.jetty.ssl.keypassword the key password, which is used to access the certificate’s key entry in the keystore (this is the same password that is supplied to the keystore command’s -keypass option).

For details of how to configure SSL on a Jetty endpoint, read the following documentation at the Jetty Site: http://docs.codehaus.org/display/JETTY/How+to+configure+SSL

Camel doesn’t expose some SSL properties directly, such as needClientAuth for mutual authentication requiring a client certificate or wantClientAuth for mutual authentication where a client doesn’t need a certificate but can have one.

Configuring general SSL properties

With the sslSocketConnectorProperties option you can set properties of the Jetty SslContextFactory.Server of all the https connectors that the component creates. The keys are the names of the properties of SslContextFactory.Server, and a property that does not exist fails the creation of the connector.

XML-only: Spring bean configuration for general Jetty SSL properties
<bean id="jetty" class="org.apache.camel.component.jetty12.JettyHttpComponent12">
    <property name="sslSocketConnectorProperties">
        <map>
            <entry key="keyStorePath" value="..."/>
            <entry key="keyStorePassword" value="..."/>
            <entry key="keyManagerPassword" value="..."/>
            <entry key="needClientAuth" value="true"/>
            <entry key="trustStorePath" value="..."/>
            <entry key="trustStorePassword" value="..."/>
        </map>
    </property>
</bean>

How to obtain reference to the X509Certificate

Jetty stores a reference to the certificate in the HttpServletRequest which you can access from code as follows:

Java-only: accessing X509Certificate from HttpServletRequest
HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class);
X509Certificate[] certs = (X509Certificate[]) req.getAttribute("jakarta.servlet.request.X509Certificate");

Obtaining X-Forwarded-For header with HttpServletRequest.getRemoteAddr()

If the HTTP requests are handled by an Apache server and forwarded to jetty with mod_proxy, the original client IP address is in the X-Forwarded-For header and the HttpServletRequest.getRemoteAddr() will return the address of the Apache proxy.

Set the useXForwardedForHeader option of the component to true to add the Jetty ForwardedRequestCustomizer to the connectors. The request then takes its client address, scheme, host and port from the Forwarded and X-Forwarded-* headers, so HttpServletRequest.getRemoteAddr() returns the address in the X-Forwarded-For header. Only enable it when Jetty is behind a trusted proxy, as any client can send these headers.

XML-only: Spring bean configuration for Jetty X-Forwarded-For support
<bean id="jetty" class="org.apache.camel.component.jetty12.JettyHttpComponent12">
    <property name="useXForwardedForHeader" value="true"/>
</bean>

This is particularly useful when an existing Apache server handles TLS connections for a domain and proxies them to application servers internally.

Default behavior for returning HTTP status codes

The default behavior of HTTP status codes is defined by the org.apache.camel.component.http.DefaultHttpBinding class, which handles how a response is written and also sets the HTTP status code.

If the exchange was processed successfully, the 200 HTTP status code is returned.
If the exchange failed with an exception, the 500 HTTP status code is returned. The stacktrace is returned in the body only when muteException is set to false. If you want to specify which HTTP status code to return, set the code in the Exchange.HTTP_RESPONSE_CODE header of the OUT message.

Customizing HttpBinding

By default, Camel uses the org.apache.camel.component.http.DefaultHttpBinding to handle how a response is written. If you like, you can customize this behavior either by implementing your own HttpBinding class or by extending DefaultHttpBinding and overriding the appropriate methods.

The following example shows how to customize the DefaultHttpBinding in order to change how exceptions are returned:

We can then create an instance of our binding and register it in the Spring registry as follows:

XML-only: Spring bean definition for custom HttpBinding
<bean id="mybinding" class="com.mycompany.MyHttpBinding"/>

And then we can reference this binding when we define the route:

  • Java

  • XML

  • YAML

from("jetty:http://0.0.0.0:8080/myapp/myservice?httpBinding=#mybinding")
    .to("bean:doSomething");
<route>
  <from uri="jetty:http://0.0.0.0:8080/myapp/myservice?httpBinding=#mybinding"/>
  <to uri="bean:doSomething"/>
</route>
- route:
    from:
      uri: jetty:http://0.0.0.0:8080/myapp/myservice
      parameters:
        httpBinding: "#mybinding"
      steps:
        - to:
            uri: bean:doSomething

Jetty handlers and security configuration

You can configure a list of Jetty handlers on the endpoint, which can be useful for enabling advanced Jetty security features. These handlers are configured in Spring XML as follows:

XML-only: Spring bean definitions for Jetty JAAS security handler
<bean id="userRealm" class="org.mortbay.jetty.plus.jaas.JAASUserRealm">
    <property name="name" value="tracker-users"/>
    <property name="loginModuleName" value="ldaploginmodule"/>
</bean>

<bean id="constraint" class="org.mortbay.jetty.security.Constraint">
    <property name="name" value="BASIC"/>
    <property name="roles" value="tracker-users"/>
    <property name="authenticate" value="true"/>
</bean>

<bean id="constraintMapping" class="org.mortbay.jetty.security.ConstraintMapping">
    <property name="constraint" ref="constraint"/>
    <property name="pathSpec" value="/*"/>
</bean>

<bean id="securityHandler" class="org.mortbay.jetty.security.SecurityHandler">
    <property name="userRealm" ref="userRealm"/>
    <property name="constraintMappings" ref="constraintMapping"/>
</bean>

You can configure a list of Jetty handlers as follows:

XML-only: Spring bean definitions for Jetty constraint-based security handler
<bean id="constraint" class="org.eclipse.jetty.http.security.Constraint">
    <property name="name" value="BASIC"/>
    <property name="roles" value="tracker-users"/>
    <property name="authenticate" value="true"/>
</bean>

<bean id="constraintMapping" class="org.eclipse.jetty.security.ConstraintMapping">
    <property name="constraint" ref="constraint"/>
    <property name="pathSpec" value="/*"/>
</bean>

<bean id="securityHandler" class="org.eclipse.jetty.security.ConstraintSecurityHandler">
    <property name="authenticator">
        <bean class="org.eclipse.jetty.security.authentication.BasicAuthenticator"/>
    </property>
    <property name="constraintMappings">
        <list>
            <ref bean="constraintMapping"/>
        </list>
    </property>
</bean>

You can then define the endpoint as:

  • Java

  • XML

  • YAML

from("jetty:http://0.0.0.0:9080/myservice?handlers=securityHandler");
<route>
    <from uri="jetty:http://0.0.0.0:9080/myservice?handlers=securityHandler"/>
    <!-- ... -->
</route>
- route:
    from:
      uri: jetty:http://0.0.0.0:9080/myservice
      parameters:
        handlers: securityHandler
      steps:
        - log:
            message: "${body}"

If you need more handlers, set the handlers option equal to a comma-separated list of bean IDs.

How to return a custom HTTP 500 reply message

You may want to return a custom reply message when something goes wrong, instead of the default reply message Camel Jetty replies to with. You could use a custom HttpBinding to be in control of the message mapping, but often it may be easier to use Camel’s Exception Clause to construct the custom reply message. For example, as show here, where we return Dude something went wrong with HTTP error code 500:

Multipart Form support

The camel-jetty component supports multipart form post out of the box. The submitted form-data are mapped into the message header. Camel Jetty creates an attachment for each uploaded file. The file name is mapped to the name of the attachment. The content type is set as the content type of the attachment file name. You can find the example here.

Jetty JMX support

The camel-jetty component supports the enabling of Jetty’s JMX capabilities at the component and endpoint level with the endpoint configuration taking priority. Note that JMX must be enabled within the Camel context to enable JMX support in this component as the component provides Jetty with a reference to the MBeanServer registered with the Camel context. Because the camel-jetty component caches and reuses Jetty resources for a given protocol/host/port pairing, this configuration option will only be evaluated during the creation of the first endpoint to use a protocol/host/port pairing. For example, given two routes created from the following XML fragments, JMX support would remain enabled for all endpoints listening on https://0.0.0.0.

  • Java

  • XML

  • YAML

from("jetty:https://0.0.0.0/myapp/myservice1/?enableJmx=true");
<from uri="jetty:https://0.0.0.0/myapp/myservice1/?enableJmx=true"/>
- from:
    uri: jetty:https://0.0.0.0/myapp/myservice1/
    parameters:
      enableJmx: true
    steps:
      - log:
          message: "${body}"
  • Java

  • XML

  • YAML

from("jetty:https://0.0.0.0/myapp/myservice2/?enableJmx=false");
<from uri="jetty:https://0.0.0.0/myapp/myservice2/?enableJmx=false"/>
- from:
    uri: jetty:https://0.0.0.0/myapp/myservice2/
    parameters:
      enableJmx: false
    steps:
      - log:
          message: "${body}"

The camel-jetty component also provides for direct configuration of the Jetty MBeanContainer. Jetty creates MBean names dynamically. If you are running another instance of Jetty outside of the Camel context and sharing the same MBeanServer between the instances, you can provide both instances with a reference to the same MBeanContainer to avoid name collisions when registering Jetty MBeans.