Questo contenuto non è disponibile nella lingua selezionata.

Chapter 241. Netty HTTP Component (deprecated)


Available as of Camel version 2.12

The netty-http component is an extension to Netty component to facilitate HTTP transport with Netty.

This camel component supports both producer and consumer endpoints.

Warning

This component is deprecated. You should use Netty4 HTTP.

Note

Stream. Netty is stream based, which means the input it receives is submitted to Camel as a stream. That means 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 data multiple times (eg: 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. Notice Netty4 HTTP reads the entire stream into memory using io.netty.handler.codec.http.HttpObjectAggregator to build the entire full http message. But the resulting message is still a stream based message which is readable once.

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

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

241.1. URI format

The URI scheme for a netty component is as follows

netty-http:http://0.0.0.0:8080[?options]

You can append query options to the URI in the following format, ?option=value&option=value&…​

Note

Query parameters vs endpoint options. You may be wondering how Camel recognizes URI query parameters and endpoint options. For example you might create endpoint URI as follows - netty-http:http//example.com?myParam=myValue&compression=true . In this example myParam is the HTTP parameter, while compression is the Camel endpoint option. The strategy used by Camel in such situations is to resolve available endpoint options and remove them from the URI. It means that for the discussed example, the HTTP request sent by Netty HTTP producer to the endpoint will look as follows - http//example.com?myParam=myValue , because compression endpoint option will be resolved and removed from the target URL. Keep also in mind that you cannot specify endpoint options using dynamic headers (like CamelHttpQuery). Endpoint options can be specified only at the endpoint URI definition level (like to or from DSL elements).

241.2. HTTP Options

A lot more options

This component inherits all the options from Netty. So make sure to look at the Netty documentation as well.
Notice that some options from Netty is not applicable when using this Netty HTTP component, such as options related to UDP transport.

The Netty HTTP component supports 7 options, which are listed below.

NameDescriptionDefaultType

nettyHttpBinding (advanced)

To use a custom org.apache.camel.component.netty.http.NettyHttpBinding for binding to/from Netty and Camel Message API.

 

NettyHttpBinding

configuration (common)

To use the NettyConfiguration as configuration when creating endpoints.

 

NettyHttpConfiguration

headerFilterStrategy (advanced)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers.

 

HeaderFilterStrategy

securityConfiguration (security)

Refers to a org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration for configuring secure web resources.

 

NettyHttpSecurity Configuration

useGlobalSslContext Parameters (security)

Enable usage of global SSL context parameters.

false

boolean

maximumPoolSize (advanced)

The core pool size for the ordered thread pool, if its in use. The default value is 16.

16

int

resolveProperty Placeholders (advanced)

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

boolean

The Netty HTTP endpoint is configured using URI syntax:

netty-http:protocol:host:port/path

with the following path and query parameters:

241.2.1. Path Parameters (4 parameters):

NameDescriptionDefaultType

protocol

Required The protocol to use which is either http or https

 

String

host

Required The local hostname such as localhost, or 0.0.0.0 when being a consumer. The remote HTTP server hostname when using producer.

 

String

port

The host port number

 

int

path

Resource path

 

String

241.2.2. Query Parameters (78 parameters):

NameDescriptionDefaultType

bridgeEndpoint (common)

If the option is true, the producer will ignore the Exchange.HTTP_URI header, and use the endpoint’s URI for request. You may also set the throwExceptionOnFailure to be false to let the producer send all the fault response back. The consumer working in the bridge mode will skip the gzip compression and WWW URL form encoding (by adding the Exchange.SKIP_GZIP_ENCODING and Exchange.SKIP_WWW_FORM_URLENCODED headers to the consumed exchange).

false

boolean

disconnect (common)

Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer.

false

boolean

keepAlive (common)

Setting to ensure socket is not closed due to inactivity

true

boolean

reuseAddress (common)

Setting to facilitate socket multiplexing

true

boolean

sync (common)

Setting to set endpoint as one-way or request-response

true

boolean

tcpNoDelay (common)

Setting to improve TCP protocol performance

true

boolean

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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

matchOnUriPrefix (consumer)

Whether or not Camel should try to find a target consumer by matching the URI prefix if no exact match is found.

false

boolean

send503whenSuspended (consumer)

Whether to send back HTTP status code 503 when the consumer has been suspended. If the option is false then the Netty Acceptor is unbound when the consumer is suspended, so clients cannot connect anymore.

true

boolean

backlog (consumer)

Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting.

 

int

bossCount (consumer)

When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty

1

int

bossPool (consumer)

To use a explicit org.jboss.netty.channel.socket.nio.BossPool as the boss thread pool. For example to share a thread pool with multiple consumers. By default each consumer has their own boss pool with 1 core thread.

 

BossPool

channelGroup (consumer)

To use a explicit ChannelGroup.

 

ChannelGroup

chunkedMaxContentLength (consumer)

Value in bytes the max content length per chunked frame received on the Netty HTTP server.

1048576

int

compression (consumer)

Allow using gzip/deflate for compression on the Netty HTTP server if the client supports it from the HTTP headers.

false

boolean

disableStreamCache (consumer)

Determines whether or not the raw input stream from Netty HttpRequest#getContent() is cached or not (Camel will read the stream into a in light-weight memory based Stream caching) cache. By default Camel will cache the Netty input stream to support reading it multiple times to ensure it Camel can retrieve all data from the stream. However you can set this option to true when you for example need to access the raw stream, such as streaming it directly to a file or other persistent store. Mind that if you enable this option, then you cannot read the Netty stream multiple times out of the box, and you would need manually to reset the reader index on the Netty raw stream.

false

boolean

disconnectOnNoReply (consumer)

If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back.

true

boolean

exceptionHandler (consumer)

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)

