Camel Components

Undertow

Since Camel 2.16

Both producer and consumer are supported

The Undertow component provides HTTP and WebSocket based endpoints for consuming and producing HTTP/WebSocket requests.

That is, the Undertow component behaves as a simple Web server. Undertow can also be used as an HTTP client that means you can also use it with Camel as a producer.

Since the component also supports WebSocket connections, it can serve as a drop-in replacement for the Camel websocket component or atmosphere-websocket component.

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

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

URI format

HTTP
undertow:http://hostname[:port][/resourceUri][?options]
undertow:https://hostname[:port][/resourceUri][?options]
WebSocket
undertow:ws://hostname[:port][/resourceUri][?options]
undertow:wss://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 Undertow 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

muteException (consumer)

Whether a consumer whose exchange failed answers with status 500 without the stack trace of the exception in the response body. Set it to false to send the stack trace as text/plain, or the serialized exception when transferException is enabled on the endpoint.

true

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

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

hostOptions (advanced)

The options of the Undertow servers that the consumers listen on, one server per host and port, such as the number of threads, the buffers and the request limits. See Host Options in the documentation.

UndertowHostOptions

undertowHttpBinding (advanced)

A custom UndertowHttpBinding that maps between the Camel message and the Undertow request and response, used by every endpoint of this component that sets none of its own.

UndertowHttpBinding

allowedRoles (security)

A comma-separated list of the roles that are allowed to access the endpoints, which the UndertowSecurityProvider checks. An endpoint can set its own allowedRoles.

String

securityConfiguration (security)

The configuration object of the UndertowSecurityProvider, of a type specific to the provider. When securityProvider is not set, the component uses the first provider found with the Java ServiceLoader that accepts this configuration.

Object

securityProvider (security)

The UndertowSecurityProvider that authenticates the requests to the endpoints that set none of their own. When not set, a provider is found with the Java ServiceLoader from securityConfiguration.

UndertowSecurityProvider

sslContextParameters (security)

The SSL/TLS configuration, such as the key store and the trust store, of the endpoints that set none of their own.

SSLContextParameters

useGlobalSslContextParameters (security)

Whether the endpoints use the global SSLContextParameters of the CamelContext when sslContextParameters is not set.

false

boolean

Endpoint Options

The Undertow endpoint is configured using URI syntax:

undertow:httpURI

With the following path and query parameters:

Path Parameters

Name Description Default Type

httpURI (common)

Required The URI of the endpoint: the scheme (http, https, ws or wss), the host, the port and the path. An HTTP producer sends its requests to it. A consumer listens on its host and port and serves its path, and a WebSocket producer sends to the peers connected to its path.

URI

Query Parameters

Name Description Default Type

useStreaming (common)

Whether the message bodies are streams rather than read into memory. HTTP: the consumer gets the request body as an InputStream instead of a byte array, and writes an InputStream reply as it reads it; the producer sends an InputStream body with chunked transfer encoding, and gets the response body as an InputStream, which must be read or closed to release the connection. WebSocket: the consumer gets a text message as a Reader and a binary message as an InputStream, instead of a String and a byte array.

false

boolean

accessLog (consumer)

Whether the consumer writes an access log entry for every request, in the common log format, to the accessLogReceiver.

false

Boolean

httpMethodRestrict (consumer)

A comma-separated list of the HTTP methods that the consumer accepts, in upper case and without spaces, such as GET,POST. A request with another method gets 405 Method Not Allowed. By default, all methods are accepted.

String

matchOnUriPrefix (consumer)

Whether the consumer also serves the requests to the paths below its path, such as /foo/bar for the path /foo, and not only the requests to its exact path. A consumer with an exact or a longer matching path takes precedence.

false

Boolean

muteException (consumer)

Whether a consumer whose exchange failed answers with status 500 without the stack trace of the exception in the response body. Set it to false to send the stack trace as text/plain, or the serialized exception when transferException is enabled.

true

Boolean

optionsEnabled (consumer)

Whether HTTP OPTIONS requests are routed to the consumer. By default, the consumer answers them itself, without routing them, with 200 and an Allow header that lists the methods of the path.

false

boolean

transferException (consumer)