Sets the exchange pattern when the consumer creates an exchange.

 

ExchangePattern

httpMethodRestrict (consumer)

To disable HTTP methods on the Netty HTTP consumer. You can specify multiple separated by comma.

 

String

mapHeaders (consumer)

If this option is enabled, then during binding from Netty to Camel Message then the headers will be mapped as well (eg added as header to the Camel Message as well). You can turn off this option to disable this. The headers can still be accessed from the org.apache.camel.component.netty.http.NettyHttpMessage message with the method getHttpRequest() that returns the Netty HTTP request org.jboss.netty.handler.codec.http.HttpRequest instance.

true

boolean

maxChannelMemorySize (consumer)

The maximum total size of the queued events per channel when using orderedThreadPoolExecutor. Specify 0 to disable.

10485760

long

maxHeaderSize (consumer)

The maximum length of all headers. If the sum of the length of each header exceeds this value, a TooLongFrameException will be raised.

8192

int

maxTotalMemorySize (consumer)

The maximum total size of the queued events for this pool when using orderedThreadPoolExecutor. Specify 0 to disable.

209715200

long

nettyServerBootstrapFactory (consumer)

To use a custom NettyServerBootstrapFactory

 

NettyServerBootstrap Factory

nettySharedHttpServer (consumer)

To use a shared Netty HTTP server. See Netty HTTP Server Example for more details.

 

NettySharedHttpServer

noReplyLogLevel (consumer)

If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back.

WARN

LoggingLevel

orderedThreadPoolExecutor (consumer)

Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. See details at the netty javadoc of org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor for more details.

true

boolean

serverClosedChannel ExceptionCaughtLogLevel (consumer)

If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server.

DEBUG

LoggingLevel

serverExceptionCaughtLog Level (consumer)

If the server (NettyConsumer) catches an exception then its logged using this logging level.

WARN

LoggingLevel

serverPipelineFactory (consumer)

To use a custom ServerPipelineFactory

 

ServerPipelineFactory

traceEnabled (consumer)

Specifies whether to enable HTTP TRACE for this Netty HTTP consumer. By default TRACE is turned off.

false

boolean

urlDecodeHeaders (consumer)