Whether a consumer whose exchange failed sends the exception back in the response body as a serialized Java object, with the content type application/x-java-serialized-object, instead of its stack trace as text. The exception must be serializable. Applies only when muteException is false, as it is true by default. The undertow producer does not deserialize such a response: it handles it as any other error response.

false

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

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

handlers (consumer (advanced))

A comma-separated list of the names of beans in the registry that implement CamelUndertowHttpHandler, an io.undertow.server.HttpHandler with a next handler, for example to add security. The consumer wraps its handler with them: the last one in the list is the outermost, so it handles a request first. On a WebSocket endpoint, they handle the upgrade request. Each endpoint needs its own handler beans, as the consumer sets the next handler on them.

String

cookieHandler (producer)

The cookie handler, such as InstanceCookieHandler or ExchangeCookieHandler, that stores the cookies of the responses and sends them with the next requests, to keep an HTTP session.

CookieHandler

keepAlive (producer)

Whether the producer sets the SO_KEEPALIVE socket option on its connections, so that the operating system sends TCP keep-alive probes on an idle connection. This is not HTTP keep-alive.

true

Boolean

options (producer)

Additional XNIO options of the HTTP producer, for its XNIO worker and its connections. The name is a constant of org.xnio.Options, in any case and with dashes or underscores, prefixed with option., such as option.send-buffer=8192&option.close-abort=true. An option set here takes precedence over keepAlive, tcpNoDelay and reuseAddresses. This is a multi-value option with prefix: option.

Map

preserveHostHeader (producer)

Whether the producer sends the Host header of the message as the Host header of the request, rather than the host and port of the endpoint URI, which it uses when the message has no Host header. Useful in a reverse proxy, so that the downstream server sees the host that the client called and can build correct URLs.

true

boolean

reuseAddresses (producer)

Whether the producer sets the SO_REUSEADDR socket option on its connections.

true

Boolean

tcpNoDelay (producer)

Whether the producer sets the TCP_NODELAY socket option on its connections, which disables Nagle’s algorithm so that small packets are sent without delay.

true

Boolean

throwExceptionOnFailure (producer)

Whether the producer fails the exchange with an HttpOperationFailedException when the response has a status code outside 200-299. Set it to false to get every response as the message, regardless of its status code.

true

Boolean

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

accessLogReceiver (advanced)

The Undertow AccessLogReceiver that gets the access log entries when accessLog is enabled. By default, a JBossLoggingAccessLogReceiver that logs them at INFO level in the io.undertow.accesslog category.

AccessLogReceiver

headerFilterStrategy (advanced)

To use a custom HeaderFilterStrategy to filter header to and from Camel message.

HeaderFilterStrategy

undertowHttpBinding (advanced)

A custom UndertowHttpBinding that maps between the Camel message and the Undertow request and response. The headerFilterStrategy, muteException and transferException options are not passed to a custom binding: configure them on the binding.

UndertowHttpBinding

allowedRoles (security)

A comma-separated list of the roles that are allowed to access the endpoint, which the UndertowSecurityProvider checks. When not set, the allowedRoles of the component apply.

String

oauthProfile (security)

OAuth profile name for validating incoming Authorization: Bearer tokens. When set, the HTTP request or WebSocket upgrade request is authenticated before the route is processed. This requires an OAuthTokenValidationFactory; camel-oauth provides the default implementation.

String

securityConfiguration (security)

The configuration object of the UndertowSecurityProvider, of a type specific to the provider. When securityProvider is not set, the endpoint uses the first provider found with the Java ServiceLoader that accepts this configuration.

Object

securityProvider (security)

The UndertowSecurityProvider that authenticates the requests to the endpoint. When not set, a provider is found with the Java ServiceLoader from securityConfiguration, or else the one of the component is used.

UndertowSecurityProvider

sslContextParameters (security)

The SSL/TLS configuration, such as the key store and the trust store: of the Undertow server that a consumer or a WebSocket producer uses, and of the connections of an https producer.

SSLContextParameters

fireWebSocketChannelEvents (websocket)

Whether the WebSocket consumer also routes an exchange, without a body, when a peer connects (ONOPEN) or disconnects (ONCLOSE). The event is in the websocket.eventType and websocket.eventTypeEnum headers.

false

boolean

sendTimeout (websocket)

Timeout in milliseconds when sending to a websocket channel. The default timeout is 30000 (30 seconds). A message that is not sent to a peer within the timeout fails the exchange, and the connection to that peer is closed. Use 0 for no timeout.

30000

Integer

sendToAll (websocket)

Whether the WebSocket producer sends every message to all the peers connected to the endpoint path, instead of the peers named by the websocket.connectionKey or websocket.connectionKey.list header. The websocket.sendToAll header overrides this option.

false

Boolean

Message Headers

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

Name Description Default Type

websocket.connectionKey (common)

Constant: CONNECTION_KEY

The key of the WebSocket connection (peer) that the message was received from, or that the producer sends the message to.

String

websocket.connectionKey.list (producer)

Constant: CONNECTION_KEY_LIST

The keys of the WebSocket connections (peers) that the producer sends the message to.

List

websocket.sendToAll (common)

Constant: SEND_TO_ALL

Whether the WebSocket producer sends the message to all the peers connected to the endpoint path. Takes precedence over the sendToAll option.

Boolean

websocket.eventType (consumer)

Constant: EVENT_TYPE

The type of the WebSocket event as a number: 1 when a peer connects, 0 when it disconnects.

Integer

websocket.eventTypeEnum (consumer)

Constant: EVENT_TYPE_ENUM

The type of the WebSocket event: ONOPEN when a peer connects, ONCLOSE when it disconnects.

Enum values:

  • ONOPEN

  • ONCLOSE

  • ONERROR

EventType

websocket.channel (consumer)

Constant: CHANNEL

The WebSocketChannel through which the message was received.

WebSocketChannel

websocket.exchange (consumer)

Constant: EXCHANGE

The WebSocketHttpExchange of the upgrade request, only set on the ONOPEN event.

WebSocketHttpExchange

CamelHttpResponseCode (common)

Constant: HTTP_RESPONSE_CODE

The HTTP status code: of the response that the producer received, or of the response that the consumer sends.

Integer

Content-Type (common)

Constant: CONTENT_TYPE

The Content-Type of the request or response body.

String

CamelHttpCharacterEncoding (consumer)

Constant: HTTP_CHARACTER_ENCODING

The charset that the Content-Type of the request declares, if any.

String

CamelHttpPath (common)

Constant: HTTP_PATH

Consumer: the path of the request after the path of the endpoint. Producer: a path that is appended to the path of the endpoint URI.

String

CamelHttpQuery (common)

Constant: HTTP_QUERY

Consumer: the query string of the request. Producer: the query string to send, instead of the one of the endpoint URI.

String

CamelHttpRawQuery (consumer)

Constant: HTTP_RAW_QUERY

The query string of the request in the raw form it arrived in, before URL decoding.

String

CamelHttpUrl (consumer)

Constant: HTTP_URL

The URL of the request, with the scheme, host and port, without the query string.

String

CamelAuthentication (consumer)

Constant: AUTHENTICATION

Set to Basic when the Authorization header of the request carries HTTP Basic credentials.

String

CamelRestHttpUri (producer)

Constant: REST_HTTP_URI

The URI to call, set by the REST producer. It takes precedence over the endpoint URI, and the producer removes the header when it uses it.

String

CamelRestHttpQuery (producer)

Constant: REST_HTTP_QUERY

The query string, set by the REST producer. It takes precedence over CamelHttpQuery and the query of the endpoint URI, and the producer removes the header when it uses it.

String

CamelHttpUri (common)

Constant: HTTP_URI

Consumer: the URI of the request, without the query string. Producer: only its query string is used, to choose GET when CamelHttpMethod is not set.

String

CamelHttpMethod (producer)

Constant: HTTP_METHOD

The HTTP method of the request. When it is not set, the producer sends a GET when there is a query string or no body, and a POST otherwise.

String

Host (producer)

Constant: HOST_STRING

The Host header that the producer sends when preserveHostHeader is enabled (the default).

String

Message Body

The message body at each side of the Undertow 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

bytes, null, map or text

HTTP: the request body as a byte array for POST, PUT and PATCH, null for the other methods such as GET (a body they carry is dropped); a Map of the fields of a form or a multipart request, a file as a DataHandler (also an attachment). WebSocket: a String for a text message, a byte array for a binary one, null for the events of fireWebSocketChannelEvents.

  • With useStreaming=true: stream, null or map