If this option is enabled, then during binding from Netty to Camel Message then the header values will be URL decoded (eg %20 will be a space character. Notice this option is used by the default org.apache.camel.component.netty.http.NettyHttpBinding and therefore if you implement a custom org.apache.camel.component.netty.http.NettyHttpBinding then you would need to decode the headers accordingly to this option.

false

boolean

workerCount (consumer)

When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads2. User can use this operation to override the default workerCount from Netty

 

int

workerPool (consumer)

To use a explicit org.jboss.netty.channel.socket.nio.WorkerPool as the worker thread pool. For example to share a thread pool with multiple consumers. By default each consumer has their own worker pool with 2 x cpu count core threads.

 

WorkerPool

connectTimeout (producer)

Time to wait for a socket connection to be available. Value is in millis.

10000

long

requestTimeout (producer)

Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty’s ReadTimeoutHandler to trigger the timeout.

 

long

throwExceptionOnFailure (producer)

Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.

true

boolean

clientPipelineFactory (producer)

To use a custom ClientPipelineFactory

 

ClientPipelineFactory

lazyChannelCreation (producer)

Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started.

true

boolean

okStatusCodeRange (producer)

The status codes which are considered a success response. The values are inclusive. Multiple ranges can be defined, separated by comma, e.g. 200-204,209,301-304. Each range must be a single number or from-to with the dash included. The default range is 200-299

200-299

String

producerPoolEnabled (producer)

Whether producer pool is enabled or not. Important: Do not turn this off, as the pooling is needed for handling concurrency and reliable request/reply.

true

boolean

producerPoolMaxActive (producer)

Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit.

-1

int

producerPoolMaxIdle (producer)

Sets the cap on the number of idle instances in the pool.

100

int

producerPoolMinEvictable Idle (producer)

Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor.

300000

long

producerPoolMinIdle (producer)

Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects.

 

int

useChannelBuffer (producer)

If the useChannelBuffer is true, netty producer will turn the message body into ChannelBuffer before sending it out.

false

boolean

useRelativePath (producer)

Sets whether to use a relative path in HTTP requests. Some third party backend systems such as IBM Datapower do not support absolute URIs in HTTP POSTs, and setting this option to true can work around this problem.

false

boolean

bootstrapConfiguration (advanced)

To use a custom configured NettyServerBootstrapConfiguration for configuring this endpoint.

 

NettyServerBootstrap Configuration

configuration (advanced)

To use a custom configured NettyHttpConfiguration for configuring this endpoint.

 

NettyHttpConfiguration

headerFilterStrategy (advanced)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers.

 

HeaderFilterStrategy

nettyHttpBinding (advanced)

To use a custom org.apache.camel.component.netty.http.NettyHttpBinding for binding to/from Netty and Camel Message API.

 

NettyHttpBinding

options (advanced)

Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used.

 

Map

receiveBufferSize (advanced)

The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes.

65536

long

receiveBufferSizePredictor (advanced)

Configures the buffer size predictor. See details at Jetty documentation and this mail thread.

 

int

sendBufferSize (advanced)

The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes.

65536

long

synchronous (advanced)

Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).

false

boolean

transferException (advanced)

If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type. On the producer side the exception will be deserialized and thrown as is, instead of the HttpOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

boolean

transferExchange (advanced)

Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level.

false

boolean

decoder (codec)

Deprecated To use a single decoder. This options is deprecated use encoders instead.

 

ChannelHandler

decoders (codec)

A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup.

 

String

encoder (codec)

Deprecated To use a single encoder. This options is deprecated use encoders instead.

 

ChannelHandler

encoders (codec)

A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup.

 

String

enabledProtocols (security)

Which protocols to enable when using SSL

TLSv1,TLSv1.1,TLSv1.2

String

keyStoreFile (security)

Client side certificate keystore to be used for encryption

 

File

keyStoreFormat (security)

Keystore format to be used for payload encryption. Defaults to JKS if not set

JKS

String

keyStoreResource (security)

Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems.

 

String

needClientAuth (security)

Configures whether the server needs client authentication when using SSL.

false

boolean

passphrase (security)

Password setting to use in order to encrypt/decrypt payloads sent using SSH

 

String

securityConfiguration (security)

Refers to a org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration for configuring secure web resources.

 