Not known when undertowHttpBinding is set.

Consumer reply

null, text, bytes, stream or file

HTTP: the response body: text, bytes, a stream or a file. A Map, a List or a POJO fails with an empty 200 response: marshal it first. A WebSocket consumer does not reply: send to the peers with a producer.

Producer input

null, text, bytes, stream or file

HTTP: the request body: text, bytes, a stream or a file; without the CamelHttpMethod header, a query string or no body sends a GET, and a body a POST. A Map, a List or a POJO is sent as an empty body: marshal it first. WebSocket: text and bytes or a stream to the peers connected to this endpoint, other bodies as their toString; no body sends nothing.

Producer output

bytes or unchanged

HTTP: the response body as a byte array, an empty one (not null) for a response without a body. WebSocket: the body is kept.

  • With useStreaming=true: stream or unchanged

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

Undertow HTTP and WebSocket 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("undertow:http://0.0.0.0:8080/secure?oauthProfile=myprofile")
    .to("direct:businessLogic");
<route>
  <from uri="undertow:http://0.0.0.0:8080/secure?oauthProfile=myprofile"/>
  <to uri="direct:businessLogic"/>
</route>
- route:
    from:
      uri: undertow: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. HTTP requests and WebSocket upgrade 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 before the route is invoked.

For WebSocket consumers, the token is validated during the HTTP upgrade handshake. The validation result is available on the ONOPEN event exchange when fireWebSocketChannelEvents=true, and on subsequent message exchanges for that connection; individual WebSocket messages are not revalidated. While the consumer is stopped, upgrade requests to its path are still validated, and a connection whose handshake was not validated does not receive the messages sent by producers on that path.

For HTTP consumers, automatic OPTIONS handling still runs before OAuth validation when optionsEnabled=false, so unauthenticated preflight and Allow requests keep the existing Undertow behavior. If an OPTIONS route is explicitly enabled, that route is protected by OAuth like other methods.

Custom Undertow handlers and UndertowSecurityProvider#wrapHttpHandler wrap outside the OAuth handler and can observe the original request headers before OAuth validation. The UndertowSecurityProvider#authenticate callback runs after OAuth validation and sees the request after Camel has removed the Authorization header. See the Security provider section below for how UndertowSecurityProvider is configured.

Host Options

The hostOptions component option allows configuring the underlying Undertow server. These options apply to all endpoints sharing the same host and port.

Option Type Description

workerThreads

Integer

The number of worker threads to use in the Undertow host.

ioThreads

Integer

The number of I/O threads to use in the Undertow host.

bufferSize

Integer

The buffer size of the Undertow host.

directBuffers

Boolean

Whether the Undertow host should use direct buffers.

http2Enabled

Boolean

Whether the Undertow host should use the HTTP/2 protocol.

maxEntitySize

Long

The maximum size of the HTTP entity body, in bytes. Requests with a body larger than this will be rejected.

multipartMaxEntitySize

Long

The maximum size of a multipart HTTP entity body, in bytes. Multipart requests larger than this will be rejected.

maxHeaderSize

Integer

The maximum size of an HTTP request header, in bytes. Requests with headers larger than this will be rejected.

noRequestTimeout

Integer

The amount of time in milliseconds a connection can be idle with no current requests before it is closed.

idleTimeout

Integer

The idle timeout in milliseconds after which the channel will be closed.

requestParseTimeout

Integer

The maximum time in milliseconds to parse an HTTP request.

maxParameters

Integer

The maximum number of query and path parameters that will be parsed.

maxHeaders

Integer

The maximum number of HTTP headers that will be parsed.

Configuration example:

camel.component.undertow.host-options.max-entity-size = 10485760
camel.component.undertow.host-options.max-header-size = 65536
camel.component.undertow.host-options.no-request-timeout = 30000

Usage

Message Headers

Camel uses the same message headers as the HTTP component.

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.

Message body

The consumer reads the body of a request of any method that has one (a Content-Length above 0 or a chunked body).

The body of a reply (consumer) or a request (producer) is sent as bytes. Text is written in the charset that the Content-Type declares (UTF-8 otherwise), and a number, a boolean, a character or an enum as its text. A Map, a List or an object must be marshalled first (for example with marshal().json()): the consumer answers 500 for such a reply, and the producer fails the exchange for a POST, PUT or PATCH with such a body.