NettyHttpSecurity Configuration

securityOptions (security)

To configure NettyHttpSecurityConfiguration using key/value pairs from the map

 

Map

securityProvider (security)

Security provider to be used for payload encryption. Defaults to SunX509 if not set.

SunX509

String

ssl (security)

Setting to specify whether SSL encryption is applied to this endpoint

false

boolean

sslClientCertHeaders (security)

When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range.

false

boolean

sslContextParameters (security)

To configure security using SSLContextParameters

 

SSLContextParameters

sslHandler (security)

Reference to a class that could be used to return an SSL Handler

 

SslHandler

trustStoreFile (security)

Server side certificate keystore to be used for encryption

 

File

trustStoreResource (security)

Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems.

 

String

241.3. Spring Boot Auto-Configuration

The component supports 31 options, which are listed below.

NameDescriptionDefaultType

camel.component.netty-http.configuration.allow-default-codec

  

Boolean

camel.component.netty-http.configuration.bridge-endpoint

If the option is true, the producer will ignore the Exchange.HTTP_URI header, and use the endpoint’s URI for request. You may also set the throwExceptionOnFailure to be false to let the producer send all the fault response back. The consumer working in the bridge mode will skip the gzip compression and WWW URL form encoding (by adding the Exchange.SKIP_GZIP_ENCODING and Exchange.SKIP_WWW_FORM_URLENCODED headers to the consumed exchange).

false

Boolean

camel.component.netty-http.configuration.chunked-max-content-length

Value in bytes the max content length per chunked frame received on the Netty HTTP server.

1048576

Integer

camel.component.netty-http.configuration.compression

Allow using gzip/deflate for compression on the Netty HTTP server if the client supports it from the HTTP headers.

false

Boolean

camel.component.netty-http.configuration.disable-stream-cache

Determines whether or not the raw input stream from Netty HttpRequest#getContent() is cached or not (Camel will read the stream into a in light-weight memory based Stream caching) cache. By default Camel will cache the Netty input stream to support reading it multiple times to ensure it Camel can retrieve all data from the stream. However you can set this option to true when you for example need to access the raw stream, such as streaming it directly to a file or other persistent store. Mind that if you enable this option, then you cannot read the Netty stream multiple times out of the box, and you would need manually to reset the reader index on the Netty raw stream.

false

Boolean

camel.component.netty-http.configuration.host

The local hostname such as localhost, or 0.0.0.0 when being a consumer. The remote HTTP server hostname when using producer.

 

String

camel.component.netty-http.configuration.map-headers

If this option is enabled, then during binding from Netty to Camel Message then the headers will be mapped as well (eg added as header to the Camel Message as well). You can turn off this option to disable this. The headers can still be accessed from the org.apache.camel.component.netty.http.NettyHttpMessage message with the method getHttpRequest() that returns the Netty HTTP request org.jboss.netty.handler.codec.http.HttpRequest instance.

true

Boolean

camel.component.netty-http.configuration.match-on-uri-prefix

Whether or not Camel should try to find a target consumer by matching the URI prefix if no exact match is found.

false

Boolean

camel.component.netty-http.configuration.max-header-size

The maximum length of all headers. If the sum of the length of each header exceeds this value, a TooLongFrameException will be raised.

8192

Integer

camel.component.netty-http.configuration.ok-status-code-range

The status codes which are considered a success response. The values are inclusive. Multiple ranges can be defined, separated by comma, e.g. 200-204,209,301-304. Each range must be a single number or from-to with the dash included. The default range is 200-299

200-299

String

camel.component.netty-http.configuration.path

Resource path

 

String

camel.component.netty-http.configuration.port

The port number. Is default 80 for http and 443 for https.

 

Integer

camel.component.netty-http.configuration.protocol

The protocol to use which is either http or https

 

String

camel.component.netty-http.configuration.send503when-suspended

Whether to send back HTTP status code 503 when the consumer has been suspended. If the option is false then the Netty Acceptor is unbound when the consumer is suspended, so clients cannot connect anymore.

true

Boolean

camel.component.netty-http.configuration.throw-exception-on-failure

Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.

true

Boolean

camel.component.netty-http.configuration.transfer-exception

If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type. On the producer side the exception will be deserialized and thrown as is, instead of the HttpOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk.

false

Boolean

camel.component.netty-http.configuration.url-decode-headers

If this option is enabled, then during binding from Netty to Camel Message then the header values will be URL decoded (eg %20 will be a space character. Notice this option is used by the default org.apache.camel.component.netty.http.NettyHttpBinding and therefore if you implement a custom org.apache.camel.component.netty.http.NettyHttpBinding then you would need to decode the headers accordingly to this option.

false

Boolean

camel.component.netty-http.configuration.use-relative-path

Sets whether to use a relative path in HTTP requests. Some third party backend systems such as IBM Datapower do not support absolute URIs in HTTP POSTs, and setting this option to true can work around this problem.

false

Boolean

camel.component.netty-http.enabled

Enable netty-http component

true

Boolean

camel.component.netty-http.header-filter-strategy

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers. The option is a org.apache.camel.spi.HeaderFilterStrategy type.

 

String

camel.component.netty-http.maximum-pool-size

The core pool size for the ordered thread pool, if its in use. The default value is 16.

16

Integer

camel.component.netty-http.netty-http-binding

To use a custom org.apache.camel.component.netty.http.NettyHttpBinding for binding to/from Netty and Camel Message API. The option is a org.apache.camel.component.netty.http.NettyHttpBinding type.

 

String

camel.component.netty-http.resolve-property-placeholders

Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders.

true

Boolean

camel.component.netty-http.security-configuration.authenticate

Whether to enable authentication <p/> This is by default enabled.

 

Boolean

camel.component.netty-http.security-configuration.constraint

The supported restricted. <p/> Currently only Basic is supported.

 

String

camel.component.netty-http.security-configuration.login-denied-logging-level

Sets a logging level to use for logging denied login attempts (incl stacktraces) <p/> This level is by default DEBUG.

 

LoggingLevel

camel.component.netty-http.security-configuration.realm

Sets the name of the realm to use.

 

String

camel.component.netty-http.security-configuration.role-class-name

  

String

camel.component.netty-http.security-configuration.security-authenticator

Sets the {@link SecurityAuthenticator} to use for authenticating the {@link HttpPrincipal} .

 

SecurityAuthenticator

camel.component.netty-http.security-configuration.security-constraint

Sets a {@link SecurityConstraint} to use for checking if a web resource is restricted or not <p/> By default this is <tt>null</tt>, which means all resources is restricted.

 

SecurityConstraint

camel.component.netty-http.use-global-ssl-context-parameters

Enable usage of global SSL context parameters.

false

Boolean

241.4. Message Headers

The following headers can be used on the producer to control the HTTP request.

NameTypeDescription

CamelHttpMethod

String

Allow to control what HTTP method to use such as GET, POST, TRACE etc. The type can also be a org.jboss.netty.handler.codec.http.HttpMethod instance.

CamelHttpQuery

String

Allows to provide URI query parameters as a String value that overrides the endpoint configuration. Separate multiple parameters using the & sign. For example: foo=bar&beer=yes.

CamelHttpPath

String

Camel 2.13.1/2.12.4: Allows to provide URI context-path and query parameters as a String value that overrides the endpoint configuration. This allows to reuse the same producer for calling same remote http server, but using a dynamic context-path and query parameters.

Content-Type

String

To set the content-type of the HTTP body. For example: text/plain; charset="UTF-8".

CamelHttpResponseCode

int

Allows to set the HTTP Status code to use. By default 200 is used for success, and 500 for failure.

The following headers is provided as meta-data when a route starts from an Netty HTTP endpoint:

The description in the table takes offset in a route having: from("netty-http:http:0.0.0.0:8080/myapp")…​

NameTypeDescription

CamelHttpMethod

String

The HTTP method used, such as GET, POST, TRACE etc.

CamelHttpUrl

String

The URL including protocol, host and port, etc

CamelHttpUri

String

The URI without protocol, host and port, etc

CamelHttpQuery

String

Any query parameters, such as foo=bar&beer=yes

CamelHttpRawQuery

String

Camel 2.13.0: Any query parameters, such as foo=bar&beer=yes. Stored in the raw form, as they arrived to the consumer (i.e. before URL decoding).

CamelHttpPath

String

Additional context-path. This value is empty if the client called the context-path /myapp. If the client calls /myapp/mystuff, then this header value is /mystuff. In other words its the value after the context-path configured on the route endpoint.

CamelHttpCharacterEncoding

String

The charset from the content-type header.

CamelHttpAuthentication

String

If the user was authenticated using HTTP Basic then this header is added with the value Basic.

Content-Type

String

The content type if provided. For example: text/plain; charset="UTF-8".

241.5. Access to Netty types

This component uses the org.apache.camel.component.netty.http.NettyHttpMessage as the message implementation on the Exchange. This allows end users to get access to the original Netty request/response instances if needed, as shown below. Mind that the original response may not be accessible at all times.

org.jboss.netty.handler.codec.http.HttpRequest request = exchange.getIn(NettyHttpMessage.class).getHttpRequest();

241.6. Examples

In the route below we use Netty HTTP as a HTTP server, which returns back a hardcoded "Bye World" message.

    from("netty-http:http://0.0.0.0:8080/foo")
      .transform().constant("Bye World");

And we can call this HTTP server using Camel also, with the ProducerTemplate as shown below:

    String out = template.requestBody("netty-http:http://0.0.0.0:8080/foo", "Hello World", String.class);
    System.out.println(out);

And we get back "Bye World" as the output.

241.7. How do I let Netty match wildcards

By default Netty HTTP will only match on exact uri’s. But you can instruct Netty to match prefixes. For example

from("netty-http:http://0.0.0.0:8123/foo").to("mock:foo");

In the route above Netty HTTP 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 do as follows:

from("netty-http:http://0.0.0.0:8123/foo?matchOnUriPrefix=true").to("mock:foo");

So now Netty matches any endpoints with starts with foo.

To match any endpoint you can do:

from("netty-http:http://0.0.0.0:8123?matchOnUriPrefix=true").to("mock:foo");

241.8. Using multiple routes with same port

In the same CamelContext you can have multiple routes from Netty HTTP that shares the same port (eg a org.jboss.netty.bootstrap.ServerBootstrap instance). Doing this requires a number of bootstrap options to be identical in the routes, as the routes will share the same org.jboss.netty.bootstrap.ServerBootstrap instance. The instance will be configured with the options from the first route created.

The options the routes must be identical configured is all the options defined in the org.apache.camel.component.netty.NettyServerBootstrapConfiguration configuration class. If you have configured another route with different options, Camel will throw an exception on startup, indicating the options is not identical. To mitigate this ensure all options is identical.

Here is an example with two routes that share the same port.

Two routes sharing the same port

from("netty-http:http://0.0.0.0:{{port}}/foo")
  .to("mock:foo")
  .transform().constant("Bye World");

from("netty-http:http://0.0.0.0:{{port}}/bar")
  .to("mock:bar")
  .transform().constant("Bye Camel");

And here is an example of a mis configured 2nd route that do not have identical org.apache.camel.component.netty.NettyServerBootstrapConfiguration option as the 1st route. This will cause Camel to fail on startup.

Two routes sharing the same port, but the 2nd route is misconfigured and will fail on starting

from("netty-http:http://0.0.0.0:{{port}}/foo")
  .to("mock:foo")
  .transform().constant("Bye World");

// we cannot have a 2nd route on same port with SSL enabled, when the 1st route is NOT
from("netty-http:http://0.0.0.0:{{port}}/bar?ssl=true")
  .to("mock:bar")
  .transform().constant("Bye Camel");

241.8.1. Reusing same server bootstrap configuration with multiple routes

By configuring the common server bootstrap option in an single instance of a org.apache.camel.component.netty.NettyServerBootstrapConfiguration type, we can use the bootstrapConfiguration option on the Netty HTTP consumers to refer and reuse the same options across all consumers.

<bean id="nettyHttpBootstrapOptions" class="org.apache.camel.component.netty.NettyServerBootstrapConfiguration">
  <property name="backlog" value="200"/>
  <property name="connectTimeout" value="20000"/>
  <property name="workerCount" value="16"/>
</bean>

And in the routes you refer to this option as shown below

<route>
  <from uri="netty-http:http://0.0.0.0:{{port}}/foo?bootstrapConfiguration=#nettyHttpBootstrapOptions"/>
  ...
</route>

<route>
  <from uri="netty-http:http://0.0.0.0:{{port}}/bar?bootstrapConfiguration=#nettyHttpBootstrapOptions"/>
  ...
</route>

<route>
  <from uri="netty-http:http://0.0.0.0:{{port}}/beer?bootstrapConfiguration=#nettyHttpBootstrapOptions"/>
  ...
</route>

241.8.2. Reusing same server bootstrap configuration with multiple routes across multiple bundles in OSGi container

See the Netty HTTP Server Example for more details and example how to do that.

241.9. Using HTTP Basic Authentication

The Netty HTTP consumer supports HTTP basic authentication by specifying the security realm name to use, as shown below

<route>
   <from uri="netty-http:http://0.0.0.0:{{port}}/foo?securityConfiguration.realm=karaf"/>
   ...
</route>

The realm name is mandatory to enable basic authentication. By default the JAAS based authenticator is used, which will use the realm name specified (karaf in the example above) and use the JAAS realm and the JAAS \{{LoginModule}}s of this realm for authentication.

End user of Apache Karaf / ServiceMix has a karaf realm out of the box, and hence why the example above would work out of the box in these containers.

241.9.1. Specifying ACL on web resources

The org.apache.camel.component.netty.http.SecurityConstraint allows to define constrains on web resources. And the org.apache.camel.component.netty.http.SecurityConstraintMapping is provided out of the box, allowing to easily define inclusions and exclusions with roles.

For example as shown below in the XML DSL, we define the constraint bean:

  <bean id="constraint" class="org.apache.camel.component.netty.http.SecurityConstraintMapping">
    <!-- inclusions defines url -> roles restrictions -->
    <!-- a * should be used for any role accepted (or even no roles) -->
    <property name="inclusions">
      <map>
        <entry key="/*" value="*"/>
        <entry key="/admin/*" value="admin"/>
        <entry key="/guest/*" value="admin,guest"/>
      </map>
    </property>
    <!-- exclusions is used to define public urls, which requires no authentication -->
    <property name="exclusions">
      <set>
        <value>/public/*</value>
      </set>
    </property>
  </bean>

The constraint above is define so that

  • access to /* is restricted and any roles is accepted (also if user has no roles)
  • access to /admin/* requires the admin role
  • access to /guest/* requires the admin or guest role
  • access to /public/* is an exclusion which means no authentication is needed, and is therefore public for everyone without logging in

To use this constraint we just need to refer to the bean id as shown below:

<route>
   <from uri="netty-http:http://0.0.0.0:{{port}}/foo?matchOnUriPrefix=true&amp;securityConfiguration.realm=karaf&amp;securityConfiguration.securityConstraint=#constraint"/>
   ...
</route>

241.10. See Also

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started
  • Netty
  • Netty HTTP Server Example
  • Jetty
Red Hat logoGithubRedditYoutubeTwitter

Formazione

Prova, acquista e vendi

Community

Informazioni sulla documentazione di Red Hat

Aiutiamo gli utenti Red Hat a innovarsi e raggiungere i propri obiettivi con i nostri prodotti e servizi grazie a contenuti di cui possono fidarsi.

Rendiamo l’open source più inclusivo

Red Hat si impegna a sostituire il linguaggio problematico nel codice, nella documentazione e nelle proprietà web. Per maggiori dettagli, visita ilBlog di Red Hat.

Informazioni su Red Hat

Forniamo soluzioni consolidate che rendono più semplice per le aziende lavorare su piattaforme e ambienti diversi, dal datacenter centrale all'edge della rete.

© 2024 Red Hat, Inc.