The producer gives a null body for a 204 or 304 response and for the response to a HEAD request.

Using localhost as host

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 an Undertow endpoint on a specific network interface, the numerical IP address of this interface should be used as the host. If you need to expose an Undertow endpoint on all network interfaces, the 0.0.0.0 address should be used.

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

To listen across an entire URI prefix see next section.

How do I let Undertow match wildcards?

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

  • Java

  • XML

  • YAML

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

In the route above Undertow 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("undertow:http://0.0.0.0:8123/foo?matchOnUriPrefix=true").to("mock:foo");
<route>
  <from uri="undertow:http://0.0.0.0:8123/foo?matchOnUriPrefix=true"/>
  <to uri="mock:foo"/>
</route>
- route:
    from:
      uri: undertow:http://0.0.0.0:8123/foo
      parameters:
        matchOnUriPrefix: true
      steps:
        - to:
            uri: mock:foo

So now Undertow matches /foo and every path below it, such as /foo/bar.

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

  • Java

  • XML

  • YAML

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

Security provider

To plug in a security provider for endpoint authentication, implement SPI interface org.apache.camel.component.undertow.spi.UndertowSecurityProvider.

Undertow component locates all implementations of UndertowSecurityProvider using Java SPI (Service Provider Interfaces). If there is an object passed to the component as parameter securityConfiguration and provider accepts it. Provider will be used for authentication of all requests.

Once the security provider has authenticated a request, the Authorization header is removed from the message, so it is not passed on to the route. The headers that the provider adds with addHeader are set after that.

Property requireServletContext of security providers forces the Undertow server to run with servlet context, as soon as an endpoint that uses such a provider, configured on the endpoint or on the component, is started. There will be no servlet actually handled. This feature is meant only for use with servlet filters, which needs servlet context for their functionality.

WebSocket endpoints

On WebSocket endpoints (ws:// and wss://), the security provider and the allowedRoles option apply to the upgrade request that opens a connection. A request that the provider rejects, or a request to an endpoint that has allowedRoles but no security provider, is answered with the same status code as on an HTTP endpoint, and no connection is opened. The headers that the provider adds are set on every exchange of the connection.

All the endpoints of a WebSocket path share its connections, including the producers that send to its peers. The security settings of the consumer apply to the whole path, and keep applying while the consumer is stopped. On a path that only has producers, the settings of the producers apply. A connection that was opened before the current settings applied, for example while the path only had producers without security settings, does not receive the messages of the producers, and it is closed when it sends a message.

The handlers and accessLog options apply to WebSocket consumers as well, before the upgrade.

Examples

HTTP Producer Example

The following is a basic example of how to send an HTTP request to an existing HTTP endpoint.

  • Java

  • XML

  • YAML

from("direct:start")
    .to("undertow:http://www.google.com");
<route>
    <from uri="direct:start"/>
    <to uri="undertow:http://www.google.com"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: undertow:http://www.google.com

HTTP Consumer Example

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

  • Java

  • XML

  • YAML

from("undertow:http://localhost:8080/myapp/myservice")
    .to("bean:myBean");
<route>
  <from uri="undertow:http://localhost:8080/myapp/myservice"/>
  <to uri="bean:myBean"/>
</route>
- route:
    from:
      uri: undertow:http://localhost:8080/myapp/myservice
      steps:
        - to:
            uri: bean:myBean

WebSocket Example

In this sample we define a route that exposes a WebSocket service at http://localhost:8080/myapp/mysocket and returns back a response to the same channel:

  • Java

  • XML

  • YAML

from("undertow:ws://localhost:8080/myapp/mysocket")
    .transform(simple("Echo ${body}"))
    .to("undertow:ws://localhost:8080/myapp/mysocket");
<route>
  <from uri="undertow:ws://localhost:8080/myapp/mysocket"/>
  <transform><simple>Echo ${body}</simple></transform>
  <to uri="undertow:ws://localhost:8080/myapp/mysocket"/>
</route>
- route:
    from:
      uri: undertow:ws://localhost:8080/myapp/mysocket
      steps:
        - transform:
            simple: "Echo ${body}"
        - to:
            uri: undertow:ws://localhost:8080/myapp/mysocket